Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add css class to parent of radio button when checked using jquery

Tags:

jquery

css

I'm trying to add a css class to the div.from of my radio button if it is checked. Then remove if it is not checked.

And the html:

<div style="width:49.5%;height:auto;float:left;" class="from">


<label>
<div class="fromm" id="order">
    <div class="frairimg"></div>
    <div class="frfromdetails"></div>
    <div class="frarrow"></div>
    <div class="frfromdetails"></div>
    <div class="frrefund"></div>
    <div class="radio"><input type="radio" name="from" id="something" class="getvalue"></div>
    <div class="frfnumber"></div>
    <div class="roundfare"></div>
</div>
</label>

<label>
<div class="fromm" id="order1">
    <div class="frairimg"></div>
    <div class="frfromdetails"></div>
    <div class="frarrow"></div>
    <div class="frfromdetails"></div>
    <div class="frrefund"></div>
    <div class="radio"><input type="radio" name="from" id="something1" class="getvalue"></div>
    <div class="frfnumber"></div>
    <div class="roundfare"></div>
</div>
</label>

  <label>
<div class="fromm" id="order2">
    <div class="frairimg"></div>
    <div class="frfromdetails"></div>
    <div class="frarrow"></div>
    <div class="frfromdetails"></div>
    <div class="frrefund"></div>
    <div class="radio"><input type="radio" name="from" id="something2" class="getvalue"></div>
    <div class="frfnumber"></div>
    <div class="roundfare"></div>
</div>
</label>                                  

</div>

CSS

<style>
.checked11 { background: red; }
</style>

Here's what I came up with in jquery:

<script>
$(document).ready(function() {
  $('input:radio').click(function() {
    $('input:radio[name='+$(this).attr('name')+']').parent().removeClass('checked11');
        $(this).parent().addClass('checked11');

    });
});

</script> 

here my problem is the class is applying for radio button only but want it to apply for div.from

Thankyou. Naresh Kamireddy

like image 698
user2361114 Avatar asked Dec 15 '22 10:12

user2361114


1 Answers

If I understand correctly, there are 2 requirements to this question.

Upon selecting a radio button:

  1. The CSS class checked11 should be added to the parent of the selected radio button.
  2. The CSS class checked11 should be removed from any parents of now no longer selected radio buttons.

If this is the case, then the following should work:

var $radioButtons = $('input[type="radio"]');
$radioButtons.click(function() {
    $radioButtons.each(function() {
        $(this).parent().toggleClass('checked11', this.checked);
    });
});

jsFiddle demonstration

like image 162
Richard Avatar answered May 25 '23 08:05

Richard