Need to accomplish: When a user selects anything other than CA, print the selected state inside the notice that I have below.
<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>Here is the portion that prints out the states:
<option value="<?= $abbr; ?>"><?= $state; ?></option>
How would I be able to target to print it out inside the [State] portion depending on what the drop-down selection is?
Advertisement
Answer
As @Martinho said, adding an id to the <b> makes changing the value a lot easier – I’ve also added one to the warning itself so you can easily hide / show it, as well as adding an inline style to hide the warning on load
You can use an eventListener on the select to listen for the change event – Each time the event is fired, we’ll use an if statement to check if the selected value is ‘CA’ or not, and then update the appropriate elements ( Hide the warning if it is, display the warning with the correct text if not )
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>