2013-04-18 44 views
4

我正在尋找如何在選中複選框時禁用窗體上的所有其他輸入。我現在有一半,但當我的問題是當我點擊複選框時,它會與其他元素一起禁用它。我只想要其他元素變得殘疾。選擇表單中的所有其他字段

http://jsfiddle.net/rockitdev/8TF2a/3/

<form action="#" method="post"> 

<div> 
    <label for="checkbox">Checkbox:</label> 
    <input type="checkbox" name="checkbox" id="checkbox" /> 
</div> 

<div> 
    <label for="name">Text Input:</label> 
    <input type="text" name="name" id="name" value="" tabindex="1" /> 
</div> 

<div> 
    <h4>Radio Button Choice</h4> 

    <label for="radio-choice-1">Choice 1</label> 
    <input type="radio" name="radio-choice-1" id="radio-choice-1" tabindex="2" value="choice-1" /> 

    <label for="radio-choice-2">Choice 2</label> 
    <input type="radio" name="radio-choice-2" id="radio-choice-2" tabindex="3" value="choice-2" /> 
</div> 

<div> 
    <label for="select-choice">Select Dropdown Choice:</label> 
    <select name="select-choice" id="select-choice"> 
     <option value="Choice 1">Choice 1</option> 
     <option value="Choice 2">Choice 2</option> 
     <option value="Choice 3">Choice 3</option> 
    </select> 
</div> 

<div> 
    <label for="textarea">Textarea:</label> 
    <textarea cols="40" rows="8" name="textarea" id="textarea"></textarea> 
</div> 



<div> 
    <input type="submit" value="Submit" /> 
</div> 

$('#checkbox').click(function() { 
    var $this = $(this); 
    // $this will contain a reference to the checkbox 
    if ($this.is(':checked')) { 
     $('input:not(this)').attr("disabled", true); 
    } else { 

    } 
}); 
+0

我想看看這裏: [HTTP://計算器。 COM /問題/ 3419159 /如何對GET-所有兒童控制對的一窗口表單形式對的一特定型按鈕(http://stackoverflow.com/questions/3419159 /如何獲取所有兒童控制的窗口形式的特定類型的按鈕) – Glimpse

回答

1
$('#checkbox').change(function(e){ 
    var $form = $(this).closest('form'); // locate the form we're referring to 
    // alternative method: var $form = $(this.form);  

    $form.find(':input') // grab all input elements (buttons, inputs, select lists, etc.) 
    .not(this) // exclude this checkbox 
    .attr('disabled', !this.checked); // mark these elements as disabled 
             // based on the checkbox value 
}); 

使用.not()排除在選擇當前元素。如果用戶決定通過表單製表符,我建議綁定到change而不是click

此外,jsFiddle(雖然在演示中,我引用this.form關閉input element,但你可以保留在我上面的例子中,$form了。)

+0

偉大的+1爲解釋:) –

+0

@downvoter:請評論? –

相關問題