jQuery val() 和复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5621324/
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
jQuery val() and checkboxes
提问by Jamie Treworgy
Is there some rationale for val()
being useless for checkbox controls, whereas it is useful for getting input data consistently across every other input control?
val()
对于复选框控件无用是否有一些理由,而它对于在所有其他输入控件中一致地获取输入数据很有用?
e.g. for checkboxes, at appears to always return "on" regardless of the checkbox state.For other input controls that don't actually have a "value" attribute, e.g. select and textarea, it behaves as you would expect. See:
例如对于复选框,无论复选框状态如何,at 似乎总是返回“on”。对于实际上没有“值”属性的其他输入控件,例如 select 和 textarea,它的行为与您期望的一样。看:
http://jsfiddle.net/jamietre/sdF2h/4/
http://jsfiddle.net/jamietre/sdF2h/4/
I can't think of a good reason why it wouldn't return true
or false
. Failing that, at least return "on" only when checked, and an empty string when not. Failing that, at least always return an empty string, given that checkboxes have no value
attribute!
我想不出一个很好的理由为什么它不会返回true
或false
. 否则,至少仅在选中时返回“on”,否则返回空字符串。否则,至少总是返回一个空字符串,因为复选框没有value
属性!
Obviously I know how to get the value using attr
, but here's the situation. I am developing a simple (so far anyway) C# jQuery implementation to do HTML parsing on the server, and I am trying to be completely faithful to jQuery's implementation so it behaves consistently on either the client or server against the same DOM. But this just seems stupid and I'm having a hard time getting myself to actually code "value" to return "ON" for a checkbox no matter what. But if I don't, it won't be consistent. So I'm trying to understand, is there some reason for doing this? Does it serve some purpose, or is it simply an artifact of some kind? Would anyone ever use the val()
method against a checkbox, if so, why? If not, why did the jQuery architects decide on this approach to make it not useful?
显然我知道如何使用 获得价值attr
,但情况就是这样。我正在开发一个简单的(到目前为止)C# jQuery 实现来在服务器上进行 HTML 解析,并且我试图完全忠实于 jQuery 的实现,以便它在客户端或服务器上针对相同的 DOM 保持一致的行为。但这似乎很愚蠢,我很难让自己实际编码“值”以返回复选框的“ON”,无论如何。但如果我不这样做,它就不会一致。所以我试图理解,这样做有什么理由吗?它是为了某种目的,还是仅仅是某种人工制品?是否有人会val()
针对复选框使用该方法,如果是,为什么?如果不,
回答by reko_t
I can't think of a good reason why it wouldn't return true or false. Failing that, at least return "on" only when checked, and an empty string when not. Failing that, at least always return an empty string, given that checkboxes have no value attribute!
我想不出一个很好的理由为什么它不会返回真或假。否则,至少仅在选中时返回“on”,否则返回空字符串。否则,至少总是返回一个空字符串,因为复选框没有 value 属性!
Checkboxes do have a value attribute. It's quite common to use it in eg. multi-checkboxes in forms, for example:
复选框确实有一个值属性。在例如使用它是很常见的。表单中的多复选框,例如:
<input type="checkbox" name="foo[]" value="1" />
<input type="checkbox" name="foo[]" value="2" />
Then when user submits the form, the server can parse which of the checkboxes were checked by checking the values of the foo[]
array. The value of the checkbox does not changewhether it is checked or not; the browser simply does not send the values of unchecked checkboxes to the server. If you do eg. $('#your-form').serialize()
in jQuery, it should work similarly; it shouldn't include values of unchecked checkboxes. If you omit the value from checkbox, it simply defaults to on
.
然后当用户提交表单时,服务器可以通过检查foo[]
数组的值来解析哪些复选框被选中。复选框的值无论是否选中都不会改变;浏览器根本不会将未选中复选框的值发送到服务器。如果你做例如。$('#your-form').serialize()
在 jQuery 中,它应该类似地工作;它不应该包含未选中复选框的值。如果您省略复选框中的值,则它只是默认为on
。
If you want to check whether an individual checkbox is checked or not in jQuery, the best most descriptive way is to do $(this).is(':checked')
如果要检查 jQuery 中是否选中了单个复选框,最好的描述性方法是 $(this).is(':checked')
回答by lonesomeday
You say that "checkboxes have no value
attribute". On the contrary: the value
attribute is optional excepton checkboxes and radio boxes.
你说“复选框没有value
属性”。相反:除了复选框和单选框外,该value
属性是可选的。
From the W3C specifications:
从W3C 规范:
[the
value
attribute] is optional except when the type attribute has the value "radio" or "checkbox"
[
value
属性] 是可选的,除非类型属性的值为“radio”或“checkbox”
on
is the default value that your browser gives the element when you ignore the specification and don't set a value
attribute.
on
是当您忽略规范并且不设置value
属性时浏览器为元素提供的默认值。
You need to remember what the value means: it is sent with the name
of the element to the server when the form is submitted. If it is not checked, the value is not sent. The value on
is therefore only sent when the checkbox is checked.
您需要记住该值的含义:name
提交表单时,它与元素的 一起发送到服务器。如果未选中,则不发送该值。on
因此,只有在选中复选框时才会发送该值。
回答by Santosh Linkha
Perhaps this should help
也许这应该有帮助
$(document).ready(function() {
$('input[type=checkbox]').click(function() {
alert("val="+$(this).val()+",checked="+$(this).attr('checked'));
});
});
Use input[type=checkbox]
to select input type="checkbox"
since checkbox is and input with type="checkbox"
使用input[type=checkbox]
选择input type="checkbox"
,因为复选框和输入类型=“复选框”
And also put value attribute to checkbox.
并将值属性放入复选框。
On jsfiddle
UPDATE
更新
<form method="post" action="#">
PHP<input type="checkbox" name="ch[]" value="PHP"><br/>
JS<input type="checkbox" name="ch[]" value="JS"><br/>
JAVA<input type="checkbox" name="ch[]" value="JAVA"><br/>
PYTHON<input type="checkbox" name="ch[]" value="PYTHON"><br/>
<input type="submit" name="submit"/>
</form>
And php
和 php
if($_POST){
foreach($_POST['ch'] as $post => $value){
echo "$post -> $value <br/>";
}
}
They all share same name as they are a common group of button. You you know which was checked and which was not through their values.
它们都具有相同的名称,因为它们是一组常见的按钮。您知道哪些已检查,哪些未通过它们的值进行检查。
The other way is
另一种方式是
if($_POST){
foreach($_POST as $post => $value){
echo "$post -> $value <br/>";
}
}
<form method="post" action="#">
PHP<input type="checkbox" name="PHP"><br/>
JS<input type="checkbox" name="JS"><br/>
JAVA<input type="checkbox" name="JAVA"><br/>
PYTHON<input type="checkbox" name="PYTHON"><br/>
<input type="submit" name="submit"/>
</form>
But the previous seems to add more dynamic and less tedious(I would believe).
但前一个似乎增加了更多的活力和不那么乏味(我相信)。
And as to @Capsule's question
至于@Capsule 的问题
alert("val="+$(this).val()+",checked="+$(this).attr('checked'));
<input type="checkbox"> Check me.
returns the value on
i believe that's the default value of the check-box.
返回on
我认为是复选框默认值的值。
And the second experiment also give the on
value.
而第二个实验也给出了on
价值。
I hope I am not wrong.
我希望我没有错。
回答by zhopon
If you pass an array to val function, it will set the checkbox as checked if the checkbox's value matches the value in the array. Source: http://api.jquery.com/val/#val-value
如果您将数组传递给 val 函数,如果复选框的值与数组中的值匹配,它会将复选框设置为已选中。来源:http: //api.jquery.com/val/#val-value
<input id="checkbox" type="checkbox" value="remember">
$("#checkbox").val(["remember"]);
回答by Shadow Wizard is Ear For You
Checkbox has value just like text box and this value is being sent to the server when the form is submitted only if the checkbox was selected at the time of submission.
复选框与文本框一样具有值,并且只有在提交时选中了复选框,才会在提交表单时将该值发送到服务器。
Unlike text box, checkbox has defaultvalue which is on
- this is sent to the server when the checkbox is selected but has no value
of its own, so that the processing code can know it was selected.
与文本框不同,复选框的默认值是on
- 当复选框被选中但没有value
自己的复选框时将其发送到服务器,以便处理代码可以知道它已被选中。
So the .val()
method is working just fine, returning the value of the element.
因此该.val()
方法工作正常,返回元素的值。
You're correct that jQuery is missing simple way to see if a specific checkbox/radio button is selected, something like $("#mycheckbox").checked()
but that's what we have plugins for. :)
您是正确的,jQuery 缺少查看是否选择了特定复选框/单选按钮的简单方法,例如,$("#mycheckbox").checked()
但这就是我们有插件的目的。:)
回答by Capsule
A checkbox is not always alone and its value is passed when submitting the form (otherwise, the name/value is not passed at all).
复选框并不总是单独存在,它的值在提交表单时被传递(否则,名称/值根本不会被传递)。
It's very useful when making arrays out of checkboxes, you can use name="test[]"
as their name, and set different values in each. When parsing the submitted result, you end up with an array containing all the checked values
当用复选框创建数组时,它非常有用,您可以使用name="test[]"
它们的名称,并在每个数组中设置不同的值。解析提交的结果时,您最终会得到一个包含所有检查值的数组
回答by Mackraken
You can do some surgery to jquerys val function to act like that. Return true or false whether theres no value attr.
你可以对 jquerys val 函数做一些手术来表现这样。是否没有值 attr 返回 true 或 false。
(function (){
var jval = $.fn.val
function superval(value){
if (value === undefined){
if (this.is("input") && this.attr("type") == "checkbox"){
if (this.attr("value")===undefined){
return this[0].checked
}
}
return jval.call(this)
} else {
return jval.call(this, value)
}
}
$.fn.val = superval
})()
console.log($('<input type="checkbox"/>').val()); // false
console.log($('<input type="checkbox" checked="whatever"/>').val()); // true
console.log($('<input type="checkbox" checked="whatever" value="yes"/>').val()); // yes
console.log($('<input type="text" value="heya"/>').val()); // heya
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>