根据从下拉列表中选择的选项为文本字段赋予一个值 [英] Give textfield a value based on option selected from drop down

查看:100
本文介绍了根据从下拉列表中选择的选项为文本字段赋予一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是给我的文本字段值基于一个选项是选择我的下拉列表。例如:我有2个字段,一个下拉菜单和一个文本字段。我从下拉列表中选择Facebook,并在我的页面显示 http://www.facebook.com/ 的值文本域。我怎样才能达到这个效果?我知道我必须调用下拉菜单上的一个函数,但这几乎是我所知道的。请记住,我并没有试图从下拉列表中将确切的选定值复制到文本字段中。 示例

标记

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

< input type =text/>

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



这是小提琴






回应你的评论,有很多方法(a switch 语句, if / elseif 语句等),最简单的办法可能是创建一个对象将文本映射到相应的 url

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

然后,在您的更改处理程序中,您可以简单地使用:

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



下面是一个例子


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

这篇关于根据从下拉列表中选择的选项为文本字段赋予一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆