I am trying to make a Jquery simple function and just want to submit a form only when the radio button value is "1". If not don't submit the form and change some things as I am showing in the code below.
At the moment if the value of the radio button is "1" or "0" the form is submitting anyway.
<script>
$(document).ready(function() {
$('.result').hide();
$('input.prettycheckbox').prettyCheckable({});
$('input.submit').on('click', function(e) {
e.preventDefault();
$('input.prettycheckbox').each(function(){
if ($(this).is(':checked') && $(this).is('input[value="0"]')) {
$(this).attr("disabled", true);;
$('.result').show();
$('.advise').hide();
$(this).parent().parent().addClass('incorrect');
} else {
$('form').submit();
};
});
});
});
</script>
Thanks a lot!
Never a good idea to attach events to a submit button - instead use the form's submit event
$(function() {
$('.result').hide();
$('input.prettycheckbox').prettyCheckable({});
$('form').on('submit', function(e) { // use #formid if you have it
var ok = false;
$('input.prettycheckbox').each(function(){
if ($(this).is(':checked') && $(this).is('input[value="0"]')) {
ok=true; // or other reason
$(this).attr("disabled", true);;
$('.result').show();
$('.advise').hide();
$(this).parent().parent().addClass('incorrect');
} // seems to have been missing
});
if (!ok) { // if not ok to submit, THEN preventDefault
e.preventDefault();
}
});
});
bind form to submit event then manually check each checkbox using
<script>
$(document).ready(function() { $('.result').hide();
$('input.prettycheckbox').prettyCheckable({});
$('form.form_class').on('submit', function(e) {
e.preventDefault();
var chkbx = $('input.prettycheckbox');
var ret = new Array(chkbx.length);
for (var i = 0; i < chkbx.length; i++)
{
if ($(this).is(':checked') && $(this).is('input[value="0"]'))
{
$(this).attr("disabled", true);;
$('.result').show();
$('.advise').hide();
$(this).parent().parent().addClass('incorrect');
return false;
continue;
}
}
return true
});
});
</script>
To simplify; override the form submit event and only prevent if the radio value is not 1.
HTML:
<form method="post" target="">
<input type="radio" name="mandatory" value="0" />Selecting me won't work<br />
<input type="radio" name="mandatory" value="1" />You must select me<br />
<input type="submit" class="submit" value="Submit" />
<form>
jQuery:
$(document).ready(function () {
$('form').on('submit', function (e) {
if( $('input[name=mandatory]:checked').val()!= 1)
{
e.preventDefault();
}
});
});
See fiddle