I’m trying to have a Javascript run when a checkbox is selected/deselected that calls a php file and passes the value of the checkbox that was selected. The script is firing but the value is not being passed as a parameter and I can’t work out why I’m doing wrong here.
Here’s an example the table cell that contains the checkbox with the script:
$(document).ready(function() {
$("td.article-export").click(function() {
var selectedRatingsIDs = $(this).val();
var checkedState = $(this).is(":checked");
console.log(selectedRatingsIDs);
// Create a reference to $(this) here:
$this = $(this);
$.post('updateExportSelections.php', {
type: 'updateSelections',
selectedRatingsIDs: selectedRatingsIDs,
selectionType: checkedState
}, function(data) {
data = JSON.parse(data);
//console.log( data );
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Selections - ' + ajaxError + '. Please contact the help desk';
return; // stop executing this function any further
} else {}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Selections - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the help desk';
$this.attr('checked', false); // Unchecks it
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<td id="RT12784" class="article-select form-check">
<label>
<input name="article-export" type="checkbox" value="RT12784">
<span> </span>
</label>
</td>
The selectedRatingsIDs variable is not getting populated – in this example it should be passing RT12784 to the script.
2
Answers
Since
$(this)
within your event handler refers to the DOMNode<td value="RT12784" class="article-select form-check">
, you cannot use$(this).val()
Since in your case, its a
<td>
node,.val()
will not work, and will returnundefined
.Instead you can use:
$(this).attr('value')
.A few corrections, it does not make sense to not have a table element outside td and $(this) refers to $("td.article-export").
Clean up a little bit your code and pay attention to nested check event. the rest of the code looks ok.
HTML:
JQuery:
I created a fiddle for you go to jsfiddle.net and append /#&togetherjs=9DxOs9F5ps to the URL