简体   繁体   中英

Reset textbox value in javascript

If I have a input textbox like this:

<input type="text" id="searchField" name="searchField" />

How can I set the value of the textfield using javascript or jQuery?

You would think this was simple but I've tried the following:

Using defaultvalue

var a = document.getElementById("searchField");
a.value = a.defaultValue;

Using jQuery

jQuery("#searchField").focus( function()
{ 
  $(this).val(""); 
} );

Using js

document.getElementById("searchField").value = "";

None of them are doing it... :/

In Javascript :

document.getElementById('searchField').value = '';

In jQuery :

$('#searchField').val('');

That should do it

使用jQuery,我发现有时使用val来清除文本框的值没有任何效果,在那些情况下我发现使用attr完成工作

$('#searchField').attr("value", "");

Use it like this:

$("#searchField").focus(function() {
    $(this).val("");
});

It has to work. Otherwise it probably never gets focused.

试试这个:

$('#searchField').val('');

To set value

 $('#searchField').val('your_value');

to retrieve value

$('#searchField').val();

I know this is an old post, but this may help clarify:

$('#searchField')
    .val('')// [property value] e.g. what is visible / will be submitted
    .attr('value', '');// [attribute value] e.g. <input value="preset" ...

Changing [attribute value] has no effect if there is a [property value]. (user || js altered input)

This worked for me:

$("#searchField").focus(function()
{ 
    this.value = ''; 
});

First, select the element. You can usually use the ID like this:

$("#searchField"); // select element by using "#someid"

Then, to set the value, use .val("something") as in:

$("#searchField").val("something"); // set the value

Note that you should only run this code when the element is available . The usual way to do this is:

$(document).ready(function() { // execute when everything is loaded
    $("#searchField").val("something"); // set the value
});

this is might be a possible solution

void 0 != document.getElementById("ad") &&       (document.getElementById("ad").onclick =function(){
 var a = $("#client_id").val();
 var b = $("#contact").val();
 var c = $("#message").val();
 var Qdata = { client_id: a, contact:b, message:c }
 var respo='';
     $("#message").html('');

return $.ajax({

    url: applicationPath ,
    type: "POST",
    data: Qdata,
    success: function(e) {
         $("#mcg").html("msg send successfully");

    }

})

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM