1

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:

JS Fiddle

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> 
isaac weathers
  • 1,436
  • 4
  • 27
  • 52

1 Answers1

4

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()

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • That works but it works like I have it already where I have to hit the #toggleButton button twice for it to work. After the first initialization it works, but the first one fails. Any idea why? – isaac weathers Feb 20 '14 at 04:51
  • @isaacweathers, See http://jsfiddle.net/G7jDK/5/ I have added `disabled` attribute to input text. It was working in the first instance also. Problem when `disabled` attribute was not defined, #toggleInput was not disabled so when you click it disables #toggleInput and the hides already hidden #toggleInput thus it seems that it was not working – Satpal Feb 20 '14 at 04:57