添加字符串+选择要输入的文本

Add string + select text to input

本文关键字:输入 文本 选择 字符串 添加      更新时间:2024-04-22

场景:用户从下拉列表中选择一个城市。根据该选择,输入文本输入字段填充字符串+该城市.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>

检查所选值的长度。如果没有,就跳过它。

$(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>

您需要像这样更改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 );
  });
});

您在页面加载时触发了change(),所以它使用了空白字段,但我怀疑您希望在选择空白选择时字段中的文本消失,所以只需添加这一行

eventChoice.change(function(){
    if ($('#test option:selected').text() == '') return;
$(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('');
            }
    });
});

当我忙于其他答案时,这个问题有三个答案。不管怎样,我都在上传代码。如果您选择默认值,它将从#productInterest文本框中删除文本。。