php - How can I change the label text in jQuery?

295

I have a textbox and a label. If the user wants to change the label text, he/she would have to enter the text in the textbox. How can I update the label text every time a user makes an entry in the textbox on change?

I know it is possible using AJAX with jQuery and PHP. Is there an easier way? Please let me know. Here is my code and a link: http://jsfiddle.net/uQ54g/1/

$('#change1').change(function(){
    var l = $(this).val();
    $('label').replaceWith(l);


});
837

Answer

Solution:

First of all, you have to use.text or.html to set the text within a label in jquery. Your current code will actually remove the label element and replace with just text. Therefore, it will no longer work if you try to edit the value again. You also may want to add a class or an id to your label because most likely you will have more than one label on a page.

HTML:

<input type="text" id="change1"/><br/>
<label id="test">Hello</label>

Javascript:

$('#change1').change(function(){
    var l = $(this).val();
    $('#test').text(l);
    // OR $('#test').html(l);
});

If you are wanting to change the label after every character entered you will need to usekeyup instead ofchange.

Here is an updated jsfiddle‚Äč

819

Answer

Solution:

The code in you fiddle is working fine as i mentioned in the comments, or you can usekeyup like

$('#change1').keyup(function(){
var l = $(this).val();
$('label').text(l);
//alert($('#change1').val())
});

http://jsfiddle.net/uQ54g/4/

also note that when you usereplaceWith it will replace the matched element, in your case itlabel after the change is triggered the<label>hello</label> will be replace withChanged Text so if you do$("label") again it will return you undefined,

30

Answer

Solution:

try this:

$('#change1').keyup(function(){
l=$(this).val()
$('label').html(l)
})
430

Answer

Solution:

use this with jquery library

$('#change1').on('keyup',function(){ //Change1 is id of textbox
   $('#label1').html($(this).val()) //label1 is the id of the label
});
$('#change1').blur(function() { //if we copy paste some text into the textbox it will also work if use this blur and trigger function
   $(this).trigger('keyup');
});
107

Answer

Solution:

How about this

$('#change1').change(function(item){
     $('label').text(item.target.value);
});

People are also looking for solutions to the problem: php - Displaying Reminders page from MySQL Database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.