0

how can we change classname of parent span element on click of input radio button.

<label for="L">
     <span class="lbllevel1">
         <span class="label-size">L</span>
          <input id="L" name="size" type="radio" value="L">
      </span>
 </label>

I want to add "selected" class to span element which is with class "lbllevel1" on click of radio button.

Basically, i need output as <span class="lbllevel1 selected"> when radio button is clicked

5 Answers 5

1

you can add an event listener to radio button for click event or change event, use document.getElementById('L') to get the input, and inside event handler function use e.currentTarget to get current clicked input, you can use .classList += to add class to element, something like this:

var input = document.getElementById('L');
input.addEventListener("click", function(e){
   e.currentTarget.parentElement.classList += ' selected';
})
.selected{
background-color:#888888;
}
<label for="L">
 <span class="lbllevel1">
     <span class="label-size">L</span>
      <input id="L" name="size" type="radio" value="L">
  </span>
 </label>

Sign up to request clarification or add additional context in comments.

Comments

0
var lInput = document.getElementById("L");
lInput.addEventListener("click", function() {
    lInput.parentNode.classList.add("selected");
})

Comments

0

You could listen to the change event of radio by then add parent element with selected class if radio is checked:

document.querySelector("#L").addEventListener("change", function () {
  // check if radio is checked
  if (this.checked)
  {
     // add .selected class to parent
     this.parentElement.classList.add("selected");
  }
});

working copy

Comments

0
<label for="L">
<span class="lbllevel1">
      <span class="label-size">L</span>
      <input id="L" name="size" onclick="changeAttr(this)" type="radio" 
value="L">
  </span>
</label>

<script>

 function changeAttr(ele)
{
    ele.parentElement.classList.add('newClass');
}

</script>

Please see if this is helpful or not :)

Comments

0

Check through name

if($("input:radio[name='Name']").is(":checked")) {
         //write your code         
}

Check through class

if($("input:radio[class='className']").is(":checked")) {
     //write your code         
}

Check through data

if($("input:radio[data-name='value']").is(":checked")) {
         //write your code         
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.