I’m new to web programming and I have the following form that I wish to validate.
<form name="feature_request_view" action="FeatureRequestView.php" method="post" onsubmit="return validateAllFields()">
<p id="errorMsg" style="color:red"> </p>
<div class="noboder">
<label for="approval">* Approve the feature request?:</label>
<input type="radio" name="approval[]" id="approval" value="1" /> Yes
<input type="radio" name="approval[]" id="approval" value="0" /> No
*
</div>
<div class="button-style">
<input type="submit" value="Submit" />
</div>
</form>
The javascript code is as follows:
<script type="text/javascript" src="../validation.js"></script>
<script type="text/javascript">
function validateAllFields()
{
var approval = document.getElementsByName("approval");
var errors = document.getElementById("errorMsg");
errors.innerHTML = "";
if(checked(approval, errors, "Please choose an option to approve/disapprove the feature request."))
{
window.alert("got in the if block");
errors.innerHTML = "Your decision has been submitted.";
return true;
}
return false;
}
</script>
And the checked function that I used is:
function checked(element, error, msg) {
var boxchecked = false;
for (i = 0; i < element.length; i++) {
if (element[i].checked) {
boxchecked = true;
}
}
if (boxchecked) {
return true;
}
else {
error.innerHTML = msg;
return false;
}
}
My problem is that the code never executes the javascript and therefore by passing it even though the radio buttons have not been filled in and it begins to execute some php that i used to populate a table. Please help! Thanks in advance.
I would imagine your first issue is that you are using
getElementsByName, and not passing in the correct name, e.g. you have named your checkboxesapproval[], notapproval.I suggest you also give them unique Ids, e.g:
Ids are used by the client, wheras the data passed back to the server uses the value of the
nameattribute to represent thenamepart of thename/valuepair for each item of form data.You could also achieve what you want with jQuery, with a simple operation: