KyleL
KyleL

Reputation: 89

Why is the following javascript not being executed?

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">&nbsp;</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.

Upvotes: 0

Views: 2007

Answers (1)

Matthew Abbott
Matthew Abbott

Reputation: 61617

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 checkboxes approval[], not approval.

I suggest you also give them unique Ids, e.g:

<input type="radio" name="approval" id="approvalYes" value="1" />
<input type="radio" name="approval" id="approvalNo" value="0" />

Ids are used by the client, wheras the data passed back to the server uses the value of the name attribute to represent the name part of the name/value pair for each item of form data.

You could also achieve what you want with jQuery, with a simple operation:

var el = $('input[name="approval"]');
if (el.is(":checked")) {
    // One of the radio buttons has been checked.
}

Upvotes: 1

Related Questions