I need to get the values of the checked checkbox of 2 group of checkbox. These 2 groups aren't in the html file but they are generated with jquery when the page is loaded. I need 2 functions getSubjects() and getDates() that return the values of the relative checked checkbox group.
The HTML and JS that I use to generate them:
function loadAvailable() {
$.ajax({
url: "Controller",
type: "POST",
data: {action: "load"},
dataType: "json",
success: function (result) {
$("#listAvailable").html("");
var courses = getCourses(result);
if(courses.length == 0){
var sorry = "Some text.";
$("#listAvailable").text(sorry);
}
$("#subjects").html("");
addDates(result);
var len = courses.length;
for(var i=0; i<len; i++){
var course = courses[i];
addCourseCheckbox(course, "#subjects");
//other stuff
}
},
error: function (xhr, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function addDates(data){
$("#days").html("");
var res = new Array();
var i;
var len = data.length;
for(i=0; i<len; i++){
var date = data[i].date;
if(!res.includes(date)){
res.push(date);
var d = new Date();
d.setTime(date);
addDateCheckbox(d);
}
}
}
function addCourseCheckbox(course) {
var container = $("#subjects");
var inputs = container.find('input');
var id = inputs.length+1;
$('<input />', { type: 'checkbox',
id: 'ccb'+id,
name: 'subject',
value: course,
class: 'checkSub'}).appendTo(container);
$('<label />', { 'for': 'ccb'+id,
text: course }).appendTo(container);
}
//
function addDateCheckbox(data) {
var container = $("#days");
var inputs = container.find('input');
var id = inputs.length+1;
$('<input />', { type: 'checkbox',
id: 'dcb'+id,
name: 'date',
value: data.getTime(),
class: 'checkDay' }).appendTo(container);
$('<label />', { 'for': 'dcb'+id,
text: shortDate(data)}).appendTo(container);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<aside id="filter">
Filtra le disponibilià:<br>
Data<br>
<div class="filter" id="days"></div>
Materia<br>
<div class="filter" id="subjects"></div>
<button onclick="filterAvailable()">Filtra</button>
</aside>
I tried in Vanilla JS like this:
function getSubjects() {
var x = new Array();
[].forEach.call(document.querySelectorAll('input[name="subject"]:checked'), function(cb) {
x.push(cb.value);
});
return x;
}
and I tried this too:
var x = new Array();
$('input[name="subject"]:checked').each(function() {
x.push(this.value);
});
return x;
And this other version:
var x = $('input[name="subject"]:checked').serialize();
return x;
But nothing seems to work.
P.S. I used getSubjects() here as example and not both because they are equals.
Thanks in advance for the help.
Aucun commentaire:
Enregistrer un commentaire