javascript - Form Validation not working as expected -
i have made cart-mechanism using php , done validation of javascript , validation not working.
this actual php script:
$result = mysqli_query($conn, "select * products"); while($row = mysqli_fetch_array($result)){ $fieldidval[] = $row['product_id']; $fieldnameval[] = $row['product_name']; $fieldcostval[] = $row['product_cost']; $fieldimgval[] = $row['product_image']; $fielddescval[] = $row['product_description']; } //printing field values for($i = 0; $i < mysqli_num_rows($result); $i++){ echo "<tr><form action = 'cart.php?pid=" . $fieldidval[$i] . "&name=" .$fieldnameval[$i] . "&cost=" . $fieldcostval[$i] . "' method = 'post' name = 'tocart' onsubmit = 'return(validateall());'><td>" . $fieldnameval[$i] . "</td><td>" . $fieldcostval[$i] . "</td><td>" . $fieldimgval[$i] . "</td><td>" . $fielddescval[$i] . "</td><td><input type = 'text' name ='qty_input[$i]' ></td><td><input type = 'submit' name = 'submit'></td></form></tr>"; }
and validation in javascript:
function validateall(){ if( document.tocart.qty_input[0].value == "" ){ alert("please enter valid number"); document.tocart.qty_input.focus(); return false; }
when hit submit nothing works.
converting comment answer
if keep inline submit handler, pass form using this
onsubmit = 'return validateall(this);'
then can access form directly in handler without having use longer document.formname
function validateall(form) { // "this" -> whatever in (....) here var qty_input= form["qty_input[0]"]; if (qty_input.value == "") { alert("please enter valid number"); qty_input.focus(); return false; } }
here better way using unobtrusive code
window.onload=function() { // when page loads. can use event listener document.queryselector("[name=tocart]").onsubmit=function() { var qty_inputs = document.queryselectorall("[name^=qty_input]"); // starts (var i=0;i<qty_inputs.length;i++) { if (qty_inputs[i].value == "") { alert("please enter valid number"); qty_inputs[i].focus(); return false; } } } }
and can avoided using
<input type = 'text' name ='qty_input[$i]' required />
Comments
Post a Comment