accessing current element index and modify corresponding text javascript -


i've been stuck on , have multiple select options , text beside , want modify current value of text of each of select elements.

i hope you'll have ample time see if can done or approaching differently. (fyi: current script work in progress php post sends these elements array want tinker on javascript better user experience)

<script>   function stvalue(idx) {   alert(idx);   } </script>  <select name="vopt[]" id="vopt[]" onchange="stvalue(this.prototype.indexof());">  <option value="1">one</option>  <option value="2">two</option>  <option value="3">three</option> </select> <p id="vch[]" name="vch[]">[value here]</p> <select name="vopt[]" id="vopt[]" onchange="stvalue(this.prototype.indexof());">  <option value="1">one</option>  <option value="2">two</option>  <option value="3">three</option> </select> <p id="vch[]" name="vch[]">[value here]</p> 

https://jsfiddle.net/49t9lj0d/

changes

  • replaced <p> <output>.

  • wrapped in <fieldset>.

  • added 1 eventlistener on <fieldset>.

  • removed inline event handlers on selects.

  • details of how single eventlistener replaces 3 inline event handlers in comments of source.

snippet

// reference parent of selects (i.e. <fieldset>).    var set = document.queryselector('fieldset');    /*  listen change event on form  element under <fieldset> (i.e. <select>).  */    set.addeventlistener('change', setvalue, false);    /*  event handler determine select  selected using e.target property.    after selected <select> referenced,  active <option>'s text retrieved using bracket  notation , selectedindex property.    next, method nextsibling used locate  closest <output>    textcontent used place value in  <output>    e.stoppropagation(); prevent unnecessary  event bubbling.  */    function setvalue(e) {    if (e.target != e.currenttarget) {      var selected = e.target.id;      var sel = document.getelementbyid(selected);      var text = sel.options[sel.selectedindex].text;      var target = sel.nextsibling;      target.textcontent = text;    }    e.stoppropagation();    }
select {    margin: 0 10px;  }
<fieldset>    <legend>      vopt vch    </legend>      <select id="vopt1" name="vopt1">      <option>----</option>      <option value="1">one</option>      <option value="2">two</option>      <option value="3">three</option>    </select>    <br/>    <br/>    <output id="vch1" name="vch1"></output>      <select id="vopt2" name="vopt2">      <option>----</option>      <option value="1">one</option>      <option value="2">two</option>      <option value="3">three</option>    </select>    <br/>    <br/>    <output id="vch2" name="vch2"></output>      <select id="vopt3" name="vopt3">      <option>----</option>      <option value="1">one</option>      <option value="2">two</option>      <option value="3">three</option>    </select>    <br/>    <br/>    <output id="vch3" name="vch3"></output>  </fieldset>