简体   繁体   English

如何使用JQuery获取表单中复选框的value属性?

[英]How to use JQuery to get the value property of a checkbox in a form?

I want to use either Javascript or JQuery to get the value of a checkbox when it is checked. 我想使用Javascript或JQuery来选中复选框的值。

How can I do that? 我怎样才能做到这一点? Please see question marks in the JQuery code below. 请在下面的JQuery代码中查看问号。

<html>
<body>

<form id="toggleForm" action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>

<script>
$('**???**').on('**checked???**', function(){
   var checkedValue = $(this).attr('**value???**');
   console.log("The checkbox value property is "+checkedValue);
});
</script>

</body>
</html>

(Please note that my question is not a duplicate of other questions, because in the other questions, the checkboxes have a class and the code is grabbing them using their class. In my question, my checkboxes don't have a class. How can I grab them without them having a class or ID?? How can I check their value? What is the event called for when they are checked? Please see the question marks in my attempt above.) (请注意,我的问题不是其他问题的重复,因为在其他问题中,复选框有一个类,而代码正在使用其类来捕获它们。在我的问题中,我的复选框没有类。如何我在没有类或ID的情况下抓住了它们?如何检查它们的值?检查它们时会发生什么事件?请在上面的尝试中查看问号。)

  1. Use .val() 使用.val()

 $(':checkbox').on('change', function() { var checkedValue = $(this).val(); console.log("The checkbox value property is " + checkedValue); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="toggleForm" action=""> <input type="checkbox" name="vehicle" value="Bike">I have a bike<br> <input type="checkbox" name="vehicle" value="Car">I have a car </form> 

 $(document).on('change','input:checkbox',function(){ var value=$(this).val(); if($(this).is(':checked')){ alert(value+" selected"); } else{ alert(value+" unselected");} }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <body> <form id="toggleForm" action=""> <input type="checkbox" name="vehicle" value="Bike">I have a bike<br> <input type="checkbox" name="vehicle" value="Car">I have a car </form> </body> </html> 

 $(document).ready(function(){ $('input:checkbox').change(function(){ ($(this).prop("checked") == true) ? console.log($(this).val()+ " " +"checked"):console.log($(this).val()+ " " +"unchecked") }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="toggleForm" action=""> <input type="checkbox" name="vehicle" value="Bike">I have a bike<br> <input type="checkbox" name="vehicle" value="Car">I have a car </form> 

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

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