I have an array of user id's like this:
var taskAssignTo = jQuery(this).attr('data-assigned');
var userArray = new Array();
userArray = taskAssignTo.split(",");
This gets a string of id's stored in the 'data-assigned' attr, which are separated by a comma.
I have tried the following to check each checkbox, if it's value is in the array, like this:
jQuery( ".assignTo input" ).each(function( index ) {
var val = jQuery( this ).val();
if(jQuery.inArray(val, userArray)){
jQuery( this ).prop('checked', true);
}
});
However this only checks the last item in the array.
If i was to console.log(val) like this:
jQuery( ".assignTo input" ).each(function( index ) {
var val = jQuery( this ).val();
console.log(val);
if(jQuery.inArray(val, userArray)){
jQuery( this ).prop('checked', true);
}
});
I can see that all results of the array are returned from the 'data-assigned' attr. If i move the console.log(val) to here:
jQuery( ".assignTo input" ).each(function( index ) {
var val = jQuery( this ).val();
if(jQuery.inArray(val, userArray)){
console.log(val);
jQuery( this ).prop('checked', true);
}
});
Again this only returns the last item in the array.
Anything obviously wrong with what i have done?
FIDDLE HERE: https://jsfiddle.net/Lvwhvadk/4/
1 Answer 1
Your first element is also matching but as quoted in https://api.jquery.com/jQuery.inArray/
If the first element within the array matches value, $.inArray() returns 0.
Which makes your if condition false. So your condition should be jQuery.inArray(val, userArray)!==-1
Instead of this, you can use Array.includes()
$(".editTask").click(function(event) {
var taskAssignTo = jQuery(this).attr('data-assigned');
var userArray = new Array();
userArray = taskAssignTo.split(",");
$(".assignTo input").each(function(index) {
var val = $(this).val();
if (userArray.includes(val)) {
$(this).prop('checked', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a title="Edit Task" href="#" data-id="1836" data-assign="" data-assigned="15,1" data-title="multiple users" data-content="<p>Task Description</p>" data-status="incomplete" class="editTask task-1836">EDIT</a>
<div class="assignTo">
<p>Assign Task To Users</p>
<label><input type="checkbox" name="project_assigned[]" value="15">User 15</label>
<label><input type="checkbox" name="project_assigned[]" value="1">User 1</label>
</div>
{}symbol in the editor.