silvia zulinka silvia zulinka - 25 days ago 5
Javascript Question

How to add element in javascript with value option selected

I want to add element

<p>
with value option selected.



<select id='select'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="selected">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>

<p>text</p>
<p>text</p>
<p>text</p>





if I select 4, element
<p>
will appear 4
<p>
element.

how to make it using nativ javascript? not jquery

Answer

If you are looking for plain JS implementation, here is what you could do.

document.addEventListener("DOMContentLoaded", function() {
  let selectEle = document.querySelector("#select");

  function setVal() {
    let val = selectEle.options[selectEle.selectedIndex].value;
    document.querySelector("p").innerText = val;
  }

  selectEle.addEventListener("change", function(event) {
    setVal();
  });
  setVal();
});
<select id='select'>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3" selected="selected">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<p>text</p>