Ferdia O'Brien
Ferdia O'Brien

Reputation: 869

Select which radio button is selected based on Name and Value

I'm working on a pretty basic show/hide script and am basing it on which of the two radio buttons below are checked. My problem is that I can't add id's to the radio buttons, as the code is dynamically generated. Is there any way using JQuery to select which box is checked based on the combination of the name and value? Once I have that IF statement I can handle the rest, but I only know how to do it using classes or ID's.

<span class="wpcf7-form-control-wrap mysql">
   <span id="mysql" class="wpcf7-form-control wpcf7-radio radiobuttons">
      <span class="wpcf7-list-item">
         <label>
            <span class="wpcf7-list-item-label">Yes</span>
            &nbsp;
            <input type="radio" name="mysql" value="Yes">
         </label>
      </span>
      <span class="wpcf7-list-item">
         <label>
            <span class="wpcf7-list-item-label">No</span>
            &nbsp;
            <input type="radio" name="mysql" value="No">
         </label>
      </span>
   </span>
</span>

So basically I am looking for something like "if the name is mysql, the value is Yes, and the radio button is checked, do X. If the name is mysql, the value is No, and the radio button is checked, do Y.

Thanks in advance.

Upvotes: 2

Views: 1945

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

$(".wpcf7-list-item input:radio").click(function(){
    if($(this).val() == "Yes"){
        alert("do yes function");
    }else{
       alert("do no function");             
    }
});

Demo: http://jsfiddle.net/jeBFN/1/

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34117

Working demo http://jsfiddle.net/YLesK/3/

The name attribute if same throughout so I reckon you will be fine if you check this.value ; otherwise, you can add this condition $(this).prop('name') === "mysql" ==> http://jsfiddle.net/YLesK/5/

Hope this helps, :)

code

$(function(){
    $('input[type="radio"]').click(function(){
        if(this.value === "Yes")
            alert("Do X I am yes");
        else if (this.value === "No")
            alert("Do Y I am No");
    });

});

Upvotes: 6

Related Questions