OPK OPK - 3 months ago 19
HTML Question

How to dynamically append selected option to a div and update if selected option is changed?

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"

Answer Source

$.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 JSFiddle demo