Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 768
Sana Joseph Avatar asked Apr 24 '12 15:04

Sana Joseph


2 Answers

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>
like image 73
Shiv Singh Avatar answered Nov 12 '22 22:11

Shiv Singh


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.

like image 20
James Allardice Avatar answered Nov 12 '22 21:11

James Allardice