This question already has an answer here:
I have a form
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br />
Password<br />
<input type="password" id="pass_input" name="password" /><br />
Confirm Password<br />
<input type="password" id="v_pass_input" name="v_password" /><br />
Email<br />
<input type="text" id="email" name="email" /><br /> <br/>
<textarea name="adress" id="adress" ></textarea>
<br>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female<br>
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
I want to disable my submit button until all the fields have values.Now everything is okay except radio button.
JS:
<script>
(function() {
$('form > input,textarea,radio').keyup(function() {
var empty = false;
$('form > input,textarea,radio').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
</script>
I don't know whether this is good code or not.I am totally new to jquery so please correct me i had make anything wrong. I want to disable my submit button until all the fields have values including radio button..Please help me.Thanks in advance
</div>
You need to use prop()
and check the type
. If the type is radio
, you can add validation checks:
required = function(fields) {
var valid = true;
fields.each(function() { // iterate all
var $this = $(this);
if ((($this.is(':text') || $this.is('textarea')) && !$this.val()) || // text and textarea
($this.is(':radio') && !$('input[name=' + $this.attr("name") + ']:checked').length)) { // radio
valid = false;
}
});
return valid;
}
validateRealTime = function() {
var fields = $("form :input");
fields.on('keyup change keypress blur', function() {
if (required(fields)) {
{
$("#register").prop('disabled', false);
}
} else {
{
$("#register").prop('disabled', true);
}
}
});
}
validateRealTime();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br /> Password
<br />
<input type="password" id="pass_input" name="password" /><br /> Confirm Password<br />
<input type="password" id="v_pass_input" name="v_password" /><br /> Email
<br />
<input type="text" id="email" name="email" /><br /> <br/>
<textarea name="adress" id="adress"></textarea>
<br>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female<br>
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
</div>
You can check if a radio button is checked or not using:
if (!$("input[name='gender']:checked").val()) {
alert('Nothing is checked!');
} else {
alert('One is checked');
}