Reputation: 1472
I'm trying to use jQuery.Validate on a multi-part form that requires showing and hiding some content and disabling the inputs that are not in view. Basically, if the user clicks on the button to toggle the additional input, it then shows so that they can enter data. But until it shows I need to keep it disabled so that jquery.validate will ignore it. Thus far I found a simple script that will toggle the disabled attribute and I can show/hide the input as needed but I need them to work together. Is there a simple way to have the input show/hide while toggling the attribute as well?
Here is a fiddle that shows what I have right now and it works but I have to click the #toggleDisabled button twice the first time:
Here is the function logic I am using:
(function($) {
$.fn.toggleDisabled = function() {
return this.each(function() {
var $this = $(this);
if ($this.attr('disabled')) $this.removeAttr('disabled').show();
else $this.attr('disabled', 'disabled').hide();
});
};
})(jQuery);
$(function() {
$('#toggleButton').click(function() {
$('#toggleInput').toggleDisabled();
});
});
And here is the simple HTML:
<form id="myform">
<input type="text" name="field1" /> <br/>
<br /> <input type="text" id="toggleInput" name="toggleInputName" style="display:none" />
<input type="button" id="toggleButton" value="Toggle Disabled" />
<input type="submit" />
</form>
Upvotes: 1
Views: 8587
Reputation: 133403
Use .prop() instead of .attr()
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this);
if ($this.prop('disabled')) {
$this.prop('disabled', false).show();
} else {
$this.prop('disabled', true).hide();
}
});
};
DEMO, You can try shorter form here
Also go through .prop() vs .attr()
Upvotes: 4