2016-08-11 111 views
1

我想禁用選擇框,當用戶選擇的東西。 Javascript代碼:選擇框禁用自我選擇

function desabilitar(val) { 
    $(val).attr('disabled','disabled'); 
} 

HTML:

<select class="form-control" onchange="desabilitar('mes')" id="mes" name="mes"> 

但不工作...任何幫助嗎?

+0

你爲什麼會這麼做?對於犯錯誤的用戶或使用鍵盤來選擇選項並按下向下箭頭鍵來嘗試移動選項列表的用戶來說,這會非常煩人。 – nnnnnn

回答

0

試試這個:

function desabilitar(val) { 
document.getElementById(val).disabled = true; 
} 

與jQuery相同:

function desabilitar(val) { 
    $("#" + val).attr('disabled', 'disabled'); 
} 

你想使用jQuery或JavaScript嗎?在你的問題中,你正在尋求JavaScript,但你正在使用jQuery?

+0

對不起,我想使用jquery ...我是新來的stackoverflow。工作太... –

0

您應該使用prop而不是attr,並確保您使用 '#' 選擇由ID屬性:

例子:

function desabilitar(val) { 
 
    $('#'+val).prop('disabled', true); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select class="form-control" onchange="desabilitar('mes')" id="mes" name="mes"> 
 
    <option>123</option> 
 
    <option>456</option> 
 
</select>

+0

工作thx!當prop不工作時,我改爲「attr」 –

0

您需要將"#" +添加到val之前。這將確保你正在尋找一個id爲val的元素。

function desabilitar(val) { 
 
    $("#" + val).attr('disabled', 'disabled'); 
 

 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select class="form-control" onchange="desabilitar('mes')" id="mes" name="mes"> 
 
    <option>Test 1</option> 
 
    <option>Test 2</option> 
 
    <option>Test 3</option> 
 
</select>

+0

工作太多,thx的答案! –

+0

歡迎您!繼續編程! – Wowsk

0

您需要使用#正確地獲得通過id元素,並設置殘疾人屬性,就像這樣:

function desabilitar(val) { 
$("#"+val).attr('disabled','disabled'); 

} 
+0

我忘了!但現在它起作用了。 –

+0

太棒了!我很樂意提供幫助。 JQuery需要一個#來獲取id,a。獲取類,沒有分隔符來獲取所有的某種元素類型。我相信你知道這一點,但總是很好記。 –