此处默认加载状态下拉列表
我的国家下拉列表是
<select id="countrydrp" name="countrydrp" class="required" onchange="changeStateType();">
<option value="">Select State</option>
<option value="US">USA</option>
<option value="IN">INDIA</option>
//some more options
</select>
我的状态下拉是
<select id="statedrp" name="statedrp" style="width: 80px; padding: 5px; height: 30px; width: 215px;" class="" onchange="validteSelected();">
<option value="">Select State</option>
<option value="AK">Alaska</option>
<option value="AL">Alabama</option>
//some more options
</select>
<input type="text" id="statetxt" name="statetxt" class="text" data-error-type="inline" />
如果用户从国家/地区下拉列表中选择除美国以外的选项
我正在尝试隐藏状态下拉菜单并将文本框显示为给定
我的剧本
$(document).ready(function () {
$("#statetxt").hide();//i am hiding the textbox on page loads
});
function changeStateType() {
debugger;
var selVal = $("#countrydrp option:selected").val();
if (selVal == "US") {
$("#statetxt").hide();
$("#statedrp").show();
$("#statedrp").addClass("required");
}
else {
$("#statetxt").show();
$("#statedrp").hide();
$("#statetxt").addClass("required");
}
}
现在问题在我选择任何国家/地区选项
之后都显示了 如果我选择Tunsia(美国除外),则会显示下拉列表和文本框
如果我选择美国则会显示两个下拉列表
答案 0 :(得分:4)
答案 1 :(得分:2)
我认为你正在寻找这个:
$("#countrydrp").on("change", function() {
//hide state if country is different than US
$("#statedrp").toggle($(this).val() == "US");
//show input text if country is different than US
$("#statetxt").toggle($(this).val() != "US");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="countrydrp" name="countrydrp" class="required" onchange="changeStateType();">
<option value="">Select State</option>
<option value="US">USA</option>
<option value="IN">INDIA</option>
</select>
<select id="statedrp" name="statedrp" style="width: 80px; padding: 5px; height: 30px; width: 215px;" class="" onchange="validteSelected();">
<option value="">Select State</option>
<option value="AK">Alaska</option>
<option value="AL">Alabama</option>
</select>
<input type="text" id="statetxt" name="statetxt" class="text" data-error-type="inline" />
&#13;
答案 2 :(得分:0)
使用以下方式获取值:
var selVal = $("#countrydrp").val();
不是这个:
var selVal = $("#countrydrp option:selected").val();// this will also give the same value but not a good one to apply .val();
我看到你的代码已经正常工作,只需删除调试器;
function changeStateType() {
var selVal = $("#countrydrp option:selected").val();
if (selVal == "US") {
$("#statetxt").hide();
$("#statedrp").show();
$("#statedrp").addClass("required");
}
else {
$("#statetxt").show();
$("#statedrp").hide();
$("#statetxt").addClass("required");
}
}