IMB
IMB

Reputation: 15909

Copy dropdown menu's data to text box on select?

Let's say you have this dropdown menu:

<select>
   <option value="10">Apple</option>
   <option value="20">Orange</option>
</select>

<input type="name" />
<input type="price" />

If user selects "Orange" from the dropdown menu, the textboxes' values should be:

<input type="name" value="Orange" />
<input type="price" value="20" />

or if it was "Apple", then textboxes' values should be Apple and 10.

Is this possible with Jquery or Jquery Mobile, if yes how?

Upvotes: 1

Views: 3118

Answers (4)

MikeB
MikeB

Reputation: 2452

I think you are a little confused with types of inputs. This MDN link will help.

If I understand you correctly, you want to take the value and the label from the select and store them in a corresponding textbox. Here is my solution:

HTML:

<select id="fruit">
   <option></option>
   <option value="10">Apple</option>
   <option value="20">Orange</option>
</select>

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

jQuery:

$("#fruit").change(function() {
     var name = $(this).find(":selected").text();
     var price =  $(this).val();
     $("#name").val(name);
     $("#price").val(price);
});

Note that this jQuery only binds the fruit select for the onchange instead of binding all select

Upvotes: 2

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17380

jQuery:

$("#s").on("change",function(){
    $("#text").val($(this).children().filter("option:selected").text());
    $("#price").val($(this).val());
});

Markup:

<select id="s">
   <option value="10">Apple</option>
   <option value="20">Orange</option>
</select>

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

jsFiddle: http://jsfiddle.net/hescano/NnsDt/

Upvotes: 2

PSL
PSL

Reputation: 123739

http://jsfiddle.net/f23uP/

$('select').change(function(){

$('input[type=name]').val($('option:selected',this).text());
    $('input[type=price]').val($(this).val());
});

Upvotes: 4

tymeJV
tymeJV

Reputation: 104785

Yes

$("select").change(function() {
    var price = this.value;
    var selText = $("select option:selected").text();

    $("input[type='name']").val(selText);
    $("input[type='price']").val(price);
});

Something like that should work

Upvotes: 2

Related Questions