jquery 如何在选中单选按钮(输入)时触发事件?

0aydgbwb  于 2022-11-22  发布在  jQuery
关注(0)|答案(3)|浏览(399)

我有两个type="radio"输入,第一个选项被默认选中。我想实现的是,如果第二个选项(输入)被选中,则激发一个特定的事件。我曾尝试通过基本的“if/else”语句(检测特定输入具有“checked”属性)来实现这一点,但它不起作用...
下面是HTML部分:

<input type="radio" name="radio-group" id="sendnow" value="Send Now" checked>
<label for="sendnow" class="camp_lbl">Send Now</label>
<input type="radio" name="radio-group" id="sendlater" value="Schedule Send">
<label id="zzz" for="sendlater" class="camp_lbl">Schedule Send</label>

还有CSS:

#send_options_radio_selectors input[type="radio"] {
  position: absolute;
  opacity: 0;
  -moz-opacity: 0;
  -webkit-opacity: 0;
  -o-opacity: 0;
}

#send_options_radio_selectors input[type="radio"] + label {
  position: relative;
  margin-right: 12%;
  font-size: 1.5rem;
  line-height: 23px;
  text-indent: 25px;
  color: #505e6d;
  cursor: pointer;
}

#send_options_radio_selectors input[type="radio"] + label:before {
  content: "";
  display: block;
  position: absolute;
  top: 2px;
  height: 18px;
  width: 18px;
  background: white;
  border: 1px solid gray;
  box-shadow: inset 0 0 0 2px white;
  -webkit-box-shadow: inset 0 0 0 2px white;
  -moz-box-shadow: inset 0 0 0 2px white;
  -o-box-shadow: inset 0 0 0 2px white;
  -webkit-border-radius: 50px;
  -moz-border-radius: 50px;
  -o-border-radius: 50px;
}

#send_options_radio_selectors input[type="radio"]:checked + label:before {
  background: #e16846;
}
lndjwyie

lndjwyie1#

您可以“监听”change事件,然后使用.prop('checked)检查特定的radio是否为:checked(有很多方法可以检查)
第一个

rslzwgfq

rslzwgfq2#

正如我在评论中提到的:
通过侦听更改来检测单选按钮组值是否更改:

$('[name="radio-group"]').on('change', function(){ /* do something */ })
mnemlml8

mnemlml83#

您可以捕获点击事件,然后检查单选按钮是否被选中,如:-

$("#sendnow").click(function()
{
     // Run every time when user click radio button 
     if( $(this).is(":checked") )
     {
         // Do what ever you want ;
         // Run only of radio button is checked
     }
});

您可以使用$("input[type='radio']")代替$("#sendnow"),将其添加到每个单选按钮上。

相关问题