Check Checkbox in jquery - javascript

This is my current code. What I am trying to accomplish is as follows.
If json[i].enabled is true, I need to check the corresponding checkbox. If not, leave it empty.
function createTable(json) {
var element = "";
var i;
for (i = 0; i < json.length; i++) {
element = element
+ '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
}
//Had forgotten to add this before.
element = element + '</tbody>';
$('#dataTable > tbody').remove();
$("#dataTable").append(element);
}
I tried it by including the following if condition but it fails.
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
So, how do I go about doing this? How do I access that particular checkbox in the loop?
Thanks!

Using string concatenation and a ternary operator:
'<tr><td><input type="checkbox"' + ( json[i].enabled== "TRUE" ? ' checked' : '' ) + '/></td><td>'

$('input[type="checkbox"]').prop('checked', true);
complete example:
var $table=jQuery('<table></table>');
for (i = 0; i < json.length; i++) {
var $tr=jQuery(
'<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>');
if(json[i].enabled== "TRUE"){
$tr.find('input["checkbox"]').prop('checked', true);
}
$table.append($tr);
}
$jQuery('body').append($table);

The checbox element has not been created yet in the DOM. So you have to put the html first. Then use
input[type="checkbox"]
to match an actual checkbox element. And at last, you might want to get the last checkbox only (in the last row of your table) with this selector :
mytable tbody tr:last input[type="checkbox"]
So you have the following code :
function createTable(json) {
var i;
for (i = 0; i < json.length; i++) {
// construct the html
element = '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
// put the html in the page
$('#mytable tbody').append(element);
if(json[i].enabled== "TRUE"){
// get the last inserted line in the table and check the checkbox
$('#mytable tbody tr:last input[type="checkbox"]').prop('checked', true);
}
}
}

Try this:
$('input[type="checkbox"]:eq(i)').prop('checked', true);

Related

Using variable for an identifier name (using jquery selectors)

Believe me, I've been looking for examples online for hours. None of them seem to help.
I'm working on making a table. There are some columns with dropdown menu and I've assigned ID to each menu. Inside a loop, I'm trying to assign selected value for each dropdown menu.
var row$ = $('<tr/>');
function updateDataBodyGenerator(myList) {
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
var colIndex = 0;
for (var key in myList[i]) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
var severityDropDownMenu = "severityDropDownMenu" + i;
colIndex++;
switch (key) {
case "Test Case":
...
break;
case "Test Result":
...
break;
case "Severity":
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>'+
'<option value="Yellow">Yellow</option>';
row$.append($(severitySting));
//failed
//$("#severityDropDownMenu" + i).val(cellValue);
//failed
//var selectorString = "#" + severityDropDownMenu.toString();
//$(selectorString).val("Green");
//failed
//$("#" + severityDropDownMenu).val(cellValue);
//failed
//var selectorString = '#' + severityDropDownMenu;
//$(selectorString).val(cellValue);
//works
//$('#severityDropDownMenu0').val(cellValue);
...
As you can see in the comments, I've tried several approaches and only 1 worked which was $('#severityDropDownMenu0').val(cellValue); but that will only change 1 dropdown menu.
I appreciate your time and assistance.
Currently you're trying to use the # selector to target the dropdown by ID.
The issue here (as mentioned in the comments) is that this selector will search the DOM for the element, however because you've never added this element to the DOM, it doesn't exist on the page; the selector will return nothing.
What you can do instead is actually turn your severitySting into a jQuery element to set its value. Whenever you do append it, the value will be properly set. Like so:
var $severity = $(severitySting); //This is the <td>
var $dropdown = $severity.find("select") //This is the <select>
$dropdown.val(cellValue); //Set dropdown value
Demo:
var severityDropDownMenu = "mytest";
var cellValue = "Yellow";
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>' +
'<option value="Yellow">Yellow</option>';
var $severity = $(severitySting);
var $dropdown = $severity.find("select");
$dropdown.val(cellValue);
$("tr").append($severity);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>

Skip some elements in an array through jquery

i'm designing a bus seat layout using jquery. And i done it correctly too.
I'm using an array with seat numbers and i'm getting the seat layout what i want. This is my coding (here '.bus-table' is a table class) :
var row = Array(),i=0, j=0;
row = [
['1','5','9','13','17','21','25','29','33','37','41','45','49'],
['2','6','10','14','18','22','26','30','34','38','42','46','50'],
['','','','','','','','','','','','','51'],
['3','7','11','15','19','23','27','31','35','39','43','47','52'],
['4','8','12','16','20','24','28','32','36','40','44','48','53']
];
$.each(row, function(index, value) {
$('.bus-table').append('<tr>');
while(j<index+1) {
for(i=0; i<value.length; i++) {
$('.bus-table tr:nth-child('+ (index+1) +')').append(
'<td seatno="'+ row[j][i] +'">' + row[j][i] + '<input type="checkbox"/></td>' );
}
j++;
}
});
This is my results : this is my seat layout output
Now the problem is In 3rd row you can see some checkboxes only. Because in those areas there are no seats in the bus. So, i want to remove those checkboxes, which means in the array (3rd row) i left some blanks, according to those blanks i don't want the checkboxes too. I don't know how to do that. Please help me to solve this case.
(I apologies for my English)
Add an if statement inside the for loop:
for(i=0; i<value.length; i++) {
if (row[j][i] !== '') {
$('.bus-table tr:nth-child('+ (index+1) +')').append(
'<td seatno="'+ row[j][i] +'">' + row[j][i] + '<input type="checkbox"/></td>' );
}
else {
$('.bus-table tr:nth-child('+ (index+1) +')').append('<td></td>');
}
}
Note the else statement, otherwise it will break your table layout
You can skip those places using continue like shown below:
for(i=0; i<value.length; i++) {
if (row[j][i] == ""){
'<td seatno="'+ row[j][i] +'">' + row[j][i] + '</td>';
continue;//for blank don't make checkbox elements
}
$('.bus-table tr:nth-child('+ (index+1) +')').append(
'<td seatno="'+ row[j][i] +'">' + row[j][i] + '<input type="checkbox"/></td>' );
}

My JavaScript/AJAX function only works while debugging

I am not very familiar with JavaScript and AJAX.
I am developing a webpage that displays information return by a ยง.getJSON / JQuery request. But this function only works, when I start debugging. I know that the debugger corrects the timing and scope from other post on this topic. But I cannot find my mistake. I do not realy need a long explaination, because as I said before I am not very familiar with JavaScript/AJAX. This is the script-part in the page (you can ignore the addDropDown() and the departmentSelected() functions(as far as i know)):
<script type="text/javascript">
var isSelected = [];
$(addDropDown);
function addDropDown(){
$.getJSON("./api/persence/departments/all", function(data, status){
if(status !== "success"){
alert(status);
}else{
var dropdownHead = "<button class='btn btn-primary dropdown-toggle' type='button' data-toggle='dropdown'>Abteilungen<span class='caret'><\/span><\/button>";
var dropdownBody = "<ul class='dropdown-menu'>";
var i;
for(i = 0; i < data.length; i++){
dropdownBody = dropdownBody + "<li><a href='javascript:departmentSelected(" + i + "," + data[i].departmentId + ");'>";
dropdownBody = dropdownBody + data[i].departmentName;
dropdownBody = dropdownBody + " - ";
dropdownBody = dropdownBody + data[i].departmentCity;
dropdownBody = dropdownBody + "<\/a><\/li>";
}
dropdownBody = dropdownBody + "<\/ul>";
dropdownHead = dropdownHead + dropdownBody;
$("#dropdown-list").append(dropdownHead);
isSelected.length = i + 1;
}
});
}
function departmentSelected(position, value){
if((isSelected[position] !== value)){
isSelected[position] = value;
}else{
isSelected[position] = "false";
}
loadTable();
}
function loadTable(){
var tHead = "<br><div class='table-responsive'><table class='table'><thead><tr><th>#</th><th>Name<\/th><th>Beruf<\/th><th>Anwesend<\/th><th>Arbeitsplatz<\/th><\/tr><\/thead>";
var tBody = "<tbody>";
for(var i = 0; i < isSelected.length; i++){
var counter = 0;
if(isSelected[i] !== "false"){
$.getJSON("./api/persence/departments/" + isSelected[i]).then(function(result, status){
if(status !== "success"){
alert(status);
}else{
for(var i = 0; i < result.length; i++) {
var employee = result[i];
tBody = tBody + "<tr> <td>" + counter + "<\/td>";
tBody = tBody + "<td>" + employee.academicTitle + " " + employee.lastName + " " + employee.firstName + "<\/td>";
tBody = tBody + "<td>" + employee.job + "<\/td>";
tBody = tBody + "<td>";
if(employee.persenceStatus === "Y"){
tBody = tBody + employee.persenceSince;
}else{
// if(employee.absenceReason !== null){
tBody = tBody + employee.absenceReason;
// }
//else{
// tBody = tBody + " ";
//}
}
tBody = tBody + "<\/td>";
tBody = tBody + "<td>" + employee.workplace + "<\/td>";
tBody = tBody + "<\/tr>";
counter++;
}
}
});
}
}
tBody = tBody + "<\/tbody> <\/table> <\/div>";
tHead = tHead + tBody;
document.getElementById("outputTable").innerHTML = tHead;
}
My Problem: I can not find what I have done wrong in this scriptpart, because the debugger (firebug) is able to optimize the code while debugging so it works perfectly fine. But if I am not in debug-mode, only the "head-line" of the table is displayed (the information is missing).
Thanks for your help.
This problem is about the finding element in DOM. Sometimes Js faster than DOM and Js can't find specific element in html DOM. You need to define js code in onLoad.
$(function() {
$(addDropDown);
});
OR
$(document).ready(function(){
$(addDropDown);
});
Inportant Info: If you include jQuery don't use JS specific functions. Sometimes it crash with jquery. Just use jQuery functions.
Example:
not good : document.getElementById("outputTable")
good : '$.("#outputTable")'
Ok, I solved the problem myself: I had to put the following part into the function called by the jQuery request (function(result, status).....)
tBody = tBody + "</tbody> </table> </div>";
tHead = tHead + tBody;
document.getElementById("outputTable").innerHTML = tHead;

How to make list in jQuery mobile nested list?

Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}

Creating html table using Javascript not working

Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE

Categories

Resources