Javascript - 在 ID 上选中特定单选按钮时显示警报

Javascript - Show alert when specific radio button is checked on ID

我需要在有人点击具有特定 ID 的单选按钮时显示提醒。

这是单选按钮:

<input name="shipping_method" type="radio" class="validate-one-required-by-name" value="kerst_shipping_standard" id="s_method_kerst_shipping_standard">

当有人点击那个单选按钮时,它需要显示一个警报。

尝试下一个代码:

document.getElementById("s_method_kerst_shipping_standard").addEventListener('click',function(){
    alert('clicked');
})
<input name="shipping_method" type="radio" class="validate-one-required-by-name" value="kerst_shipping_standard" id="s_method_kerst_shipping_standard">

试试这个。

document.getElementById('s_method_kerst_shipping_standard').addEventListener('click', function() {
    alert('ok');
});

我假设 ID 在文档中是唯一的。

快速示例:

document.getElementById("s_method_kerst_shipping_standard").onclick = function(){
  alert('Your alert')
}

Link 类似于 question

This could easily be done by selecting your button using the document method getElementById() and binding a function with your alert inside to its onclick.

就像我在下面做的那样:

document.getElementById('s_method_kerst_shipping_standard').onclick = function(){
  alert("Alert!");
};
<input name="shipping_method" type="radio" class="validate-one-required-by-name" value="kerst_shipping_standard" id="s_method_kerst_shipping_standard">

    radioBtn = document.querySelector("#s_method_kerst_shipping_standard");
  console.log(radioBtn);

  radioBtn.addEventListener("click",function(e){
      alert("test")

  }
)

function inputSelect(value)
      {
       if(document.getElementById("s_method_kerst_shipping_standard").checked===true)
       {
           alert("You Clicked");
       }
      }
<input name="shipping_method" type="radio" class="validate-one-required-by-name" value="kerst_shipping_standard" id="s_method_kerst_shipping_standard" onclick="inputSelect(this.value)">

您必须设置一个onclick 侦听器。您可以在javascript中检查它是否被选中,如下