[英]Deactivate the 'Submit' button for the selected value in dropdown menu
我搜索了論壇並遇到了那個帖子,但它對我不起作用。 如果我錯過了什么,請指點我。
我在其中一個網站上有一個下拉菜單,當我顯示默認選擇值時,我想停用“提交”按鈕,因為人們只需點擊“提交”並最終進入404頁面。
我是Javascript的傻瓜,所以如果有人可以提供幫助真的很棒。
這是我的HTML:
<div class="optin_box">
<h3 style="color:#fff !important;">Box Title</h3>
<p class="optin_text">Select your city:</p>
<form name="redirect">
<select name="selection">
<option>My city</option>
<optgroup label="Area 1">
<option value="http://domain.com">City 1</option>
<option value="http://domain2.com">City 2</option>
<option value="http://domain3.com">City 3</option>
</optgroup>
<optgroup label="Area 2">
<option value="domain4.com">City 4</option>
<option value="domain5.com">City 5</option>
</optgroup>
</select>
<br/>
<input class="button_link hover_fade red button_widget" style="font-size:14px;" type=button value="SUBMIT" onClick="WinOpen();">
</form>
</div>
這是我的一些JavaScript:
<script language="JavaScript">
function WinOpen() {
var url=document.redirect.selection.value
document.location.href=url
}
</script>
所以我想要實現的是當有人在下拉列表中看到“我的城市”時,應該停用“提交”按鈕。
在此先感謝您的幫助。 吉
如果你使用jquery(必須包含lib)
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
為方便起見,請在下拉列表中設置ID
<select id="myselect" name="selection">
也在你的提交按鈕上
<input id="mybutton" .... />
然后使用jquery檢測選擇的更改
$('#mysselect').change(function() {
if($('#mysselect').val() === 'My City') {
$('#mybutton').prop( "disabled", true);
}
});
這里有一些腳本可以使用您已經包含在頁面中的現有jQuery庫來執行您想要的操作。 只需包含此腳本,它將最初禁用該按鈕,然后處理選擇更改。
(function($) {
$(function() {
$("select[name=selection]").on("change", function() {
$(this).closest("form")
.find("input.button_link")
.prop("disabled", $(this).val() == "#");
})
.trigger("change");
});
})(jQuery);
注意:這假定您將值#
添加到select中的初始選項,正如您之前提到的那樣。
首先,為<select>
和Submit按鈕指定ID:從JS訪問它們會更容易。 其次,添加onChange事件監聽器以了解用戶何時更改了丟棄框。
<select name="selection" id="mySelect" onchange="checkSelect();">
...
<input class="button_link hover_fade red button_widget" style="font-size:14px;" type=button value="SUBMIT" onClick="WinOpen();" id="mySubmit">
然后在用戶更改時檢查值:
function checkSelect()
{
// Let domain5.com be wrong
if (document.getElementById('mySelect').value == 'domain5.com'))
document.getElementById('mySubmit').disabled = true;
else
document.getElementById('mySubmit').disabled = false;
}
它將是純粹的JS。 您可以像其他人所說的那樣使用jQuery。
有一種替代方法,可以將this
用作發送到函數的參數。 然后你不需要解析DOM。 感謝Archer的建議。
HTML將是這樣的:
<select name="selection" onchange="checkSelect(this);">
JS將改為:
function checkSelect(element)
{
// Let domain5.com be wrong
if (element.value == 'domain5.com')
document.getElementById('mySubmit').disabled = true;
else
document.getElementById('mySubmit').disabled = false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.