Skip to content Skip to sidebar Skip to footer

Give Textfield A Value Based On Option Selected From Drop Down

What I'm trying to do is give my textfield a value based an an option is select form my drop down. For example: I have 2 fields, a drop down and a textfield. I select Facebook from

Solution 1:

example markup

<select>
    <option value="http://www.facebook.com">Facebook</option>
    <option value="http://www.twitter.com">Twitter</option>
</select>

<input type="text" />

jquery

$('select').change(function() {
    $('input[type="text"]').val(this.value);
});

Here's a fiddle


In response to your comment, there are a number of ways to do it (a switch statement, if/elseif statement etc), the easiest would probably be to create an object mapping the text to the corresponding url:

var urlFromText = {
  'Facebook' : 'http://www.facebook.com/',
  'Twitter' : 'http://www.twitter.com/'
};

Then, in your change handler, you can simply use:

$('input[type="text"]').val(urlFromText[$('option:selected', this).text()]);

Here's an example


Solution 2:

HTML

<select id="network">
    <option value="http://www.facebook.com">Facebook</div>
    <option value="http://www.twitter.com">Twitter</div>
</select>
<input id="network-txt"/>

Jquery

$("#network").change(function(){
    $("#network-txt").val($(this).val());
});

Working Example http://jsfiddle.net/nVEEE/


Post a Comment for "Give Textfield A Value Based On Option Selected From Drop Down"