将JS函数转换为jQuery - (输入字段清除默认值)

时间:2012-02-08 00:55:19

标签: javascript jquery forms onsubmit

我想知道一些jQuery专家是否会如此友好地将以下脚本转换为jQuery。我自己无法转换它,并且更喜欢使用jQuery等效。

我想要做的只是从onSubmit上的关键字字段中删除默认值“搜索”,因为用户可以将关键字字段留空。

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

任何帮助都会非常感激。

3 个答案:

答案 0 :(得分:3)

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

请注意,.on()是jQuery 1.7中的新功能,在这种情况下与.bind()相同。

以下是与此答案相关的文档:

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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