我是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>
如果在HTML标记属性周围添加引号,则代码应该可以正常工作。
注1:你的JS代码是一个有效的代码,但最好用bind
替换on
,因为bind
方法是专门用于jQuery版本3的,检查:
$('#texta, #selectiona, #textb, #selectionb').on('keypress blur', function() {
注意2:如果您将要将事件附加到公共类的所有元素,然后将事件附加到此类,则您的代码将更有效:
$('.common_class').on('change input', function() {
你也可以使用input
事件为input
&textarea
和change
为select
's。
$('#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>
我看到的第一件事是HTML标签应该在配额内:例如。 id =“texta”而不是id = texta
你可以使用“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>