Selecting checked radio button with jQuery when inputs are duplicated


I'm working on a form that has a funky layout and requires me to duplicate one of the radio questions into another location. This is causing some issues with the Javascript I've written.

On page load, I call a method to find the checked radio input and add a class to its parent (for styling reasons) to do this:

checkPillRadioButton("valuemodeheight");

function checkPillRadioButton(name) {
    var checked = $('input[name="' + name + '"]:checked')
    checked.parent().addClass("selected");
}

This was working, but now the question has been duplicated it only works for the second set of the radio buttons. Is there a way I can modify what I have to work with duplicate input radio names?

Thanks.

As per request, example of markup:

<div class="pillRadioButtons">
    <label class="pillRadioButtons-option">
        <input type="radio" name="valuemodeheight" value="CM">
            <span>CM</span>
    </label>
   <label class="pillRadioButtons-option">
        <input type="radio" name="valuemodeheight" value="CM" checked>
            <span>CM</span>
    </label>
</div>

Here is also a Plunkr of the issue:

https://plnkr.co/edit/PDJhLtN1ub1SPH3iKXvq?p=preview

- - Source

Answers

answered 4 day ago Shikha thakur #1

Thats is not working because you have passed a different argument altogether to the function 'checkPillRadioButton'

It should be 'valuemodeheight'

checkPillRadioButton("valuemodeweight");

answered 4 day ago weBBer #2

Actually, I didn't get what you are looking for, but here is an answer from me from my understanding of the issue.

checkPillRadioButton("valuemodeheight");
checkPillRadioButton("valuemodewidth");

function checkPillRadioButton(name) {
  var checked = $('input[name="' + name + '"]:checked');
  checked.parent().addClass("selected");
}
.pillRadioButtons-option.selected {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pillRadioButtons">
  <label class="pillRadioButtons-option">
        <input type="radio" name="valuemodeheight" value="CM">
            <span>CM</span>
    </label>
  <label class="pillRadioButtons-option">
        <input type="radio" name="valuemodeheight" value="Feet" checked>
            <span>Feet</span>
    </label>
</div>
<br/>
<br/>
<div class="pillRadioButtons">
  <label class="pillRadioButtons-option">
        <input type="radio" name="valuemodewidth" value="CM">
            <span>CM</span>
    </label>
  <label class="pillRadioButtons-option">
        <input type="radio" name="valuemodewidth" value="Feet" checked>
            <span>Feet</span>
    </label>
</div>

answered 4 day ago DCR #3

change your css to:

<style type="text/css" media="all">
   input[type=radio]:checked + span {
   background-color: red;
}
</style>

and add an onchange event to your input

comments powered by Disqus