簡體   English   中英

onclick清除表單字段JavaScript

[英]onclick to clear form fields JavaScript

我希望這個問題不會在檔案庫中重復出現; 我看過但找不到解決我問題的答案,因為我似乎正在遵循給出的建議。

我正在使用JavaScript制作動態表單,並希望在用戶單擊它時清除每個字段中的提示。 這是表單字段之一的一部分。 我不知道為什么onlick =“ this.value =''”; 不起作用。 任何幫助將非常感激。

    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);

預先感謝您的幫助。

您應該在該字段上查找onFocus事件,然后在該事件上將該字段的值設置為空字符串。 如果用戶通過表單輸入字段進行制表,這還具有清除字段值的好處。

設置onfocus時,還需要引用VMake1元素。 因此可能看起來像這樣:

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);

請注意,我將條件移到了實際的onfocus代碼中。

onclick="this.value=''";

用。。。來代替

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

或者,更好的是

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

如果您願意使用框架,這是jQuery的方法:

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

甚至

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM