[英]Toggle Disabled attribute and show/hide at same time in jQuery
我正在嘗試在多部分表單上使用jQuery.Validate,該表單需要顯示和隱藏一些內容並禁用不在視圖中的輸入。 基本上,如果用戶單擊按鈕切換附加輸入,則會顯示該輸入,以便他們可以輸入數據。 但是直到它顯示我需要保持它被禁用,以便jquery.validate將忽略它。 到目前為止,我發現了一個簡單的腳本,它將切換禁用的屬性,我可以根據需要顯示/隱藏輸入,但我需要它們一起工作。 是否有一種簡單的方法可以在切換屬性時顯示/隱藏輸入?
這是一個小提示,顯示我現在擁有的東西,它可以工作,但我必須在第一次兩次單擊#toggleDisabled按鈕:
這是我正在使用的函數邏輯:
(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();
});
});
這是簡單的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>
$.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();
}
});
};
也可以通過.prop()vs .attr()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.