I have my HTML: a <select>
, and a <div>
:
<select>
<option>Please select one</option>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
<div></div>
When I select an option, I want to append the being selected option value to the <div>
element. This in my js
code:
$('select').on('change', function (e){
$('div').append("//not sure how to write code here");
});
What should I add in the append()
, so that when a user select an option, it will shows up on my div
, if the user change to another option, it will update the content?
For example, if I select Volvo, "Volvo" text will show in my div
, if I change to Saab
, "Saab" text will show up in my div
to replace "Volvo"
$.append
adds new html element
inside the target
element.
Use instead $.text
. It will replace the div
content to the new value. Also use $.val
to get the current selected value from the select
tag. Note that this
refers to the select
tag
Try this:
$('select').on('change', function (e){
$('div').text($(this).val());
});
See demo:
$('select').on('change', function(e) {
$('div').text($(this).val());
});
div {
border: 1px dashed #999;
padding: 15px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option>Please select one</option>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
<div>Anything selected yet</div>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments