Get Checkbox Value Without Page Refresh
I got a table of checkboxes:
Solution 1:
You want to use AJAX. Here is an example in jQuery without AJAX:
<td><input id="box1" class="box" name="box1"type="checkbox" value="1" checked /></td>
<td><input id="box2" class="box" name="box2"type="checkbox" value="2" checked /></td>
<td><input id="box3" class="box" name="box3"type="checkbox" value="3" checked /></td>
JavaScript:
$(document).ready(function() {
$('.box').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
});
});
Demo: http://jsbin.com/ipasud/1/
Now instead of doing an alert
call, do a $.post to a backend URL that takes an id and a value of checked or unchecked. For example,
$.post('/submit-checkbox.php', {id: checkbox.attr('id'), value: isChecked});
And if we put that back into the code, it would look like this:
$(document).ready(function() {
$('.box').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
$.post('/whatever-your-url-is.php', {id: checkbox.attr('id'), value: isChecked});
});
});
Solution 2:
You can use jQuery: http://jquery.com/
<scripttype="text/javascript">
$(document).ready(function(){
$('#box').click(function(){
var selectedValue = $(this).value();
submitValue(selectedValue);
});
});
functionsubmitValue(valueSelected){
var request = $.ajax({
url: URL_OF_YOUR_PHP_FILE,
type: "POST",
dataType: 'json',
data: {value: valueSelected}
});
request.done(function(results) {
//DO WHAT YOU WANT WITH YOUR RESULTS
});
}
</script>
Then in your PHP file you can get the value selected in $_POST['value'] and return what you want (in JSON format).
Post a Comment for "Get Checkbox Value Without Page Refresh"