【发布时间】:2021-06-23 22:37:25
【问题描述】:
我编写了一个地址表单,它使用 API 将国家/地区拉入一个选择输入,然后 jQuery/ajax 将相关的州/地区填充到另一个选择输入。除非某些国家/地区没有可使用的州/地区(奥兰群岛),否则这可以正常工作。在这些情况下,我不得不包含一个“其他状态”字段,因此我将其替换为文本输入。
我的问题是当我选择不同的国家时;如果我选择一个没有州/地区的国家/地区,它会切换到文本输入,但一旦我选择了另一个国家,它就不会切换回来。
jQuery:
$("#inputCountry").on('change', function () {
$.getJSON("ajax/changecountry?country=" + $(this).val(), function (data) {
})
.then(function (data) {
var string = '';
$.each(data, function (i, o) {
string += '<option value="' + i + '">' + i + '</option>';
});
if (string !== '') {
$('#inputState').html(string);
} else {
$('#inputState').replaceWith('<input id="inputOtherstate" placeholder="State or Region" type="text" class="form-control" name="other-state" />');
}
})
.then(function () {
$('#inputState').val($('#userstate').val());
});
}).change();
字段:
<div class="col-md-3">
<label for="inputCountry" class="form-label">Country</label>
<select class="form-select" aria-label="Address Country" id="inputCountry" name="country">
<?php
foreach ($countries as $name => $code) {
echo ($code==='US') ? '<option value="' . $code . '" selected>' . $name . '</option>' : '<option value="' . $code . '">' . $name . '</option>';
}
?>
</select>
</div>
<div class="col-md-3">
<label for="inputState" class="form-label">State</label>
<select class="form-select" aria-label="Default select example" id="inputState" name="state">
<option selected>Select a country...</option>
</select>
<input type="hidden" id="userstate" value="<?= isset($user['state']) ? $user['state'] : '' ?>" />
</div>
【问题讨论】:
标签: jquery