[英]Toggle Disabled attribute and show/hide at same time in jQuery
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. 我正在尝试在多部分表单上使用jQuery.Validate,该表单需要显示和隐藏一些内容并禁用不在视图中的输入。 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.
但是直到它显示我需要保持它被禁用,以便jquery.validate将忽略它。 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: 这是一个小提示,显示我现在拥有的东西,它可以工作,但我必须在第一次两次单击#toggleDisabled按钮:
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: 这是简单的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>
Use .prop() instead of .attr() 使用.prop()代替.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 DEMO ,您可以在这里尝试更短的形式
Also go through .prop() vs .attr() 也可以通过.prop()vs .attr()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.