1

I have this group of checkboxes displayed using a while loop form sql select. The checkboxes have values assigned to them from sql. I have assigned all the checkboxes the same class.

If I click on one of them, I want the value shown in an alert using jQuery`.

Code:

<?php
//$class=trim("YEAR 1");
$rec = mysqli_query($db, "SELECT * from studentbyclass where CLASS='$class'  "); 
                        
while($row = mysqli_fetch_array($rec)){
?>

<label class="form-check form-switch">
<input class="form-check-input students" type="checkbox"  value="<?php $row["STUDENT-ID"];?>" checked>
<span class="form-check-label students"><?php echo $row["STUDENT-NAME"];?></span>
</label>
           
<?php
}
?>
JQUERY

$(".students").on('click' , function(){         
            
  val = this.val();
        
  alert(val);           
});
2
  • .val() is a jquery function, not a htmlelement function. this is a html element. Wrap it in a jquery object to use .val() on it. E.g. $(this).val(). Or skip the overhead of making a jquery object for something so trivial and just write this.value. developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/value Commented Sep 1, 2024 at 17:48
  • This question is similar to: .val() is not a function. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. You should have been getting the "val is not a function" error in your console - did you check that? Commented Sep 2, 2024 at 8:15

1 Answer 1

0

The reason is you are using jQuery function with html element.

Either you should use html element with its value like this: this.value

$(".students").on('click' , function(){         
    val = this.value;
    alert(val);           
});

or jQuery selector with its jQuery function like this: $(this).val()

$(".students").on('click' , function(){         
    val = $(this).val();
    alert(val);           
});
Sign up to request clarification or add additional context in comments.

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.