Weird JS Behavior With Bootstrap Sliders - javascript

So I recieved help from an internet saint to vastly improve my code to create a bootstrap slider per list item within a JS for loop, but now it is behaving erratically.
Sometimes it works perfectly, others it creates new items but not sliders (just a text input field), and others it only creates one item per list.
Any great minds see where I'm going wrong?
var proArray = [];
function addPro() {
var val = document.getElementById("proInput").value.trim();
document.getElementById("proForm").reset();
if (val.length == 0) {
return;
}
if (document.getElementById('proInput' + val) == null) {
proArray.push({id: val, slider: null});
} else {
return;
}
for (var i = 0; i < proArray.length; i++) {
var ele = document.getElementById('proInput' + proArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + proArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='proInput" +
proArray[i].id + "' data-slider-id='SIDproInput" + proArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("proList").innerHTML += newItem;
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var val = proArray[i].slider.getValue();
proArray[i].slider.destroy();
document.getElementById('SIDproInput' + proArray[i].id).remove();
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
proArray[i].slider.setValue(val);
}, 100);
})(i);
}
}
}
var conArray = [];
function addCon() {
var valCon = document.getElementById("conInput").value.trim();
document.getElementById("conForm").reset();
if (valCon.length == 0) {
return;
}
if (document.getElementById('conInput' + valCon) == null) {
conArray.push({id: valCon, slider: null});
} else {
return;
}
for (var i = 0; i < conArray.length; i++) {
var ele = document.getElementById('conInput' + conArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + conArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='conInput" +
conArray[i].id + "' data-slider-id='SIDconInput" + conArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("conList").innerHTML += newItem;
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var valCon = conArray[i].slider.getValue();
conArray[i].slider.destroy();
document.getElementById('SIDconInput' + conArray[i].id).remove();
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
conArray[i].slider.setValue(valCon);
}, 100);
})(i);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="addPro()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="addCon()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div> <!-- cons -->

Because you have two lists you can use two arrays:
var proArray = [];
var conArray = [];
The inline functions can be changed in order to pass the list prefix as parameter:
newAdd('pro')
newAdd('con')
And so you can adjust the addPro function to these changes.
From comment:
If I type in "#" or "?" as an item in your snippet above it shows the error. Not for you?
In order to solve such an issue you need to escape those chars when creating the slider:
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' +
arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').....
The snippet:
var proArray = [];
var conArray = [];
function newAdd(listIdPrefix) {
var val = document.getElementById(listIdPrefix + "Input").value.trim();
document.getElementById(listIdPrefix + "Form").reset();
if (val.length == 0) {
return;
}
var arr;
if (document.getElementById(listIdPrefix + 'Input' + val) == null) {
if (listIdPrefix == 'pro') {
proArray.push({id: val, slider: null});
arr = proArray;
} else {
conArray.push({id: val, slider: null});
arr = conArray;
}
} else {
return;
}
for (var i = 0; i < arr.length; i++) {
var ele = document.getElementById(listIdPrefix + 'Input' + arr[i].id);
if (ele == null) {
var newItem = "<li><p>" + arr[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='" + listIdPrefix + "Input" +
arr[i].id + "' data-slider-id='SID" + listIdPrefix + "Input" + arr[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById(listIdPrefix + "List").innerHTML += newItem;
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
} else {
(function (i, arr) {
setTimeout(function () {
var val = arr[i].slider.getValue();
arr[i].slider.destroy();
document.getElementById('SID' + listIdPrefix + 'Input' + arr[i].id).remove();
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
arr[i].slider.setValue(val);
}, 100);
})(i, arr);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('pro')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('con')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div>

Related

Can't add more than 10 rows to my datatable

I want to add dynamically rows to my DataTable to save them, but when I achieve 10 rows I can't get more than that, and it can't even save it.
// Add row into table
var addRowTable = {
options: {
addButton: "#addToTable",
table: "#addrowExample",
dialog: {}
},
initialize: function() {
this.setVars().build().events()
},
setVars: function() {
return this.$table = $(this.options.table), this.$addButton = $(this.options.addButton), this.dialog = {}, this.dialog.$wrapper = $(this.options.dialog.wrapper), this.dialog.$cancel = $(this.options.dialog.cancelButton), this.dialog.$confirm = $(this.options.dialog.confirmButton), this
},
build: function() {
//var window.table = this.datatable;
return this.datatable = this.$table.DataTable({
aoColumns: [null, null, null, null, null, null, {
bSortable: !1
}],
"sDom": 't'
}), window.dt = this.datatable, this
},
events: function() {
var object = this;
return this.$table.on("click", "button.button-save", function(e) {
e.preventDefault(), object.rowSave($(this).closest("tr"))
}).on("click", "button.button-discard", function(e) {
e.preventDefault(), object.rowCancel($(this).closest("tr"))
}).on("click", "button.button-remove", function(e) {
e.preventDefault();
var $row = $(this).closest("tr");
var sumToRemove = $(this).closest('tr').find('td:eq(5)').text();
//Update sum value
Application.sumCharge -= parseFloat(sumToRemove);
$("#lb-sum").html(Application.sumCharge.toFixed(2));
object.rowRemove($row)
}), this.$addButton.on("click", function(e) {
e.preventDefault(), object.rowAdd()
}), this.dialog.$cancel.on("click", function(e) {
e.preventDefault(), $.magnificPopup.close()
}), this
},
rowAdd: function() {
this.$addButton.attr({
disabled: "disabled"
});
var actions, data, $row;
actions = ['<button class="btn btn-sm btn-icon btn-pure btn-default on-editing button-save" data-toggle="tooltip" data-original-title="Save" hidden><i class="icon-drawer" aria-hidden="true"></i></button>', '<button class="btn btn-sm btn-icon btn-pure btn-default on-editing button-discard" data-toggle="tooltip" data-original-title="Discard" hidden><i class="icon-close" aria-hidden="true"></i></button>', '<button class="btn btn-sm btn-icon btn-pure btn-default on-default button-remove"><i class="icon-trash" aria-hidden="true"></i></button>'].join(" "), data = this.datatable.row.add(["", "", "", "", "", "", actions]), ($row = this.datatable.row(data[0]).nodes().to$()).addClass("adding").find("td:last").addClass("actions"), this.rowEdit($row), this.datatable.order([0, "asc"]).draw()
},
rowCancel: function($row) {
var $actions, data;
$row.hasClass("adding") ? this.rowRemove($row) : (($actions = $row.find("td.actions")).find(".button-discard").tooltip("hide"), $actions.get(0) && this.rowSetActionsDefault($row), data = this.datatable.row($row.get(0)).data(), this.datatable.row($row.get(0)).data(data), this.handleTooltip($row), this.datatable.draw())
},
rowEdit: function($row) {
var counter = 0;
var data, object = this;
data = this.datatable.row($row.get(0)).data(), $row.children("td").each(function(i) {
var $this = $(this);
if (counter == 0) {
Application.tableLength++;
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<label style="font-weight: 400 !important">' + Application.tableLength + '</label>');
} else if (counter > 0 && counter < 5) {
if (counter == 1) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" data-provide="datepicker" data-date-autoclose="true" class="form-control input-date" value="' + data[i] + '" required>');
} else if (counter == 2) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="text" class="form-control" value="' + data[i] + '" required>');
} else if (counter == 3) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="text" class="form-control" value="' + data[i] + '" required>');
} else if (counter == 4) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="text" class="form-control" value="' + data[i] + '" required>');
}
} else {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="number" step="0.01" class="form-control" value="' + data[i] + '" required>');
}
counter++;
})
},
rowSave: function($row) {
if ($('#form').get(0).reportValidity()) {
var $actions, object = this,
values = [],
counter = 0;
$row.hasClass("adding") && (this.$addButton.removeAttr("disabled"), $row.removeClass("adding")), values = $row.find("td").map(function() {
var $this = $(this),
input = '',
input_value = $this.find("label,input,textarea").val();
if ($this.hasClass("actions")) {
return object.rowSetActionsDefault($row), object.datatable.cell(this).data();
} else {
if (counter == 0) {
input = $this.find("label").text();
} else if (counter > 0 && counter < 5) {
if (counter == 1) {
input = "<input type='hidden' name='date[]' value='" + input_value + "'>";
}
if (counter == 2) {
input = "<input type='hidden' name='description[]' value='" + input_value + "'>";
} else if (counter == 3) {
input = "<input type='hidden' name='details[]' value='" + input_value + "'>";
} else if (counter == 4) {
input = "<input type='hidden' name='charge_observation[]' value='" + input_value + "'>";
}
} else {
input = "<input type='hidden' name='sum[]' value='" + input_value + "'>";
Application.sumCharge += parseFloat(input_value);
$("#lb-sum").html(Application.sumCharge.toFixed(2));
}
counter++;
return $.trim($this.find("label,input,textarea").val()) + input;
}
}), ($actions = $row.find("td.actions")).find(".button-save").tooltip("hide"), $actions.get(0) && this.rowSetActionsDefault($row), this.datatable.row($row.get(0)).data(values), this.handleTooltip($row), this.datatable.draw()
}
},
rowRemove: function($row) {
$row.hasClass("adding") && this.$addButton.removeAttr("disabled"), this.datatable.row($row.get(0)).remove().draw()
},
rowSetActionsEditing: function($row) {
$row.find(".on-editing").removeAttr("hidden"), $row.find(".on-default").attr("hidden", !0)
},
rowSetActionsDefault: function($row) {
$row.find(".on-editing").attr("hidden", !0), $row.find(".on-default").removeAttr("hidden")
},
handleTooltip: function($row) {
$row.find('[data-toggle="tooltip"]').tooltip()
}
};
$(function() {
addRowTable.initialize()
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped fixed" cellspacing="0" id="addrowExample">
<thead>
<tr>
<th style="width: 5%">#</th>
<th>{{ __('all.date')}}</th>
<th>{{ __('all.description')}}</th>
<th>{{ __('all.details')}}</th>
<th style="width: 25%">{{ __('all.observation')}}</th>
<th>{{ __('all.sum')}}</th>
<th style="width: 10%">{{ __('all.action')}}</th>
</tr>
</thead>
<tbody>
</tbody>
<tbody>
</tbody>
</table>
<h6 class="p-10 bg-primary text-light text-right">{{ __('all.total sum')}} : <b id="lb-sum">0.00</b> <small>MAD</small></h6>
</div>

Computer Guess A Number JavaScript

I am trying to create a simple "guess the number game" in a web page where a user is the one thinking of the number and the computer is to guess the number(in range 1-100) that the user is thinking (no user input required). I've created four buttons for user to respond to the computer's guess: Start, Guess Higher, Guess Lower, Bingo. I have a problems with this range. If user click button 'Lover' it should became the biggest number (For example, 60 is too high, then computer guess between 1-60)(same with 'Higher'), but can't connect it together. Here is my code:
let computerGuess = 0,
numberOfGuesses = 0;
function writeMessage(elementId, message, appendMessage) {
let elemToUpdate = document.getElementById(elementId);
if (appendMessage) {
elemToUpdate.innerHTML = elemToUpdate.innerHTML + message;
} else {
elemToUpdate.innerHTML = message;
}
};
function newGame() {
computerGuess = 0;
numberOfGuesses = 1;
writeMessage('historyList', '');
document.getElementById('buttonLover').disabled = true;
document.getElementById('buttonHigher').disabled = true;
document.getElementById('buttonBingo').disabled = true;
}
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function computerGuessed() {
let compGuess = document.getElementById('compGuess'),
butLover = document.getElementById('buttonLover'),
butHigher = document.getElementById('buttonHigher'),
butBingo = document.getElementById('buttonBingo'),
statusArea = document.getElementById('statusArea'),
historyList = document.getElementById('historyList');
document.getElementById('buttonArea').disabled = true;
butLover.disabled = false;
butHigher.disabled = false;
butBingo.disabled = false;
let a = 1, b = 100;
computerGuess = randomNumber(a, b);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
writeMessage('statusArea', '<p>Choose a number between 1-100 and click the button.</p>');
butLover.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too high)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
computerGuess = randomNumber(a, computerGuess);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butHigher.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too low)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
computerGuess = randomNumber(computerGuess, b);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butBingo.addEventListener("click", function () {
writeMessage('statusArea', '<p>You got me in ' + numberOfGuesses + ' guesses, I was thinking ' + computerGuess + '. Let\'s go again...</p>');
writeMessage('compGuess', '<p>' + '' + '</p>', false);
document.getElementById('buttonArea').disabled = false;
newGame();
});
}
window.onload = function () {
newGame();
document.getElementById('buttonArea').addEventListener('click', computerGuessed);
};
<div id="game">
<h1>Computer Guessing Game</h1>
<div id="statusArea">
<p>Choose a number between 1-100 and click the button.</p>
</div>
<div id="compGuess">
</div>
<div class="buttons">
<input type="button" value="Start" class="button" id="buttonArea"/>
<input type="button" value="Lover" class="button" id="buttonLover"/>
<input type="button" value="Higher" class="button" id="buttonHigher"/>
<input type="button" value="Bingo" class="button" id="buttonBingo"/>
</div>
<div id="historyArea">
<h2>Computer Previous Guesses</h2>
<ol id="historyList">
</ol>
</div>
</div>
Each time you call computerGuessed() you reset a & b to 1 and 100. Try setting them as global vars (since you're already using global vars), and set them to 1 and 100 on the start of each game.
let computerGuess = 0,
numberOfGuesses = 0,
a=0,
b=100;
function writeMessage(elementId, message, appendMessage) {
let elemToUpdate = document.getElementById(elementId);
if (appendMessage) {
elemToUpdate.innerHTML = elemToUpdate.innerHTML + message;
} else {
elemToUpdate.innerHTML = message;
}
};
function newGame() {
computerGuess = 0;
numberOfGuesses = 1;
a = 0;
b = 100;
writeMessage('historyList', '');
document.getElementById('buttonLower').disabled = true;
document.getElementById('buttonHigher').disabled = true;
document.getElementById('buttonBingo').disabled = true;
}
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function computerGuessed() {
let compGuess = document.getElementById('compGuess'),
butLower = document.getElementById('buttonLower'),
butHigher = document.getElementById('buttonHigher'),
butBingo = document.getElementById('buttonBingo'),
statusArea = document.getElementById('statusArea'),
historyList = document.getElementById('historyList');
document.getElementById('buttonArea').disabled = true;
butLower.disabled = false;
butHigher.disabled = false;
butBingo.disabled = false;
computerGuess = randomNumber(a, b);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
writeMessage('statusArea', '<p>Choose a number between 1-100 and click the button.</p>');
}
window.onload = function () {
newGame();
document.getElementById('buttonArea').addEventListener('click', computerGuessed);
let butLower = document.getElementById('buttonLower'),
butHigher = document.getElementById('buttonHigher'),
butBingo = document.getElementById('buttonBingo');
butLower.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too high)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
b = computerGuess;
computerGuessed();
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butHigher.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too low)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
a = computerGuess;
computerGuessed();
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butBingo.addEventListener("click", function () {
writeMessage('statusArea', '<p>You got me in ' + numberOfGuesses + ' guesses, I was thinking ' + computerGuess + '. Let\'s go again...</p>');
writeMessage('compGuess', '<p>' + '' + '</p>', false);
document.getElementById('buttonArea').disabled = false;
newGame();
});
};
<div id="game">
<h1>Computer Guessing Game</h1>
<div id="statusArea">
<p>Choose a number between 1-100 and click the button.</p>
</div>
<div id="compGuess">
</div>
<div class="buttons">
<input type="button" value="Start" class="button" id="buttonArea"/>
<input type="button" value="Lower" class="button" id="buttonLower"/>
<input type="button" value="Higher" class="button" id="buttonHigher"/>
<input type="button" value="Bingo" class="button" id="buttonBingo"/>
</div>
<div id="historyArea">
<h2>Computer Previous Guesses</h2>
<ol id="historyList">
</ol>
</div>
</div>
This version disables lower/higher buttons if we've already ruled out those possibilities, and it detects bingo automatically if there is no other option left.
//initialize global variables to keep track of stuff between functions
var min = 1;
var max = 100;
var currentGuess = -1;
function start() {
//reset everything
min = 1;
max = 100;
document.getElementById("historyList").innerHTML = "";
disable("startButton");
enable("lowerButton");
enable("higherButton");
enable("bingoButton");
//and guess
guess();
}
function guess() {
//generate a guess between min and max
currentGuess = rando(min, max);
//disable higher/lower buttons if we've ruled out those possibilities
currentGuess == min ? disable("lowerButton") : enable("lowerButton");
currentGuess == max ? disable("higherButton") : enable("higherButton");
//tell the user the guess
document.getElementById("compGuess").innerHTML = currentGuess;
}
function lower() {
//our guess was too high, so our new max is one lower than that guess
max = currentGuess - 1;
//automatically detect bingo if it's the only possible outcome left and don't bother executing the rest of the lower function
if (max == min) {
currentGuess = min;
return bingo();
}
//record that the guess was too high
document.getElementById("historyList").innerHTML += "<li>" + currentGuess + " (too high)</li>";
guess();
}
function higher() {
//our guess was too low, so our new min is one higher than that guess
min = currentGuess + 1;
//automatically detect bingo if it's the only possible outcome left and don't bother executing the rest of the higher function
if (max == min) {
currentGuess = min;
return bingo();
}
//record that the guess was too low
document.getElementById("historyList").innerHTML += "<li>" + currentGuess + " (too low)</li>";
guess();
}
function bingo() {
//record that the guess was a bingo
document.getElementById("historyList").innerHTML += "<li>" + currentGuess + " (BINGO)</li>";
//only allow start button
enable("startButton");
disable("lowerButton");
disable("higherButton");
disable("bingoButton");
//give the user a breakdown
document.getElementById("compGuess").innerHTML = "You got me in " + document.getElementsByTagName("li").length + " guesses. I was thinking " + currentGuess + ". Let's go again...";
}
//these two functions just make our code easier to read
function disable(id) {
document.getElementById(id).disabled = true;
}
function enable(id) {
document.getElementById(id).disabled = false;
}
<script src="https://randojs.com/1.0.0.js"></script>
<div id="game">
<h1>Computer Guessing Game</h1>
<div id="statusArea">
<p>Choose a number between 1-100 and click the button.</p>
</div>
<div id="compGuess"></div>
<div class="buttons">
<input type="button" value="Start" id="startButton" onclick="start();" />
<input type="button" value="Lower" id="lowerButton" onclick="lower();" disabled/>
<input type="button" value="Higher" id="higherButton" onclick="higher();" disabled/>
<input type="button" value="Bingo" id="bingoButton" onclick="bingo();" disabled/>
</div>
<div id="historyArea">
<h2>Computer Previous Guesses</h2>
<ol id="historyList"></ol>
</div>
</div>
It uses randojs.com to make the randomness easier to read, so if you use this code, make sure you have this in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
try the following ...
start.html
<!DOCTYPE html>
<html>
<head>
<script>
function StartGame()
{
aMaxValue = Number(theMaxValueText.value);
window.localStorage.setItem ("theMaxValueToGuess", aMaxValue);
aNumberToGuess = Math.floor ( Math.random() * aMaxValue + 1 );
window.localStorage.setItem ("theNumberToGuess", aNumberToGuess);
aMaxNumberOfTries = Math.floor ( Math.log2 (aMaxValue) + 1 );
window.localStorage.setItem ("theMaxNumberOfTries", aMaxNumberOfTries);
window.localStorage.setItem ("theUserTriesCount", 0);
aPrevGuessesString = "";
window.localStorage.setItem ("thePrevGuessesString", aPrevGuessesString);
document.location.href = "play.html";
}
</script>
</head>
<body>
<h1>Guess a Number</h1>
<div class="form">
<label for="theMaxValueText">Max Value to Guess:</label>
<input type="text" id="theMaxValueText">
<input type="submit" value="Play" id="ExecPlayBtn" onclick="StartGame()">
</div>
</body>
</html>
play.html
<!DOCTYPE html>
<html>
<head>
<script>
var theMaxNumberToGuess = Number ( window.localStorage.getItem ("theMaxValueToGuess") );
// let theMaxNumberOfTries = 0;
// let theNumberToGuess = 0;
// let theUserTriesCount = 0;
function getMaxNumberOfTries() {
return Number ( window.localStorage.getItem ("theMaxNumberOfTries") );
}
function getNumberToGuess() {
return Number ( window.localStorage.getItem ("theNumberToGuess") );
}
function getUserTriesCount() {
return Number ( window.localStorage.getItem ("theUserTriesCount") );
}
function incrUserTriesCount()
{
aUserTriesCount = getUserTriesCount();
++ aUserTriesCount;
window.localStorage.setItem ("theUserTriesCount", aUserTriesCount);
}
function getNumberOfTriesLeft()
{
aMaxNumberOfTries = getMaxNumberOfTries();
aUserTriesCount = getUserTriesCount();
aNumberOfTriesLeft = aMaxNumberOfTries - aUserTriesCount;
return aNumberOfTriesLeft;
}
function getPrevGuessesString() { return window.localStorage.getItem ("thePrevGuessesString"); }
function addToPrevGuessesString (aStr)
{
aPrevGuessesString = getPrevGuessesString();
aPrevGuessesString += (aStr + " ");
window.localStorage.setItem ("thePrevGuessesString", aPrevGuessesString);
}
function PageLoaded()
{
document.getElementById("theMaxNumberToGuessLabel").innerHTML = theMaxNumberToGuess;
// compute values ...
// theNumberToGuess = Math.floor ( Math.random() * theMaxNumberToGuess + 1 );
// theMaxNumberOfTries = Math.floor ( Math.log2 (theMaxNumberToGuess) + 1 );
// theUserTriesCount = 0;
DisplayGameStatus();
}
window.addEventListener ("load", PageLoaded);
function DisplayNumberOfTriesLeft()
{
aNumberOfTriesLeft = getNumberOfTriesLeft();
document.getElementById("theTriesLeftCountLabel").innerHTML = aNumberOfTriesLeft;
}
function DisplayPrevUserGuesses()
{
aPrevGuessesString = getPrevGuessesString();
document.getElementById("theUserPrevGuessesLabel").innerHTML = aPrevGuessesString;
}
function DisplayGameStatus()
{
DisplayNumberOfTriesLeft();
DisplayPrevUserGuesses();
}
function CheckUserGuess()
{
aNumberOfTriesLeft = getNumberOfTriesLeft();
if (aNumberOfTriesLeft <= 0) {
// go to the loose page
}
aNumberToGuess = getNumberToGuess();
aUserGuess = Number(theUserValueText.value);
addToPrevGuessesString ("" + aUserGuess);
if (aUserGuess < aNumberToGuess) {
// retry
document.getElementById("theUserHintMessageLabel").innerHTML =
"retry, the number to guess is > higher"
} else if (aUserGuess > aNumberToGuess) {
// retry
document.getElementById("theUserHintMessageLabel").innerHTML =
"retry, the number to guess is < lower"
} else {
// the user wins !!
document.getElementById("theUserHintMessageLabel").innerHTML =
"you win !! " + aUserGuess + " == " + aNumberToGuess + ""
alert ("you win !! " + aUserGuess + " == " + aNumberToGuess + "");
// go to the win page ...
document.location.href = "youwin.html";
}
// ++ theUserTriesCount;
incrUserTriesCount();
aNumberOfTriesLeft = getNumberOfTriesLeft();
if (aNumberOfTriesLeft <= 0) {
// go to the loose page
document.location.href = "youloose.html";
}
DisplayGameStatus();
}
</script>
</head>
<body>
<div>
<h1>
<label>Guess a Number in the Range ( 0 .. </label>
<label id="theMaxNumberToGuessLabel"></label>
<label>)</label>
</h1>
</div>
<div>
<label>you have </label>
<label id="theTriesLeftCountLabel"></label>
<label> tries left</label>
</div>
<p></p>
<div>
<label for="theUserValueText">Enter your Guess: </label>
<input type="text" id="theUserValueText">
<input type="submit" value="Guess" id="ExecUserGuessBtn" onclick="CheckUserGuess()">
</div>
<p></p>
<div>
<label>Prev Guesses: </label>
<label id="theUserPrevGuessesLabel"></label>
</div>
<p></p>
<div>
<label id="theUserHintMessageLabel"></label>
</div>
</body>
</html>
youloose.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<h1>
<label>Sorry, You Loose !!</label>
<label>go to </label> Start
</h1>
</div>
</body>
</html>
youwin.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<h1>
<label>Congrats, You Win !!</label>
<label>go to </label> Start
</h1>
</div>
</body>
</html>
that's all folks ...

How can i call javaScript function in iOS Swift

i am trying to get html string from a web view. i try to get html string from web view like,
let html = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
print(html)
in this code i get all Html code without the input value what i given after web loading.
on the other hand there is function which that will give me full html code with input value. but i was unable to call javascript function in my swift code.also my javaScript function have a parameter which one i want to call.
i was try to call javaSript function like this,
let pp = webView.stringByEvaluatingJavaScript(from:"draft")
But its not working. i want to get all of html including input value.
Here is a Screenshot how it's done in android.
i was attach all of my html code here
<!DOCTYPE html>
<html lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html charset=UTF-8'/>
<link type='text/css' rel='stylesheet' href='file:///android_asset/bootstrap.min.css'>
<script src="file:///android_asset/jquery.min.js"></script>
<title>Quick Inspection</title>
<style>
textarea{
resize: none;
}
</style>
</head>
<body style='background: #fff3d6'>
<div class='container-fluid' style='padding-top: 10px; padding-left: 0px; padding-right: 0px; background: #fff3d6'>
<div class='container'>
<div class='row'>
<form id='rendered-form'>
<div class='rendered-form'>
<div class='fb-textarea form-group field-textarea-1505524302868'>
<label for='textarea-1505524302868' class='fb-textarea-label'>1. Description of Work</label>
<textarea class='form-control textarea' name='textarea-1505524302868' id='textarea-1505524302868'></textarea>
</div>
<div class='fb-textarea form-group field-textarea-1505524384468'>
<label for='textarea-1505524384468' class='fb-textarea-label'>2. Work Status</label>
<textarea class='form-control textarea' name='textarea-1505524384468' id='textarea-1505524384468'></textarea>
</div>
<div class='fb-textarea form-group field-textarea-1505524405168'>
<label for='textarea-1505524405168' class='fb-textarea-label'>3. Progress</label>
<textarea class='form-control textarea' name='textarea-1505524405168' id='textarea-1505524405168'></textarea>
</div>
<div class='fb-textarea form-group field-textarea-1505524418785'>
<label for='textarea-1505524418785' class='fb-textarea-label'>4. Observation</label>
<textarea class='form-control textarea' name='textarea-1505524418785' id='textarea-1505524418785'></textarea>
</div>
<div class='fb-textarea form-group field-textarea-1505524433458'>
<label for='textarea-1505524433458' class='fb-textarea-label'>5. Recommendation</label>
<textarea class='form-control textarea' name='textarea-1505524433458' id='textarea-1505524433458'></textarea>
</div>
</div>
</form>
</div>
</div>
<div class="clearfix"></div>
</div>
<div id="jsonvalue" style="visibility: hidden; display:inline;"></div>
</body>
<script>
var getJsonData = $("#jsonvalue").text();
if(getJsonData != ""){
SetJsonValue();
}
function getHtml()
{
var Alldata = $('form').serializeArray();
var JsonString = JSON.stringify(Alldata);
$("div#jsonvalue").text(JsonString);
var allCode = document.documentElement.outerHTML;
return allCode;
}
function SetJsonValue()
{
var getJsonData = $("#jsonvalue").text();
var obj = $.parseJSON(getJsonData), dataObj = {};
len = obj.length;
for (i = 0; i < len; i++) {
var f_name = obj[i].name;
var f_value = obj[i].value;
var result = f_name.split('-');
var type = result[0];
if (type == 'textarea') {
$("#rendered-form " + type + "[name = " + f_name + "]").text(f_value);
} else if (type == 'text') {
$("input[name = " + f_name + "]").val(f_value);
} else if (type == 'radio') {
$('#rendered-form input[name=' + f_name + '][value=' + f_value + ']').prop("checked", true);
} else if (type == 'select') {
$("#rendered-form " + type + "[name = " + f_name + "]").val(f_value);
} else {
$(":checkbox[value=" + f_value + "]").prop("checked","true");
}
}
}
function draft(){
var getAllHtmlCode = getHtml();
Android.fullCode(getAllHtmlCode);
}
function finalsave(){
var obj = $('form').serializeArray();
len = obj.length;
//$( ".fb-radio-group").hide();
for (i = 0; i < len; i++) {
var f_name = obj[i].name;
var f_value = obj[i].value;
var result = f_name.split('-');
var type = result[0];
if (type == 'textarea') {
//if( f_value == "") {
// $( ".field-textarea-"+result[1]).hide();
//}else{
var bodyText = f_value;
var body = $("<div class='ans'> </div>");
body.text(bodyText);
$("#rendered-form " + type + "[name = " + f_name + "]").replaceWith(body);
//}
} else if (type == 'text') {
//if( f_value == "") {
// $( ".field-text-"+result[1]).hide();
//}else{
var bodyText = f_value;
var body = $("<div class='ans'> </div>");
body.text(bodyText);
$("input[name = " + f_name + "]").replaceWith(body);
//}
} else if (type == 'radio') {
//$(".l_header").hide();
//$(".field-radio-group-"+result[2]).prev().show();
//$(".field-radio-group-"+result[2]).show();
var r_value = $('#rendered-form input[name=' + f_name + ']:checked').val();
$('#rendered-form input[name=' + f_name + ']').parent().hide();
$("label[for='"+f_name+"']").append('<div class="ans">'+r_value+'</div>');
} else if (type == 'select') {
if( f_value == "" || f_value == "0") {
//$( ".field-select-"+result[1]).hide();
}else{
var lbl = $("#rendered-form " + type + "[name = " + f_name + "]").find('option:selected').text();
var body = $("<div class='ans'> </div>");
body.text(lbl);
$("#rendered-form " + type + "[name = " + f_name + "]").replaceWith(body);
}
} else {
$(":checkbox[value=" + f_value + "]").prop("checked","true");
}
}
var allCode = document.getElementById("rendered-form").outerHTML;
Android.finalCode(allCode);
}
</script>
</html>

Only 1 result from JSON array

In my getValueByKey function, I want to output 5 different items and their attributes, but my for loop only seems to allow me to choose one at a time.
When I change to i = 4 it will go to the 5th item. I just want to output all instead of choosing just one.
Any help is appreciated. Thank you very much.
window.onload = function() {
var getJSON = function (url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', url, true);
xhr.setRequestHeader("X-Algolia-Application-Id", apiApplicationId);
xhr.setRequestHeader("X-Algolia-API-Key", apiKey);
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
var status;
var data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
successHandler && successHandler(xhr.response);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
var search = document.getElementById('search');
search.addEventListener('keyup', function() {
getJSON(apiEndpoint, function(data) {
function getValueByKey(key, data) {
var i, len = data.length;
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
return data[i][key];
}
}
return -1;
}
document.getElementById('item-wrapper').innerHTML =
'<div class="col-sm-4">' +
'<img src="path/to-image.jpg">' +
'</div>' +
'<div class="col-sm-8">' +
'<ul>' +
'<li><strong>Bag Brand:</strong> <span id="search-results-brand"></span></li>' +
'<li><strong>Bag ID:</strong> <span id="search-results-id"></span></li>' +
'<li><strong>Bag Color:</strong> <span id="search-results-color"></span></li>' +
'<li><strong>Bag Description:</strong> <span id="search-results-description"></span></li>' +
'<li><strong>Bag Material:</strong> <span id="search-results-material"></span></li>' +
'<li><strong>Bag Price:</strong> $<span id="search-results-price"></span></li>' +
'</ul>' +
'</div>';
output_id = getValueByKey('id', data.hits);
output_brand = getValueByKey('brand', data.hits);
output_color = getValueByKey('color', data.hits);
output_description = getValueByKey('description', data.hits);
output_material = getValueByKey('material', data.hits);
output_price = getValueByKey('price', data.hits);
document.getElementById("search-results-brand").innerHTML = output_brand;
document.getElementById("search-results-id").innerHTML = output_id;
document.getElementById("search-results-color").innerHTML = output_color;
document.getElementById("search-results-description").innerHTML = output_description;
document.getElementById("search-results-material").innerHTML = output_material;
document.getElementById("search-results-price").innerHTML = output_price;
}, function(status) {
alert('Something went wrong.');
});
});
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/common.css">
<script type="application/ecmascript" src="js/common.js"></script>
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1>Test</h1>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="col-sm-12">
<input placeholder="search bags" id="search">
</div>
</div>
</div>
<div class="container">
<div class="row item-row" id="item-wrapper"></div>
</div>
</body>
</html>
You are return data[i][key]; . Do not return untill loop finishes.
function getValueByKey(key, data) {
var i, len = data.length;
var result =[];
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
result.push(data[i][key]);
}
}
return result;
}
Edit for your question in the comment
As per my understanding your question, you can try something like this.I did not test this code. Let me know if there are any errors.
var items;
for(var i=0; i<output_id.length; i++){
items +='<div class="col-sm-4">' +
'<img src="path/to-image.jpg">' +
'</div>' +
'<div class="col-sm-8">' +
'<ul>' +
'<li><strong>Bag Brand:</strong>'+output_brand[i]+'<span id="search-results-brand"></span></li>' +
'<li><strong>Bag ID:</strong>'+output_id[i]+' <span id="search-results-id"></span></li>' +
'<li><strong>Bag Color:</strong>'+output_color[i]+' <span id="search-results-color"></span></li>' +
'<li><strong>Bag Description:</strong>'+output_description[i]+' <span id="search-results-description"></span></li>' +
'<li><strong>Bag Material:</strong>'+output_material[i]+' <span id="search-results-material"></span></li>' +
'<li><strong>Bag Price:</strong> '+output_price[i]+'$<span id="search-results-price"></span></li>' +
'</ul>' +
'</div>';
}
document.getElementById('item-wrapper').innerHTML =items;

how to select all checkbox in javascript?

Script:-
<script type="text/javascript">
$(document).ready(function () {
var x = document.getElementById("currentPage").value;
if (x == null || x == "")
GetPage(parseInt(1));
else
GetPage(parseInt(x));
$('#pager').on('click', 'input', function () {
GetPage(parseInt(this.id));
document.getElementById("currentPage").value = parseInt(this.id);
});
});
function GetPage(pageIndex) {
//debugger;
$.ajax({
cache: false,
//url: "/EmailScheduler/",
url: '#(Url.RouteUrl("EmailScheduler"))',
type: "POST",
data: { "selectValue": pageIndex },
traditional: true,
dataType: "json",
success: function (data) {
//debugger;
$('#GridRows').empty();
$('#pager').empty();
var trHTML = '';
var htmlPager = '';
$.each(data.Customers, function (i, item) {
trHTML += ' <tbody class="table-hover"><tr>'
+ '<td class="text-left"><div class="checkbox" style="padding-left:50px;"><label><input type="checkbox" id=" ' + item.CustomerID + '" class="checkBoxClass"/></label></div></td>'
+ '<td class="text-left" id="tblFirstName"> ' + item.FirstName + '</td>'
+ '<td class="text-left" id="tblLastName"> ' + item.LastName + '</td>'
+ '<td class="text-left" id="tblEmailID"> ' + item.EmailID + '</td>'
+ '<td class="text-left" id="tblCustomerType"> ' + item.CustomerType + '</td>'
+ '<td class="text-left" id="tblCustomerDesignation" style="padding-left:40px;padding-right:30px;"> ' + item.CustomerDesignation + '</td></tr></tbody>'
});
$('#GridRows').append(trHTML);
if (data.Pager.EndPage > 1) {
htmlPager += '<ul class="pagination">'
if (data.Pager.CurrentPage > 1) {
htmlPager += '<li><input class="myButton" style="width:25px;height:25px;" type="button" id="1" style="font-weight:bold;" value="<<" /></li><li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage - 1) + '"value="<"></li>'
}
for (var page = data.Pager.StartPage; page <= data.Pager.EndPage; page++) {
htmlPager += '<li class="' + (page == data.Pager.CurrentPage ? "active" : "") + '"><input type="button" class="myButton" id="' + page + '" value="' + page + '"/></li>'
}
if (data.Pager.CurrentPage < data.Pager.TotalPages) {
htmlPager += '<li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage + 1) + '" value=">"/></li><li><input type="button" class="myButton" id="' + (data.Pager.TotalPages) + '" value=">>"/></li>'
}
htmlPager += '</ul>'
}
$('#pager').append(htmlPager);
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
}
$(document).on('click', '#GridRows .checkBoxClass',
function () {
var cid = $(this).attr('id');
debugger;
var CustomerIDArray = [];
var hidCID = document.getElementById("hfCustomerID");
if (hidCID != null && hidCID != 'undefined') {
var CustID = hidCID.value;
CustomerIDArray = CustID.split("|");
var currentCheckboxValue = cid;
var index = CustomerIDArray.indexOf(currentCheckboxValue);
//debugger;
if (index >= 0) {
var a = CustomerIDArray.splice(index, 1);
//alert("a" + a);
}
else {
CustomerIDArray.push(currentCheckboxValue);
//alert('pushed value:' + CustomerIDArray);
}
hidCID.value = CustomerIDArray.join("|");
//alert('Final' + hidCID.value);
}
else {
alert('undefined');
}
});
$(document).on('click', '#cbSelectAll', function () {
if (this.checked) {
//$(':checkbox').each(function () {
$("#GridRows .checkBoxClass").each(function () {
//debugger;
this.checked = true;
var selectall = document.getElementsByClassName(".checkBoxClass");
var custid = $(this).attr('id');
console.log('custid' + custid);
var hidSelectAll = document.getElementById("hfSelectAll");
var hidCustomer = document.getElementById("hfCustomerID");
hidCustomer = '';
var str = 'Select All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$("#GridRows .checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var cid = $(this).attr('id');
console.log('cid' + cid);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'Select All + unselected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
else {
$(':checkbox').each(function () {
this.checked = false;
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'UnSelect All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$(".checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'unSelect All + selected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
});
</script>
HTML:-
<div class="table-responsive" style="padding-left:20%;">
<table id="tCustomer" class="table-fill" style="float:left;">
<thead>
<tr>
<th class="text-left">
Select All
<div class="checkbox">
<input style="margin-left:15px;" type="checkbox" id="cbSelectAll" class="checkBoxClass"/>
</div>
</th>
<th class="text-left" style="padding-left:27px;">
First Name
</th>
<th class="text-left" style="padding-left:32px;">
Last Name
</th>
<th class="text-left" style="padding-left:40px;padding-right: 60px;">
Email-ID
</th>
<th class="text-left" style="padding-left:30px;padding-right: 40px;">
Customer Type
</th>
<th class="text-left" style="padding-left:15px;">
Customer Designation
</th>
</tr>
</thead>
</table>
<div id="GridRows" style="width:65%;">
</div>
</div>
<div id="pager"></div>
<input type="hidden" id="currentPage">
<input type="hidden" id="hfCustomerID"/>
<input type="hidden" id="hfSelectAll" />
In this When click on Select all checkbox then all values from should
be checked but when select all checked box is checked then only value
from current pagination got selected.
table contain is generated from ajax to avoid loss of checked value
while page load.
In your case
$(".checkBoxClass").prop('checked', true);
should work too.
The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements.
Read More: Here
In jquery you can achieve this by:
$('input[type="checkbox"]').prop('checked', true);
It will make all checkbox checked.

Categories