Home > Back-end >  How to I get value from Select Option tag using JavaScript function
How to I get value from Select Option tag using JavaScript function

Time:10-31

I have a dropdown list like this:

<select id="itemsList" onchange="gettingList()">
    <option>Please select the option</option>
    <option value="50">Soap</option>
    <option value="100">Sugar</option>
    <option value="290">Oil</option>
</select>
<br><br>

I have to get the value of the above list in the below input tag.

<input type="text" id="price">

For this, I am using this script.

<script>
    function gettingList() {
        var selectItem = document.getElementById('itemsList').value;
        var displayPrice = selectItem.options[selectItem.selectedIndex].text;
        document.getElementById('price').value = displayPrice;
    }
</script>

How can I resolve this issue.?

CodePudding user response:

You can do this:

var selectItem = document.getElementById('itemsList');

function gettingList() {
  document.getElementById('price').value = selectItem.value;
}
<select id="itemsList" onchange="gettingList()">
  <option>Please select the option</option>
  <option value="50">Soap</option>
  <option value="100">Sugar</option>
  <option value="290">Oil</option>
</select>
<br><br>
<input type="text" id="price">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You get the selected price via the select value property. now, you can update the input with it.

    function gettingList() {
    
        var selectItemPrice = document.getElementById('itemsList').value;
        document.getElementById('price').value = selectItemPrice;
    }
<select id="itemsList" onchange="gettingList()">
    <option>Please select the option</option>
    <option value="50">Soap</option>
    <option value="100">Sugar</option>
    <option value="290">Oil</option>
</select>
<br><br>

<input type="text" id="price">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

More about the select element - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select

CodePudding user response:

Your function should be like this

function gettingList() {
  let itemsList = document.querySelector('#itemsList');
  let price = itemsList.value
  let item = itemsList.options[itemsList.selectedIndex].text

  document.querySelector("#price").value = price
  document.querySelector("#item").value = item

  console.log(price, item)
}
<select id="itemsList" onchange="gettingList()">
    <option>Please select the option</option>
    <option value="50">Soap</option>
    <option value="100">Sugar</option>
    <option value="290">Oil</option>
</select>

<input placeholder="Price" type="text" id="price">
<input placeholder="Item" type="text" id="item">
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related