Libor Vymětalík
Libor Vymětalík

Reputation: 53

Jquery change label text with inner input

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" />

When input box is changed I want to set label text to: Send copy to my mail: [email protected]

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

I have this Jquery code:

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

but when keyup function is triggered label is changed right, but inner input is deleted.

<label for="sendCopy">
   Send copy to my mail [email protected]
</label>

I hope you understand my problem.

Upvotes: 5

Views: 4235

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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>

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>

Upvotes: 5

Omer Bonfil
Omer Bonfil

Reputation: 417

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

You have to put the input outside of the label, before it.

Upvotes: -1

neelsg
neelsg

Reputation: 4842

Just change

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

To

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

Upvotes: 2

Related Questions