简体   繁体   English

在javascript中重置文本框值

[英]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? 如何使用javascript或jQuery设置文本字段的值?

You would think this was simple but I've tried the following: 你会认为这很简单,但我尝试过以下方法:

Using defaultvalue 使用defaultvalue

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

Using jQuery 使用jQuery

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

Using js 使用js

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

None of them are doing it... :/ 他们都没有这样做......:/

In Javascript : 在Javascript中:

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

In jQuery : 在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) (用户|| js更改输入)

This worked for me: 这对我有用:

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

First, select the element. 首先,选择元素。 You can usually use the ID like this: 你通常可以使用这样的ID:

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

Then, to set the value, use .val("something") as in: 然后,要设置该值,请使用.val("something")如下所示:

$("#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");

    }

})

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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