简体   繁体   English

onclick清除表单字段JavaScript

[英]onclick to clear form fields JavaScript

I hope this question isn't duplicating something in the archives; 我希望这个问题不会在档案库中重复出现; I've looked but can't find an answer that solves my problem because I seem to be following the advice given. 我看过但找不到解决我问题的答案,因为我似乎正在遵循给出的建议。

I am making a dynamic form with JavaScript and would like to clear the prompts in each field when a user clicks in it. 我正在使用JavaScript制作动态表单,并希望在用户单击它时清除每个字段中的提示。 Here is part of what I have for one of the form fields. 这是表单字段之一的一部分。 I can't figure out why onlick="this.value=' '"; 我不知道为什么onlick =“ this.value =''”; isn't working. 不起作用。 Any help would be much appreciated. 任何帮助将非常感激。

    var VMake1 = document.createElement("input"); 
    VMake1.name = "veh_1_make"; 
    VMake1.type = "text";
    VMake1.value= "Please enter the make of vehicle 1";
    if (VMake1.value=="Please enter the make of vehicle 1") {   
        onclick="this.value=''";    }   
    placeVeh1Make.parentNode.insertBefore(VMake1,placeVeh1Make);

Thank you in advance for your help. 预先感谢您的帮助。

You should look for the onFocus event on the field and set the value of the field to an empty string on that event. 您应该在该字段上查找onFocus事件,然后在该事件上将该字段的值设置为空字符串。 This also has the benefit of clearing values from fields if the user tabs through the form input fields. 如果用户通过表单输入字段进行制表,这还具有清除字段值的好处。

You also need to reference the VMake1 element when setting the onfocus. 设置onfocus时,还需要引用VMake1元素。 So it might look like this: 因此可能看起来像这样:

var VMake1 = document.createElement("input"); 
VMake1.name = "veh_1_make"; 
VMake1.type = "text";
VMake1.value= "Please enter the make of vehicle 1";
VMake1.onfocus = "if (this.value === "Please enter the make of vehicle 1") {this.value='';}";   
placeVeh1Make.parentNode.insertBefore(VMake1,placeVeh1Make);

Note that I moved the conditional into the actual onfocus code. 请注意,我将条件移到了实际的onfocus代码中。

onclick="this.value=''";

replace with 用。。。来代替

VMake.onclick="this.value=''"; // or onfocus

or, better yet, 或者,更好的是

VMake.addEventListener("click", function(){this.value=''}); // or "focus"

If you are willing to use a framework, this is the jQuery way: 如果您愿意使用框架,这是jQuery的方法:

$(VMake).click(function(){ //or .focus(...)
  this.value=''
}); 

or even 甚至

$(VMake).click(function(){
  $(this).val('')
});

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

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