Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the label text in jQuery?

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);


});
like image 812
user1362002 Avatar asked May 05 '12 03:05

user1362002


People also ask

Is text () a jQuery method?

jQuery text() MethodThe text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of ALL matched elements.

How can set text to textbox in jQuery?

Answer: Use the jQuery val() Method You can simply use the jQuery val() method to set the value of an input text box.


1 Answers

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 use keyup instead of change.

Here is an updated jsfiddle​

like image 177
Josh Mein Avatar answered Sep 18 '22 11:09

Josh Mein