Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change button text in JQuery

I have this working code so far:

Fiddle: http://jsfiddle.net/r4emt/12/

Right now before you enter the JQuery UI autocomplete, the button reads "Hello". You can type "item" in the JQuery UI autocomplete and you'll notice the button now says "World". Click on the "world" button to put item in the list. If you type item again you can select one and click the replace button on an item already in the list. However once you do this, The button still says "world" but it should say "hello" because there is nothing in the input field. If you click in the input field and then hit delete or back arrow it changes back to "hello" but there isn't anything there to delete or go to the left of. I think it has to do with this part of the code:

$('#inputWrapper').on('keyup', '#tags', function() {
    if($(this).val() == '') {
        $('button.addButton').text('Hello');
    } else {
        $('button.addButton').text('World');
    }
});

Specifically the 'keyup' part. So my question is how can I fix this so that whenever the input box is empty the button always reads "hello" and when there is input in the field, the button reads "world"? Thanks!

like image 982
sbru Avatar asked Apr 22 '13 19:04

sbru


People also ask

How to change text of a button jQuery?

Answer: Use the jQuery prop() and html() Methods You can simply use the jQuery prop() method to change the text of the buttons built using the HTML <input> element, whereas to change the text of the buttons which are created using the <button> element you can use the html() method.

How do I change the button text?

To change the button text, first we need to access the button element inside the JavaScript by using the document. getElementById() method and add a click event handler to the button, then set it's value property to blue . Now, when we click on our button , it changes the value from Red to Blue or vice versa.

How to change button value jQuery?

With jQuery, you can use the . val() method to set values of the form elements. To change the value of <input> elements of type button or type submit (i.e., <input type="button"> or <input type="submit"> ), you can do like: JS.


1 Answers

I know this is a long dead thread, but I needed to add this, because I've just spent 2 days tracking down a memory leak (Caused by me using code from this page).

IMPORTANT: Do not use jQuerys text() on button elements!

The function creates something in the DOM that cannot be removed by empty(). If you then call the function multiple times over a long period a large amount of rubbish will be plopped in your DOM, causing stuff to break.

See jQuery API documentation.

(Can't find exactly where its mentioned in the documentation, but its in there somewhere, I've got to run for my train now)...

like image 104
User2 Avatar answered Oct 12 '22 05:10

User2