简体   繁体   中英

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 the dropdown and the value " http://www.facebook.com/ " appears in my textfield. How can I achieve this effect? I know that I have to call a function onchange of the drop down but that's pretty much everything I know. Remember that I'm not trying to copy the exact selected value from the dropdown to the textfield here.

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM