简体   繁体   English

如何在jQuery中更改标签文本?

[英]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. 我知道使用AJAX和jQuery和PHP是可行的。 Is there an easier way? 有没有更简单的方法? Please let me know. 请告诉我。 Here is my code and a link: http://jsfiddle.net/uQ54g/1/ 这是我的代码和链接: http//jsfiddle.net/uQ54g/1/

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


});

First of all, you have to use .text or .html to set the text within a label in jquery. 首先,您必须使用.text.html在jquery中的标签内设置文本。 Your current code will actually remove the label element and replace with just text. 您当前的代码实际上将删除label元素并仅替换为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. 您还可能希望在标签中添加类或ID,因为很可能您在页面上有多个标签。

HTML: HTML:

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

Javascript: 使用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 . 如果您想在输入每个字符后更改标签,则需要使用keyup而不是change

Here is an updated jsfiddle 这是一个更新的jsfiddle

The code in you fiddle is working fine as i mentioned in the comments, or you can use keyup like 你在小提琴中的代码正如我在评论中提到的那样正常工作,或者你可以使用keyup

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

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

also note that when you use replaceWith it will replace the matched element, in your case it label after the change is triggered the <label>hello</label> will be replace with Changed Text so if you do $("label") again it will return you undefined, see it for yourself 还要注意的是,当你使用replaceWith它将替换匹配的元素,在你的情况下,它label的变化被触发后<label>hello</label>将其替换Changed Text ,所以如果你做$("label")再次它将返回你未定义, 为自己看到它

try this: 试试这个:

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

use this with jquery library 与jquery库一起使用它

$('#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');
});

How about this 这个怎么样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM