Reputation: 688
I am trying to loop through all the elements in a form to make sure if any element is empty, then my submit button is still in disabled state( initial on load i am disabling it), else if all the input values are entered then Submit button is enabled.
Here is my onKeyup function for the form, but this code isn't working and is not looping through the elements.$(this) always returns 'formId' instead of looping through its elements
function formkeyup() {
var empty = false;
$('#formId').each(function () {
if ($(this).val() === '') {
empty = true;
}
});
if (empty) {
$('#SubmitId').attr('disabled', 'disabled');
} else {
$('#SubmitId').removeAttr('disabled');
$("#SubmitId").css('font-weight', 'bold');
}
}
MY HTML code:
<form action="~/Home/About" method="post" data-ajax="false" id="formId" onkeyup="formkeyup();">
<fieldset>
<legend>Registration Form</legend>
<div class="section">
<h3>Step 1: Password</h3>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
<input type="password" name="pwd" id="pwd" autocomplete="off" value="@Model.Password" onkeyup=" return Validate() "/>
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
<input type="password" name="confirmpwd" id="confirmpwd" autocomplete="off" value="@Model.ConfirmPwd" onkeyup=" return Validate() "/>
</li>
</ol>
</div>
<div id="divSection2" class="section">
<h3>Step 2: Age</h3>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
</div>
<p>
<input type="button" id="SubmitId" name="SubmitId" value="Submit" />
</p>
</fieldset>
</form>
Any help on this is much appreciated!
Thanks,
WH
Upvotes: 0
Views: 483
Reputation: 302
Your usage of the $.each function is invalid. You need to pass the elements you want to actually loop through to the $.each() function.
$.each('input', function() {
**validation code here**
});
Or you could give each input/textarea a classname and loop through all of those.
$('#formID').each('.input', function() {
**validation code here**
});
JSFiddle example.
Upvotes: 3