Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if radio is checked doesn't work when the radio is checked using jQuery

I need to dynamically set textarea as required or not but it doesn't want to work properly. JQuery check it itself but then can't check if it's checked or not. But when you clicked inside the second radio, the textarea is always required. I tried many times to make it works but it's still buggy. I have added "attr" and "removeAttr" because I read on stackoverflow that sometimes '.prop('required',false);' doesn't work but still no luck.

I made a fiddle with my problem.jsFiddle

$(".parent-div").click(function() {
    $(this).next().slideToggle();
    var a = $(this).next();
    $('.child-div').not(a).slideUp();
    $(this).find("input").prop( "checked", true );
});
$("#my-radio").change(function() {
if(this.checked) {
    $("#my-textarea").prop('required',true);
$("#my-textarea").attr('required');
}
else {
    $("#my-textarea").prop('required',false);
$("#my-textarea").removeAttr('required');
}
});
like image 891
joryl Avatar asked Dec 30 '25 09:12

joryl


1 Answers

You dont need the change event of #my-radio. You can do it in .parent-div click event like following.

$(".parent-div").click(function () {
    $(this).next().slideToggle();
    var a = $(this).next();
    $('.child-div').not(a).slideUp();

    //i have added this
    var checkbox = $(this).find("input");
    checkbox.prop("checked", true);
    $("#my-textarea").prop('required', checkbox.val() == 'second');
});

UPDATED FIDDLE

like image 57
Ibrahim Khan Avatar answered Jan 01 '26 22:01

Ibrahim Khan