1

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

silvia zulinka
  • 728
  • 3
  • 18
  • 39

3 Answers3

1

With pure javascript you can do it like this create an external function and call it on change.

 <script>

        var create_p= function()
        {
            var number =document.getElementById('select').value;
            document.getElementById("add").innerHTML='<p>'+number+'</p>';
        }

        </script>
    <select id='select' onchange="create_p()">
          <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>
        <div id="add">

        </div>
henrybbosa
  • 1,139
  • 13
  • 28
1

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>
Sreekanth
  • 3,110
  • 10
  • 22
-1

First I advise you give a class or id to the <p> you want to put the text in. But the following should get you started.

$('#select').on('change', function() {
    $('p').text($('#select').val());
});
Shaun Parsons
  • 362
  • 1
  • 11
  • This is Jquery Yet silvia asked for native javascript – henrybbosa Nov 12 '16 at 07:56
  • 1
    Yes this is jQuery. And if you check his original post he did not specify he did not want jQuery. So a bit harsh to mark this down, and it is still a valid example for those with a similar query that do want to use jQuery. – Shaun Parsons Nov 12 '16 at 07:58