javascript 使用 jQuery 清除输入字段中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21852406/
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
clear value in an input field with jQuery
提问by 001221
Hi I have a number of inputs for telephone numbers, they use the same class and the same show/hide techinque. I want to be able to clear the contents of the phone number in the input box, i.e. with the class name of input_tel.
嗨,我有许多电话号码输入,它们使用相同的类和相同的显示/隐藏技术。我希望能够清除输入框中电话号码的内容,即带有input_tel的类名。
However it seems to clear all inputs which I assume is because I am using the following line; input:text
, when I put in a class it just fails to work.
然而,它似乎清除了我认为是因为我使用以下行的所有输入;input:text
,当我上课时,它就无法正常工作。
My JS and some of my html is below or view a jsFiddle:
我的 JS 和我的一些 html 在下面或查看jsFiddle:
$(".contact_numbers").on('click', '.clearnumber', function () {
$(this).siblings('input:text').val('');
});
<div class="telephonetwo contact_numbers">
<input type="text" class="smallinput contactpagelabel" name="faxname" size="10" value="Fax">
<input type="checkbox" class="contact_no" name="showfax" value="Y">
<input type="text" name="fax" size="30" value="016128 13456" class="input_tel">
<a href="#" class="remove">Hide</a> <a href="#" class="clearnumber">Clear #</a>
</div>
If you are viewing my JSfiddle click the reveal additional numbers for the clear button to appear.
如果您正在查看我的 JSfiddle,请单击显示其他数字以显示清除按钮。
Update
更新
I want to be able to clear the closest input_tel rather than all of them, as their are multiple numbers.
我希望能够清除最近的 input_tel 而不是全部,因为它们是多个数字。
Thanks in advance
提前致谢
回答by Dhaval Bharadva
replace:
代替:
$(this).siblings('input:text').val('');
with
和
$(this).siblings('input:text').closest('.input_tel').val('');
回答by Niklas
How about targeting the input_tel
class then?
input_tel
那么针对班级怎么样?
$(".contact_numbers").on('click', '.clearnumber', function () {
$(this).parent().parent().find('input.input_tel').val('');
});
Assuming no other input fields have that input_tel
class on them.
假设没有其他输入字段具有input_tel
该类。
回答by Edd Smith
This should do it...
这个应该可以...
$(".contact_numbers").on('click', function () {
$(".input_tel").val('');
});
回答by Zuckerberg
The safe way to clear input fields with jquery
使用 jquery 清除输入字段的安全方法
$.fn.noText = function() {/*use the jquery prototype technology to make a chainable clear field method*/
if(this.is('input')){ /*check to c if you the element type is an input*/
this.val('');/*clear the input field*/
}return this;/*means it is chainable*/
};
$('input').noText();