Sana Joseph
Sana Joseph

Reputation: 1948

Change Textbox value when an item is selected in drop down box

I'm trying to change the value of a text box with the the item I select from a drop down box. But it's not working.

I tried this HTML:

<select name="ncontacts" id="contacts" onchange="ChooseContact(this);"> 
</select>

and this JS:

function ChooseContact(data)
{
   alert(data);
   document.getElementById("friendName").value = data;
}

But the text box val is not updated.

Upvotes: 11

Views: 101302

Answers (2)

Shiv Singh
Shiv Singh

Reputation: 7211

I suggest you very simple method

$('#quantity').change(function(){
  var qty = $('#quantity').val();
  $("#totalprice").val(qty);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pricesection">
        <input type="hidden" id="productPrice" value="340"/>
    Quantity: 
    <select id="quantity">
        <option value="1" selected>1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
    </select>
Total: $
<input type="text" id="totalprice" value="1"/>

    
</div>

Upvotes: 3

James Allardice
James Allardice

Reputation: 165971

This is because this (the argument to ChooseContact) refers to the select element itself, and not its value. You need to set the value of the friendName element to the value of the select element:

document.getElementById("friendName").value = data.value; //data is the element

Here's a working example.

Upvotes: 20

Related Questions