输入状态字段取决于下拉选择



需要完成:当用户选择CA以外的任何内容时,请在我下面的通知中打印所选状态。

<div class="row mt-3">
<div class="col-md">
<label for="resident">I am a resident of:</label>
<div class="invalid-feedback">
Select state of residence.
</div>
</div>
</div>
<div class="row mt-3">
<div class="col-md">
<div class="alert alert-danger">
This feature is not available at this time for <b>[State]</b> residents.
</div>
</div>
</div>

以下是打印状态的部分:

<option value="<?= $abbr; ?>"><?= $state; ?></option>

我如何能够根据下拉选择的内容在 [状态] 部分内打印出来?

正如@Martinho所说,向<b>添加 id 可以更轻松地更改值 - 我还在警告本身中添加了一个,以便您可以轻松地隐藏/显示它,以及添加内联样式以在加载时隐藏警告

您可以在选择上使用 eventListener 来侦听change事件 - 每次触发事件时,我们都会使用 if 语句来检查所选值是否为 'CA',然后更新相应的元素(如果是,则隐藏警告,如果不是,则显示带有正确文本的警告(

document.getElementById('resident').addEventListener('change', function() {
if (this.value !== 'CA') {
document.getElementById('stateWarning').style.display = 'block';
document.querySelector('#stateWarning b#stateName').textContent = this.value;
} else {
document.getElementById('stateWarning').style.display = 'none';
}
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript" ></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js" type="text/javascript" ></script>
<div class="row mt-3">
<div class="col-md">
<label for="resident">I am a resident of:</label>
<select class="custom-select" id="resident" required>
<option value="">Choose...</option>
<option value="CA">CA</option>
<option value="MT">MT</option>
<option value="TX">TX</option>
<option value="WA">WA</option>
</select>
<div class="invalid-feedback">
Select state of residence.
</div>
</div>
</div>
<div class="row mt-3">
<div class="col-md">
<div id="stateWarning" class="alert alert-danger" style="display: none;">
This feature is not available at this time for <b id="stateName">[State]</b> residents. For more information about our privacy practices, please visit our <a href="<?= $config->get_url('policy'); ?>" target="_blank">privacy policy</a>.
</div>
</div>
</div>

你可以简单地使用JQuery来实现你想要的。

但首先你应该为你的"b"标签分配一个id,以简化代码。让我们假设 id 是"状态"。

$("#resident").change(function(){
if($(this).val() != 'CA'){
$("#state").text($(this).val());
}
})

希望这有帮助!

最新更新