从多个字段中获取价值并在文本字段中显示

从多个字段中获取价值并在文本字段中显示

本文介绍了jQuery:从多个字段中获取价值并在文本字段中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有6个不同的选择框和一个文本字段,我需要使用jQuery从中获取值并将其合并为一个文本字段.

I have 6 different select boxes and a text field which I need to fetch the value from and combine in to one text field using jQuery.

我基本上理解我将使用像这样的字符串构建targetTextField的值:$('#targetTextField').val(opt1+opt2+opt3+opt4+opt5+opt6+textField);

I understand essentially I will build the value for the targetTextField with a string like this: $('#targetTextField').val(opt1+opt2+opt3+opt4+opt5+opt6+textField);

我该如何获取select#options1的值并将其转换为opt1?

What do I use to fetch the value of select#options1 and transform that in to opt1?

是沿着opt1 = $('select#options1').val();的路线还是我朝着完全错误的方向前进?

Would it be along the lines of opt1 = $('select#options1').val(); or am I heading in completely the wrong direction?

我创建了一个基本的jsfiddle,只有两个选项:

I've created a basic jsfiddle with just two options at:

http://jsfiddle.net/e2ScF/2/

jQuery

$(function() {
    $("#options").change(function(){
    var opt1 = $('select#options').val()
    }$('#targetTextField').val(opt1+opt2);
});
    $("#options2").change(function(){
    var opt2 = $('select#options2').val()
    }$('#targetTextField').val(opt1+opt2);
});
});​

HTML

<select id="options">
  <option value="" selected>Choose...</option>
  <option value="opt1Value1" >Option 1</option>
  <option value="opt1Value2" >Option 2</option>
</select>
<select id="options2">
  <option value="" selected>Choose...</option>
  <option value="opt2Value1" >Option 1</option>
  <option value="opt2Value2" >Option 2</option>
</select>
<input type="text" id="targetTextField" name="targetTextField" size="31" tabindex="0" maxlength="99">​

...但是它似乎没有用,所以我显然误解了或错过了一些东西.

...but it doesn't appear to be working, so I've obviously misunderstood or missed something.

推荐答案

我为您制作了此演示,希望对您有帮助

I made this demo for you, hope it helps

http://jsfiddle.net/e2ScF/5/

$(function() {
$("#options").change(function(){
        setTarget() ; // Something has changed so lets rebuild the target
});
    $("#options2").change(function(){
        setTarget();// Something has changed so lets rebuild the target
});
});

// Just get the values you want and update the target
function setTarget(){
    var tmp = $("#options").val();
    tmp += $("#options2").val();
    $('#targetTextField').val(tmp);
}
​

这篇关于jQuery:从多个字段中获取价值并在文本字段中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:22