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><optionvalue="http://www.facebook.com">Facebook</option><optionvalue="http://www.twitter.com">Twitter</option></select><inputtype="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

<selectid="network"><optionvalue="http://www.facebook.com">Facebook</div><optionvalue="http://www.twitter.com">Twitter</div></select><inputid="network-txt"/>

Jquery

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

Working Examplehttp://jsfiddle.net/nVEEE/

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