使用 jQuery 删除输入值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1524916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:37:55  来源:igfitidea点击:

Remove value of input using jQuery

jquery

提问by Elitmiar

I need to remove some values from a hidden and text input box using jQuery, but somehow this is not working

我需要使用 jQuery 从隐藏和文本输入框中删除一些值,但不知何故这不起作用

Example:

例子:

<input type="hidden" value="abc" name="ht1" id="ht1" />
<input type="text" name="t1" id="t1" />

I use the following jQuery code to remove the values with an onclick event

我使用以下 jQuery 代码通过 o​​nclick 事件删除值

$('#rt1').click(function() {
    $('#t1').val();  
    $('#ht1').val();  
});

Can I empty the contents of the input box and clear the value of the hidden field using jQuery?

我可以使用jQuery清空输入框的内容并清除隐藏字段的值吗?

回答by Tamas Czinege

You should do this:

你应该做这个:

$('#rt1').click(function() {
    $('#t1').val('');  
    $('#ht1').val('');  
});

That is, pass an empty string. Either that, or use removeAttr (query.removeAttr('value')).

也就是说,传递一个空字符串。要么,要么使用removeAttr(query.removeAttr('value'))。

回答by Mark Bell

$('#rt1').click(function() {
    $('#t1').attr('value', '');  
    $('#ht1').attr('value', '');  
});

回答by dotty

Shorter version

较短的版本

$('#rt1').click(function() {
    $('#t1, #ht1').val('');  
});

回答by rogeriopvl

You just need to pass an empty string in the val()function or, you can use the more generic attr()function that sets a given attribute to a given value:

您只需要在val()函数中传递一个空字符串,或者,您可以使用更通用的attr()函数将给定的属性设置为给定的值:

$('#rt1').click(function() {
    $('#t1').attr("value", "");  
    $('#ht1').attr("value", "");  
});

回答by jerjer

This should be:

这应该是:

$('#rt1').click(function() {
    $('#t1').val('');  
    $('#ht1').val('');  
});

When val() function doesn't have parameter it will serves as getter not setter

当 val() 函数没有参数时,它将作为 getter 而不是 setter

回答by Indranil

$(document).ready(function(){ 

  $('input').click(function(){ 

    $(this).removeAttr('value');

  });
});

//remove value when click

//without effect input type  submit 
$(document).ready(function(){ 

  $('input:not(:submit)').click(function(){ 

    $(this).removeAttr('value');
  });
});