简体   繁体   English

使用jQuery单击选择单选按钮

[英]Select radio button on click with jQuery

I'm trying to select a radio button on click with jQuery. 我试图用jQuery选择一个单选按钮。 I can't seem to get this to work though. 我似乎无法使它正常工作。 Here is my current attempt. 这是我目前的尝试。

JS JS

$(document).ready(function() {
  $("#payment").click(function(event) {
    event.preventDefault()
    $("input:radio[name=slug_tier_1]").attr("checked", true)
  })
});

HTML 的HTML

  <label class="plans__tier-1__actions">
    <%= radio_button_tag "slug", "tier_1", required: true %>
    <a href="#" class="button" id="payment">Select</a>
  </label>

Screenshot of name 名称的屏幕截图

在此处输入图片说明 This seems as though it should work? 这似乎应该工作吗? Any thing jump out at you? 有什么事想你吗?

<a class="btn">button</a>
<input type="radio" class="radio">

$(".btn").click(function(){
    $(".radio").prop("checked", true);
});

 $("input[type='radio'][name='slug_tier_1']").attr("checked", true); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" name="slug_tier_1"> 

If the name of the input is the same in the rendered HTML, the selector should be 如果输入的名称在呈现的HTML中相同,则选择器应为

$("input[type='radio'][name='slug_tier_1']").attr("checked", true);

The type should be given like any other attribute in [] .Also the name should be enclosed in quotes. 应该像[]任何其他属性一样给定类型。还应将名称用引号引起来。 See link 链接

From RoR Docs 从RoR 文件

radio_button_tag 'gender', 'male'
# => <input id="gender_male" name="gender" type="radio" value="male" />

So in this case the name should be just slug . 因此,在这种情况下,名称应该是刚slug slug_tier_1 is the ID of the element. slug_tier_1是元素的ID。

Either try 要么尝试

$("input[type='radio'][id='slug_tier_1']").attr("checked", true);

Or 要么

$("input[type='radio'][name='slug']").attr("checked", true);

Your code looks fine. 您的代码看起来不错。 Try this and check in console. 试试这个,并检查控制台。 There might be multiple elements of same ids 可能有多个具有相同ID的元素

$(document).ready(function() {
  console.log($("#payment"));
  $("#payment").click(function(event) {
    console.log($("input:radio[name=slug_tier_1]"));
  })
});

Check if it returns a single element or multiple elements for both #payment or $("input:radio[name=slug_tier_1]") 检查是否为#payment$("input:radio[name=slug_tier_1]")返回单个元素还是多个元素

Try and Reply 尝试并回复

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

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