使用 javascript 连接多个表单输入值

Concat multiple form input values using javascript

我对 HTML/javascript 很陌生。我正在尝试创建一个包含四个字段的表单:第一个字段 (texta) 是 readonly,第二个字段 (selectiona) 是一个下拉列表,第三个字段 (textb) 是 readonly,第四个字段(句子)是其他三个字段的串联。我不明白为什么我的 javascript 不工作:

<script>
$('#texta, #selectiona, #textb, #selectionb').bind('keypress blur', function() { 
    $('#sentence').val($('#texta').val() + ' ' +
    $('#selectiona').val() + ' ' +
    $('#textb').val() + ' ' +
    $('#selectionb').val() );
});
<script>
<p>Text A:<input id=texta readonly value="My favorite car is a: "></p>
<p>Selection A: <select id=selectiona>
 <option>Select...</option>
 <option>Toyota</option>
 <option>Honda</option>
 </select></p>
<p>Text B: <input id=textb readonly value="because they are "></p>
<p>Selection B: <select id=selectionb>
 <option>Select...</option>
 <option>reliable.</option>
 <option>fun to drive.</option>
 </select></p>
<p>Sentence: <input id=sentence readonly></p>

您可以使用 "on change" :

$('#selectiona, #selectionb').on('change', function() { 
    $('#sentence').val($('#texta').val() + ' ' +
    $('#selectiona').val() + ' ' +
    $('#textb').val() + ' ' +
    $('#selectionb').val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text A:<input id=texta readonly value="My favorite car is a: "></p>
<p>Selection A: <select id=selectiona>
 <option>Select...</option>
 <option>Toyota</option>
 <option>Honda</option>
 </select></p>
<p>Text B: <input id=textb readonly value="because they are "></p>
<p>Selection B: <select id=selectionb>
 <option>Select...</option>
 <option>reliable.</option>
 <option>fun to drive.</option>
 </select></p>
<p>Sentence: <input id=sentence readonly></p>

如果您在 HTML 标签属性周围添加引号,您的代码应该可以正常工作。

注意 1: 您的 JS 代码是有效代码,但最好将 bind 替换为 on,因为 bind 方法自 jQuery 版本 3 起专用,检查:

$('#texta, #selectiona, #textb, #selectionb').on('keypress blur', function() {

注意 2: 如果您将要附加事件的所有元素都提供给公共 class,然后将事件附加到这个 class :

$('.common_class').on('change input', function() {

您还可以为 inputtextarea 使用 input 事件,为 select 使用 change

$('#texta, #selectiona, #textb, #selectionb').bind('input change', function() {
  $('#sentence').val($('#texta').val() + ' ' +
    $('#selectiona').val() + ' ' +
    $('#textb').val() + ' ' +
    $('#selectionb').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Text A:<input id="texta" readonly value="My favorite car is a: "></p>
<p>Selection A:
  <select id="selectiona">
    <option>Select...</option>
    <option>Toyota</option>
    <option>Honda</option>
  </select>
</p>
<p>Text B: <input id="textb" readonly value="because they are "></p>
<p>Selection B:
  <select id="selectionb">
    <option>Select...</option>
    <option>reliable.</option>
    <option>fun to drive.</option>
  </select>
</p>
<p>Sentence: <input id="sentence" style="width:70%" readonly></p>