JQuery shortcut label text with internal input

I am new to JQuery. I want to change the text of the label when the input field changes. I have an input field named email .

<input type="text" name="email" id="email" />

      

When changing the input field, I want to set the label text: Send a 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>

      

I have JQuery code:

$(function () {
    $("#email").keyup(function () {
        var email = $("#email").val();
        $("label[for='sendCopy']").val('Send copy to my mail: ' + email);
    });
});

      

but when the keyup function fires, the label changes to the right, but the internal input is removed.

<label for="sendCopy">
   Send copy to my mail mail@example.com
</label>

      

Hope you can understand my problem.

+3


source to share


3 answers


You can wrap the label text in span

for easier selection:

<label for="sendCopy">
    <input id="sendCopy" type="checkbox" checked="" name="copy"></input>
    <span>Send copy to my mail</span>
</label>

      

$("#email").keyup(function () {
    $('label[for="sendCopy"] span').text('Send copy to my mail: ' + $(this).val());
});

      



Alternatively, you can keep the HTML as is and change 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();
});

      

Sample script

+3


source


Just change

<label for="sendCopy">
<input id="sendCopy" type="checkbox" checked="" name="copy"></input>
Send copy to my mail
</label>

      



For

<input id="sendCopy" type="checkbox" checked="" name="copy"></input>
<label for="sendCopy">
Send copy to my mail
</label>

      

+2


source


You are changing the content of the label to text, so the input inside it is removed, the input is part of the value.

Before that, you need to place the input outside the label.

0


source







All Articles