Pixelomo
Pixelomo

Reputation: 6737

Reset input value without refreshing the page

I'm trying to disable a search submit button if my forms input is empty, this works fine if nothing has been searched for but if I submit a search and then (once the page loads) clear the search input and click submit again, the button isn't disabled.

I'm disabling the submit button using this code

$("#searchform input#search-submit").click(function() { var sValue = $('#searchform input#s').val(); if (sValue != "") { $('form#searchform input[type=submit]').removeAttr('disabled'); } else { $('form#searchform input[type=submit]').attr('disabled', 'disabled'); } });

I've worked out that the issue is the input field is retaining whatever value I searched for previously and so the button isn't disabled as it checks the input value and thinks its not empty.

Is there a way to delete an input value automatically once you've cleared the input field without refreshing the page?

Update:

Here's a fiddle

Upvotes: 0

Views: 2291

Answers (3)

Sankar Jay
Sankar Jay

Reputation: 196

Here i included the Jsfiddle link with your expected result, see the below link you will get the result.

$("#searchform input#searchsubmit").click(function() {
    var sValue = $('#searchform input#s').val();
    if (sValue != "") {
        $('form#searchform input[type=submit]').removeAttr('disabled');
        return true;
    } else {
        $('form#searchform input[type=submit]').attr('disabled', 'disabled');
        return false;
    }
return false;
});

http://jsfiddle.net/j7zwT/30/

Upvotes: 1

BPT
BPT

Reputation: 36

I think binding your click with live or on will help you out $("#searchform input#searchsubmit").click(function(e) { var sValue = $('#searchform input#s').val(); alert(sValue) if (sValue != "") { $('form#searchform input[type=submit]').removeAttr('disabled'); } else { e.preventDefault() $('form#searchform input[type=submit]').attr('disabled', 'disabled'); } });

Upvotes: 1

kpull1
kpull1

Reputation: 1663

If you click the search button when the input #s is empty, the button turns into disabled. Then it cannot be pressed again, neither being reenabled. Try it on another event like changed or keypress:

$('form#searchform input#s').changed(function() ...

Also take in account that, depending on the jQuery version (1.9 or above), you have to enable and disable (or add/remove the check mark) controls with .prop():

$('form#searchform input[type=submit]').prop('disabled', true);

More info about how migrating to jQuery 1.9

Upvotes: 1

Related Questions