我有两个选择字段 -wpvcountry和wpvregion。
如果wpvcountry选择了选项 1(即值为 0(,我想将wpvregion选项 1 的标签替换为文本请先选择一个国家/地区
这是我到目前为止的代码:
if ( $('select[name="wpvcountry"]').val() == 0 ) {
$('select[name="wpvregion"]').val(0).text('Please select a country first');
}
这目前只是覆盖所有选择选项,导致:
<select name="wpvregion" class="form-control">Please select a country first</select>
知道我做错了什么吗?
好的,首先我会抱怨你如何 你的代码是如何工作的
$('select[name="wpvregion"]').val(0).text('Please select a country first');
$('select[name="wpvregion"]')
- 将获得<select name="wpvregion">
元素- 当调用
.val(0)
将使<select>
选择值0或平均值选项时,将选择<option value="0">
但不获取<option value="0">
元素- 调用
.text('Please select a country first')
将在<select>...</select>
内设置新文本,<select>Please select a country first</select>
不<option>
,因为元素仍然<select>
顺便说一句,如果您需要设置<option value="0">
则需要致电
$('select[name="wpvregion"]')
.children('option[value ="0"]') //--> will get option value "0" element
.text('Please select a country first');
或
$('select[name="wpvregion"] option[value ="0"]') //--> will get option value "0" element
.text('Please select a country first');
这里演示...
countryCheck();
$('select[name="wpvcountry"]').on('change', function() {
countryCheck();
});
function countryCheck(){
if ($('select[name="wpvcountry"]').val() == "0") {
$('select[name="wpvregion"]').val('0');
$('select[name="wpvregion"] option[value ="0"]')
.text('Please select a country first');
$('select[name="wpvregion"] option').hide();
} else {
$('select[name="wpvregion"] option[value ="0"]')
.text('-');
$('select[name="wpvregion"] option').show();
//country = $('select[name="wpvcountry"]').val();
//getRegion(country); -->Get country region here
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="wpvcountry">
<option value="0">-----</option>
<option value="US">United State</option>
<option value="UK">United Kingdom</option>
<option value="JP">Japan</option>
</select>
<select name="wpvregion">
<option value="0">-</option>
<option value="Loading" disabled>Loading...</option>
</select>
试试这个:
<select name="wpvcountry" class="form-control">
<option value=0></option>
<option value=1>A</option>
<option value=2>B</option>
<option value=3>C</option>
</select>
<select name="wpvregion" class="form-control"></select>
在脚本部分中:
var val = $('select[name="wpvcountry"]').val();
if (val == 0) {
$('select[name="wpvregion"]').html('<option value=0>Please select a country first</option>');
}
我想你想要这个
$('select[name="wpvcountry"]').change(function(){
if ( $(this).val() == '0' ) {
$('select[name="wpvregion"]').prepend("<option value='0'>Please select a country first</option>");
}
});