How to change button text in JQuery

sbru picture sbru · Apr 22, 2013 · Viewed 88.7k times · Source

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!

Answer

Daniel Eidson picture Daniel Eidson · Apr 22, 2013

Here is the working fiddle. Changes made are:

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

and at the end of your button click:

$('#tags').val('');
$('#tags').keyup();