场景:用户从下拉列表中选择一个城市。从该选择中,输入文本输入字段然后填充一个字符串+城市.text()
问题:使用我所拥有的(下面),当选项的文本被追加时,字符串将自动填充。
默认情况下,我希望输入文本字段为空白,并且只有当用户选择一个城市时,它才会添加文本+选项文本的字符串。
感谢您的关注和建议!
演示:http://codepen.io/salbaldovinos/pen/QwrZbp
$(document).ready(function(){
var eventChoice = $('#test'),
prodInterest = $('#productInterest');
eventChoice.change(function(){
var str = "";
$('#test option:selected').each(function(){
str += "Channel & TR Event Reg - " + $(this).text();
});
prodInterest.val( str );
}).change();
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="">
<select name="" id="test">
<option value="" selected></option>
<option value="hongkong">Hong Kong</option>
<option value="taipai">Taipai</option>
</select>
<input type="text" id="productInterest" />
</form>
发布于 2015-02-24 21:00:11
您需要像这样修改jQuery代码:
$(document).ready(function(){
var eventChoice = $('#test'),
prodInterest = $('#productInterest');
eventChoice.change(function(){
var str = "";
$('#test option:selected').each(function(){
str += "Channel & TR Event Reg - " + $(this).text();
});
prodInterest.val( str );
});
});注意,在绑定之后删除了change(),这导致它在绑定完成后立即触发更改。
选择选项为空时的代码版本:
$(document).ready(function(){
var eventChoice = $('#test'),
prodInterest = $('#productInterest');
eventChoice.change(function(){
var str = "";
$('#test option:selected').each(function(){
if ($(this).val() != "") {
str += "Channel & TR Event Reg - " + $(this).text();
}
});
prodInterest.val( str );
});
});发布于 2015-02-24 21:00:57
检查所选值的长度。如果没有,就跳过它。
$(document).ready(function(){
var eventChoice = $('#test'),
prodInterest = $('#productInterest');
eventChoice.change(function(){
var str = "";
$('#test option:selected').each(function(){
if (this.value.length) {
str += "Channel & TR Event Reg - " + $(this).text();
}
});
prodInterest.val( str );
}).change();
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="">
<select name="" id="test">
<option value="" selected></option>
<option value="hongkong">Hong Kong</option>
<option value="taipai">Taipai</option>
</select>
<input type="text" id="productInterest" />
</form>
发布于 2015-02-24 21:01:18
您在页面加载时触发了change(),所以它使用的是空白字段,但我怀疑您希望在选中空白选择时字段中的文本消失,所以只需添加这一行
eventChoice.change(function(){
if ($('#test option:selected').text() == '') return;https://stackoverflow.com/questions/28706088
复制相似问题