简体   繁体   English

如何通过单击div单击单选?

[英]How to click radio by clicking on div?

Why is my code not working? 为什么我的代码不起作用? i need to simulate click on radio button. 我需要模拟单击单选按钮。 Radio button has click event. 单选按钮具有单击事件。

 $(".form-group").click(function() { alert("clicked") $(this).closest(".hotelObj", function() { $(this).trigger("click"); }) }); 
 .form-group { background-color: pink; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="form-group"> <label for="male" style="font-weight:800;">chose <input type="radio" value="z6" class="hotelObj" name="hotelType"> <p>description</p> </label> </div> 

Given the markup you've provided, javascript isn't necessary for this task, unless there's some other requirement you've left out. 给定您提供的标记,除非您有其他要求,否则不需要JavaScript即可完成此任务。

Since the label contains all the area that you want the click handler to affect, it should just work as is (clicking anywhere in the pink box will cause the radio button to become selected). 由于label包含您希望单击处理程序影响的所有区域,因此它应该可以按原样工作(在粉红色框中单击任何位置都会使单选按钮变为选中状态)。

 .form-group { background-color: pink; } 
 <div class="form-group"> <label style="font-weight:800;">chose <input type="radio" value="z6" class="hotelObj" name="hotelType"> <p>description</p> </label> </div> 

Your code is not working because you are using .closest() jquery method which will look for element starting from itself and then up in DOM tree. 您的代码无法正常工作,因为您使用的是.closest() jQuery方法,该方法会从自身开始查找元素,然后在DOM树中查找元素。 This way element with class .hotelObj is never found. 找不到带有.hotelObj类的这种方式的元素。

You need to use .find() method to find .hotelObj , because it's inside .form-group . 您需要使用.find()方法来查找.hotelObj ,因为它位于.form-group

$(".form-group").click(function() {
  $(this)
     .find(".hotelObj")
     .trigger("click");
});
Try onClickHandled property

<input type="checkbox" onclick="onClickHandler()" id="box" />

<script>
function onClickHandler(){
    var chk=document.getElementById("box").value;

    //use this value

}
</script>

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

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