Palle
Palle

Reputation: 166

Convert JS function to jQuery - (input field clear default value)

I was wondering if some jQuery expert would be so kind to convert the below script to jQuery. I am having trouble converting it myself and would much prefer to use a jQuery equivalent.

What I am trying to do is simply remove the default value of 'Search' from a keyword field onSubmit, as the user can leave the keyword field blank.

function clearValue() {
    var searchValue = document.getElementById("global-search").value;
    if (searchValue == "Search") {
        document.getElementById("global-search").value = "";
    }
}

Any help would be much appreciate.

Upvotes: 1

Views: 249

Answers (3)

Billy Moon
Billy Moon

Reputation: 58551

function clearValue() {
    if ($("#global-search").val() == "Search") {
        $("#global-search").val('');
    }
}

Upvotes: 0

legendofawesomeness
legendofawesomeness

Reputation: 2911

if($("#global-search").val() == "Search")
    $("#global-search").val("");

Upvotes: 0

Jasper
Jasper

Reputation: 76003

//wait for the DOM to be ready (basically make sure the form is available)
$(function () {

    //bind a `submit` event handler to all `form` elements
    //you can specify an ID with `#some-id` or a class with `.some-class` if you want to only bind to a/some form(s)
    $('form').on('submit', function () {

        //cache the `#global-search` element
        var $search = $('#global-search');

        //see if the `#global-search` element's value is equal to 'Search', if so then set it to a blank string
        if ($search.val() == 'Search') {
            $search.val('');
        }
    });
});

Note that .on() is new in jQuery 1.7 and in this case is the same as .bind().

Here is the documentation related to this answer:

Upvotes: 3

Related Questions