场景:用户从下拉列表中选择一个城市。从该选择中,输入文本输入字段然后填充字符串+该城市.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>
答案 0 :(得分:2)
检查所选值的长度。如果没有,那就跳过它。
$(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();
});
&#13;
<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>
&#13;
答案 1 :(得分:1)
您需要像这样更改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 );
});
});
答案 2 :(得分:1)
你在页面加载时触发了change(),所以它使用了空白字段,但我怀疑你希望当选择那个空白选择时字段中的文本消失,所以只需添加这一行
eventChoice.change(function(){
if ($('#test option:selected').text() == '') return;
答案 3 :(得分:1)
$(document).ready(function(){
$("#test").change(function (){
if($("#test :selected").text().length != 0 ) {
var str1 = "Channel & TR Event Reg - " + $("#test :selected").text();
$("#productInterest").val(str1);
}
else {
$("#productInterest").val('');
}
});
});
虽然我忙于其他答案,但这个问题有3个答案。我试过的任何方式,所以我上传代码。如果您选择默认值,它将从#productInterest文本框中删除文本..