-2

I have some radio buttons and want to add the value of the selected to the parent element (label) but this does not work:

jQuery(document).ready(function($){
    var columns = $(".acf-field-59e775b8e5977 .acf-input .acf-button-group  label.selected input").val(); 
        if(columns == "4"){
        $(this).parent().addClass("four");
    }
});

This is the field:

<label class="selected"><input name="acf_1" value="4" checked="checked" type="radio">4/12</label>
Henning Fischer
  • 1,495
  • 1
  • 17
  • 32

2 Answers2

2

Based on the code you provide, do like this:-

jQuery(document).ready(function($){
    var obj = $("input[name='acf_1']"); 
    if(obj.val() == 4){
     obj.parent('label').addClass("four");
    }
});

Working snippet:-

jQuery(document).ready(function($){
    var obj = $("input[name='acf_1']"); 
    if(obj.val() == 4){
     obj.parent('label').addClass("four");
    }
});
.four{
  font-size:20px;
  color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is the field:

<label class="selected"><input name="acf_1" value="4" checked="checked" type="radio">4/12</label>
Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
1

As SLaks mentioned, Class names cannot start with numbers. You say in the comments that the numbers for the class name is just an example, but when I test your code in JSFiddle with "test" instead of "4", it works.

https://jsfiddle.net/mn7dk5h2/

jQuery(document).ready(function($){
    var columns = $("input").val(); 
    alert(columns);
    if(columns == "test"){
            alert('marco')
        $(this).parent().addClass("test");
    }
});

and

<label class="selected"><input name="acf_1" value="test" checked="checked" type="radio">4/12</label>

So based on the code you've provided, the problem seems to be that the class name starts with a number.

Goose
  • 4,243
  • 3
  • 36
  • 75