问题描述
|
我有3个选择框和1个输入。
我需要将选定的值合并在一起,并将其添加到隐藏的输入框中。
例如:
<select name=\"select-choice-1\" id=\"select-choice-1\">
<option value=\"1-\">1</option>
</select>
<select name=\"select-choice-1\" id=\"select-choice-2\">
<option value=\"5-\">5</option>
</select>
<select name=\"select-choice-1\" id=\"select-choice-3\">
<option value=\"2011\">2011</option>
</select>
最后我想得到:
这种情况下的值是:
1-5-2011
我如何才能获得此功能?
解决方法
JSFiddle演示:
一种方法是:
HTML:
<select name=\"select-choice-1\" id=\"select-choice-1\">
<option value=\"1-\">1</option>
<option value=\"2-\">2</option>
<option value=\"3-\">3</option>
</select>
<select name=\"select-choice-1\" id=\"select-choice-2\">
<option value=\"5-\">5</option>
<option value=\"6-\">6</option>
<option value=\"7-\">7</option>
</select>
<select name=\"select-choice-1\" id=\"select-choice-3\">
<option value=\"2011\">2011</option>
<option value=\"2012\">2012</option>
<option value=\"2013\">2013</option>
</select>
<input type=\'hidden\' id=\'myhidden\' value=\'\' />
JavaScript:
<script type=\'text/javascript\'>
$(document).ready(function() {
$(\'select\').each(function() {
$(this).change(function() {
var myele = \'\';
$.each($(\'select option:selected\'),function() {
myele += $(this).val();
});
$(\'#myhidden\').val(myele);
console.log($(\'#myhidden\').val());
});
});
});
</script>
修改了onchange。
,如果您希望代码足够灵活以使用任意数量的<select>
元素,则可以编写如下代码:
$(\"#yourInputBoxId\").val($(\"[id^=select-choice-]\").map(function() {
return $(this).val();
}).get().join(\"\"));
在这里,map()将所有其id
属性以select-choice-
开始的<select>
个元素的选定值投影到数组中。然后将数组项串联成一个不带分隔符的字符串(因为值已经包含一个)。
,$( \"#id_of_hidden_input\" ).val(
$( \"#select-choice-1\" ).val() +
$( \"#select-choice-2\" ).val() +
$( \"#select-choice-3\" ).val()
);
,你总是通过POST使用PHP或获取
改名字
<select name=\"select-choice-1\" id=\"select-choice-1\">
<option value=\"1-\">1</option>
</select>
<select name=\"select-choice-2\" id=\"select-choice-2\">
<option value=\"5-\">5</option>
</select>
<select name=\"select-choice-3\" id=\"select-choice-3\">
<option value=\"2011\">2011</option>
</select>
$choice1 = $_POST[\'select-choice-1\'];
$choice2 = $_POST[\'select-choice-2\'];
$choice3 = $_POST[\'select-choice-3\'];
echo $choice .\"-\".$choice2 .\"-\".$choice3;
,您将要使用select元素的selectedIndex和options属性。这是一个简单的示例:
var elm1 = document.getElementById(\"select-choice-1\"),elm2 = document.getElementById(\"select-choice-2\"),elm3 = document.getElementById(\"select-choice-3\"),sel1 = elm1.options[elm1.selectedIndex].value,sel2 = elm2.options[elm2.selectedIndex].value,sel3 = elm3.options[elm3.selectedIndex].value;
alert( sel1 + sel2 + sel3);
, var $selects = $(\'#select_box_1,#select_box_2,#select_box_3\');
var seperator = \'-\';
$selects.change(function() {
var val = [];
$selects.each(function() {
val.push($(this).val());
});
$(\'#hidden_input\').val(val.join(seperator));
}).trigger(\'change\');
这允许使用您选择的分隔符来合并任意数量的选择框值。
.trigger(\'change);
导致绑定的.change(...)
事件触发并隐含页面加载时的值(以防万一已提交表单并且预填了选择框)