jQuery更改带有内部输入的标签文本 [英] Jquery change label text with inner input
问题描述
我是Jquery的新手.输入框更改后,我想更改标签文本.我有一个名为电子邮件的输入框.
I am novice in Jquery. I want change label text when input box is changed. I have input box with name email.
<input type="text" name="email" id="email" />
更改输入框后,我要将标签文本设置为:将副本发送到我的邮件:mail@example.com
When input box is changed I want to set label text to: Send copy to my mail: mail@example.com
<label for="sendCopy">
<input id="sendCopy" type="checkbox" checked="" name="copy"></input>
Send copy to my mail
</label>
我有这个Jquery代码:
I have this Jquery code:
$(function () {
$("#email").keyup(function () {
var email = $("#email").val();
$("label[for='sendCopy']").val('Send copy to my mail: ' + email);
});
});
但是在触发 keyup 功能时,标签会被正确更改,但内部输入会被删除.
but when keyup function is triggered label is changed right, but inner input is deleted.
<label for="sendCopy">
Send copy to my mail mail@example.com
</label>
希望您能理解我的问题.
I hope you understand my problem.
推荐答案
您可以将标签的文本包装在span
中,以使其更易于选择:
You could wrap the text of the label in a span
to make it easier to select:
$("#email").keyup(function() {
$('label[for="sendCopy"] span').text('Send copy to my mail: ' + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="email" id="email" />
<label for="sendCopy">
<input id="sendCopy" type="checkbox" checked="" name="copy" />
<span>Send copy to my mail</span>
</label>
或者,您可以保留HTML并直接修改textNode.
Alternatively, you can keep the HTML as it is and amend the textNode directly.
$("#email").keyup(function() {
var textNodes = $('label[for="sendCopy"]').contents().filter(function() {
return this.nodeType == 3;
});
textNodes[textNodes.length - 1].nodeValue = 'Send copy to my mail: ' + $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email" />
<label for="sendCopy">
<input id="sendCopy" type="checkbox" checked="" name="copy" />
Send copy to my mail
</label>
这篇关于jQuery更改带有内部输入的标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!