-5

I need to show a alert when someone clicks on a radio button with a specific ID.

This is the radio button:

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

And when someone clicks that radio button it needs to show a alert.

n00bly
  • 395
  • 6
  • 21
  • That's not giving me the right answer since the inputs are generated by code, so I can't add the onclick="alert('test');" in the input tag, I need to do it by javascript. – n00bly Nov 05 '19 at 08:50

6 Answers6

1

Try next code:

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">
Aksen P
  • 4,564
  • 3
  • 14
  • 27
1

Quick example :

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

Link to similar question

Davit Mkrtchyan
  • 449
  • 5
  • 15
1

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.

like i did below:

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">
jsadev.net
  • 2,800
  • 1
  • 16
  • 28
1
    radioBtn = document.querySelector("#s_method_kerst_shipping_standard");
  console.log(radioBtn);

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

  }
)
jsadev.net
  • 2,800
  • 1
  • 16
  • 28
Zah
  • 106
  • 5
  • Thanks for you answer, this works also! – n00bly Nov 05 '19 at 09:02
  • 1
    Welcome to Stack Overflow! While this code may answer the question, it is better to include some context, explaining how it works and when to use it. Code-only answers tend to be less useful in the long run. See [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) for some more info. – Mark Ormesher Nov 05 '19 at 09:03
0

Try this.

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

I am assuming ID is unique in the document.

Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17
0

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)">

You have to set an onclick listener. You can check whether it is selected or not in javascript as follow

Mohamed Rashiq
  • 322
  • 1
  • 3
  • 12