samedi 7 mars 2015

checkbox checked test with submit button

I've searched previous threads but non helped me with this. I know HTML5 has an option to add a "required" attr to checkboxes, which would avoid all of this, but my teacher wants us to do it anyway...


So I have a checkbox and a submit button. I want the form to submit ONLY if the checkbox is checked.


Here are my codes:



<input type="checkbox" name="check" id="test" value="unchecked" onchange="checked()" />some text here<br />
<input type="submit" onclick="check()"/>


and the JS:



function checked() { //This function changes the value of the checkbox for the next function.
if ($("#test").val() == "unchecked") {
$("#test").val("checked")
}
else {
$("#test").val("unchecked")
}
};

function check() { //This function tests if the "contact us" form should be sent.
if ($("#test").val() == "checked") {
$("#test").submit()
}
else {
alert("please agree to terms blah blah blah")
}
};


I used F12 to check the DOM of the page, and there seems to be a problem in the first function (the value of the checkbox doesn't change...)


Also I'm not sure I'm using the .submit() correctly. Will it submit to the original address I gave for the form?


Aucun commentaire:

Enregistrer un commentaire