YellowBerry YellowBerry - 1 month ago 12
jQuery Question

Form Validation not working as expected

I have made a cart-mechanism using PHP and done validation with the help of JavaScript and the validation is not working.

This is my actual php script:

$result = mysqli_query($conn, "SELECT * FROM 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 this is my validation in javascript:

function validateAll(){
if( document.tocart.qty_input[0].value == "" ){
alert("Please enter a valid number");
document.tocart.qty_input.focus();
return false;
}


When I hit submit nothing works.

Answer Source

You can make a form object like var qty_input= form["qty_input[your---index]"]; and just call it as a parameter in your onsubmit button, like return validateAll(this); and we are using this as a reference for the dominant object in the function.