Can't add more than 10 rows to my datatable - javascript

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>

Related

Getting ArgumentNullException: Value cannot be null when using DateTimePicker

Before I use it DateTimePicker everything was working fine, but after adding some javascript code for datetimepicker I am getting ArgumentNullException for
#Html.DropDownListFor(x => x.LeagueId, new SelectList(ViewBag.Leagues, "Id", "LeagueType"), "", new { #class = "form-control", id="liga" }), first player is added successfully but when I want to one more, my application crashes.
Input for date
<div class="form-group">
<label asp-for="Player.Birth" class="control-label">#DbResHtml.T("Датум на раѓање","Resources")</label>
<input asp-for="Player.Birth" type="text" class="form-control datepicker" required id="birth" />
<span asp-validation-for="Player.Birth" class="text-danger"></span>
</div>
After adding this lines of code my app crashes
<script>
$(document).ready(function() {
$.datetimepicker.setDateFormatter('moment');
$(".datepicker").datetimepicker({
timepicker: false,
format: 'DD/MM/YYYY',
});
})
</script>
Other scripts for Create page
<script>
$(document).ready(function() {
$('#select2-3').find('option').not(':selected').remove();
var count = 0;
$('#liga').on('change', function() {
var selectedText = $(this).find('option:selected').text();
var selectedVal = $(this).val();
var leagueAjax = $.ajax({
type: "POST",
url: "#Url.Action("GetClubsForLeague", "Player")",
data: {
id: selectedVal
},
success: function(data) {
if (count == 0) {
var s = '<option value="-1"></option>';
}
count++;
$('#select2-3').find('option').not(':selected').remove();
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
}
$('#select2-3').append(s);
var mycode = {};
$("select[id='select2-3'] > option").each(function() {
if (mycode[this.text]) {
$(this).remove();
} else {
mycode[this.text] = this.value;
}
});
},
error: function(req, status, error) {
ajaxErrorHandlingAlert("error", req.status);
}
})
})
})
</script>
<script>
$(document).ready(function() {
$('#select2-3').change(function() {
var cc = $('#select2-3').val();
var ids = [];
for (let i = 0; i < cc.length; i++) {
ids.push(cc[i]);
}
$.ajax({
type: "POST",
url: "#Url.Action("GetClubsById","Player")",
data: { "ids": ids },
success: function(data) {
console.log(data);
$('#clubsTBody tr').remove();
var counter = 1;
for (let i = 0; i < data.length; i++) {
$("#clubsTBody").append("<tr><td>" + counter + "</td>"
+ "<td>" + data[i].name + "</td>"
+ "<td>" + data[i].league.leagueType + "</td>"
+ "<td>" + '<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn" title=#DbResHtml.T("Delete", "Resources")></button>' + "</td>"
+ "</tr >");
counter++;
}
},
error: function(req, status, error) {
console.log(msg);
}
});
})
$('#clubs').on('click', '.deleteBtn', function() {
$(this).parents('tr').remove();
var value = $(this).closest('tr').children('td:eq(1)').text();
$(`#select2-3 option:selected:contains("${value}")`).prop("selected", false).parent().trigger("change");
});
})
</script>
I am debugging for 3 days, but still nothing.

how to replace a single choice with a select my cart

For now I have a cart in javascript that works
But when I click the add to cart button
there is only one product added
I would like to replace this with a select so that the user can choose the number of articles to add
I tried to modify the code but when I select a quantity and I click on add to cart
It's always two that adds up
var MonPanier = (function() {
panier = [];
function Item(nom, prix, quantite) {
this.nom = nom;
this.prix = prix;
this.quantite = quantite;
}
function savepanier() {
console.log("saving",panier)
// sessionStorage.setItem('MonPanier', JSON.stringify(panier));
}
function loadpanier() {
// panier = JSON.parse(sessionStorage.getItem('MonPanier'));
panier = []
}
// if (sessionStorage.getItem("MonPanier") != null) {
// loadpanier();
// }
//variable objet
var obj = {};
obj.ajouter_produit_dans_panier = function(nom, prix, quantite) {
for (var item in panier) {
if (panier[item].nom === nom) {
//panier[item].quantite ++ ; ancien code
panier[item].quantite;
savepanier();
return;
}
}
var item = new Item(nom, prix, quantite);
panier.push(item);
savepanier();
}
obj.setquantiteForItem = function(nom, quantite) {
for (var i in panier) {
if (panier[i].nom === nom) {
panier[i].quantite = quantite;
break;
}
}
};
obj.enlever_produit_de_panier = function(nom) {
for (var item in panier) {
if (panier[item].nom === nom) {
panier[item].quantite--;
if (panier[item].quantite === 0) {
panier.splice(item, 1);
}
break;
}
}
savepanier();
}
obj.enlever_produit_de_panier_tous = function(nom) {
for (var item in panier) {
if (panier[item].nom === nom) {
panier.splice(item, 1);
break;
}
}
savepanier();
}
obj.clearpanier = function() {
panier = [];
savepanier();
}
obj.totalquantite = function() {
var totalquantite = 0;
for (var item in panier) {
totalquantite += panier[item].quantite;
}
return totalquantite;
}
obj.totalpanier = function() {
var totalpanier = 0;
for (var item in panier) {
totalpanier += panier[item].prix * panier[item].quantite;
}
return Number(totalpanier.toFixed(2));
}
obj.listpanier = function() {
var panierCopy = [];
for (i in panier) {
item = panier[i];
itemCopy = {};
for (p in item) {
itemCopy[p] = item[p];
}
itemCopy.total = Number(item.prix * item.quantite).toFixed(2);
panierCopy.push(itemCopy)
}
return panierCopy;
}
return obj;
})();
$('.ajouter-panier').click(function(event) {
event.preventDefault();
var nom_option = "";
var prix_option = 0;
var nom = $(this).data('nom');
var prix = Number($(this).data('prix')) + prix_option;
var quantite = $(this).data('select');
MonPanier.ajouter_produit_dans_panier(nom, prix, quantite);
//MonPanier.ajouter_produit_dans_panier(nom, prix,1); ancien code
afficherpanier();
});
$('.clear-panier').click(function() {
MonPanier.clearpanier();
afficherpanier();
});
$('.choix_livraison').click(function() {
const cases = document.querySelectorAll('input[name="choix_livraison"]');
for (const x of cases) {
if (x.checked) {
afficherpanier();
}}
});
function afficherpanier() {
var panierArray = MonPanier.listpanier();
var output = "";
var countart=0;
var countart2=0;
var count=0;
for(var i in panierArray) {
output += "<div class='row' style='border-style: ridge; border-width: 1px; border-color: #8ebf42; background-color: #d9d9d9;margin-bottom:5px;'>"
+ "<div class='col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'><button class='btn btn-danger effacer-item' data-nom='" + panierArray[i].nom + "'>X</button></div>"
+ "<div class='col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'>" + panierArray[i].nom + "</div>"
+ "<div class='col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'>" + panierArray[i].prix.toFixed(0) + " euro</div>"
+ "<div class='form-inline col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'><div class='input-group'><button class='btn btn-primary moins-item' data-nom='" + panierArray[i].nom + "'>-</button>"
+ "<input type='number' min='1' class='form-control item-quantite' style='width:55px !important' data-nom='" + panierArray[i].nom + "' value='" + panierArray[i].quantite + "'>"
+ "<button class='btn btn-primary plus-item' data-nom='" + panierArray[i].nom + "'>+</button></div></div>"
//+ ' = '
+ "<div class='col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'>" + panierArray[i].total + " euros</div>"
+ "</div>";
count++;
countart += panierArray[i].quantite; // somme des unités d'articles
countart2 = countart
}
$('.show-panier').html(output);
if (Livraison == 3)
{
// % du prix total total correspondant au prix de la livraison
const cases = document.querySelectorAll('input[name="choix_livraison"]');
//const cases = document.querySelectorAll('input[name="ajout");
for (const x of cases) {
if (x.checked) {
let nom_choix_livraison = x.dataset.nom;
let prix_choix_livraison = x.value;
//console.log(panierArray[i] );
let prix_et_livraison = (( (MonPanier.totalpanier()*Poucentage_Livraison))) + Number(prix_choix_livraison) + Number(Forfait_Livraison ) ;
document.getElementById('amount').value = prix_et_livraison ;
$('.total-panier').html(prix_et_livraison.toFixed(2));
document.getElementById('livraison-detail').innerHTML ="<div class='col' style='text-align:right;background-color: #78b8df;visibility:hidden;'> (" + nom_choix_livraison + ")" + prix_choix_livraison + " euro(s)</div>";
document.getElementById('remise').innerHTML =MonPanier.totalpanier()*Poucentage_Livraison_opposse ;
document.getElementById('nouveau_prix').innerHTML =(MonPanier.totalpanier()- (MonPanier.totalpanier()*Poucentage_Livraison_opposse));
document.getElementById('frais-fixe').innerHTML =Forfait_Livraison ;
document.getElementById("prix_depart").innerHTML = MonPanier.totalpanier();
document.getElementById("countart_bas").innerHTML = countart;
document.getElementById("countart_haut").innerHTML = countart;
break;
}
}
}
$('.total-panier-modal').html(MonPanier.totalpanier());
$('.total-quantite').html(MonPanier.totalquantite());
if ((Qte_Minimum == 1) && (Number.isInteger(MonPanier.totalquantite() / Qte_Minimum_Valeur) == false) && (MonPanier.totalquantite() != 0))
{
document.getElementById('qte_minimum_report').innerHTML = txt_qte_minimum_bad;
}
else if ((Qte_Minimum == 1) && (Number.isInteger(MonPanier.totalquantite() / Qte_Minimum_Valeur) == true) && (MonPanier.totalquantite() != 0))
{
document.getElementById('qte_minimum_report').innerHTML = txt_qte_minimum_ok;
}
else if (Qte_Minimum == 1)
{
document.getElementById('qte_minimum_report').innerHTML = txt_qte_minimum_defaut;
}
else if (Qte_Minimum == 0)
{
document.getElementById('qte_minimum_report').innerHTML = "";
}
}
$('.show-panier').on("click", ".effacer-item", function(event) {
var nom = $(this).data('nom')
MonPanier.enlever_produit_de_panier_tous(nom);
afficherpanier();
})
$('.show-panier').on("click", ".moins-item", function(event) {
var nom = $(this).data('nom')
MonPanier.enlever_produit_de_panier(nom);
afficherpanier();
})
$('.show-panier').on("click", ".plus-item", function(event) {
var nom = $(this).data('nom')
MonPanier.ajouter_produit_dans_panier(nom);
afficherpanier();
})
$('.show-panier').on("change", ".item-quantite", function(event) {
var nom = $(this).data('nom');
var quantite = Number($(this).val());
MonPanier.setquantiteForItem(nom, quantite);
afficherpanier();
});
afficherpanier();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row mt-3">
<div class="col-md-4">
<p>Produit 02 (15.00 €)</p>
</div>
<div class="col-md-2">
<select class="form-control" id="02">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<div class="col-md-6 text-end">
<a style="cursor:pointer;" data-nom="Produit 02" data-prix="15.00" data-select="02" class="btn btn-primary ajouter-panier">Add to Cart</a>
</div>
</div>

Why am i getting NaN while multipling select data-attrib with input value

I am having issues to get total for my <span class="cubics"></span>. I am getting NaN as my result when i input value to my <input class="item_unit" value=""> and multiply with select data-cubics
Here is my code
PHP To populate select options
foreach($result as $row)
{
$output .= '<option value="'.$row["unit_name"].'" data-cubics="'.$row["unit_price"].'" >'.$row["unit_name"].'</option>';
}
TABLE to display results
<table class="table table-bordered" id="item_table">
<tr>
<th>Enter Quantity</th>
<th>Select Unit</th>
<th>Total</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<tr class="bg">
<td width="33%">TOTAL</td>
<td width="33%"><span id="totalquantity"></span>
</td>
<td width="33%">TOTAL</td>
<td width="33%"><span class="totalcubics"></span>
</td>
</tr>
JAVASCRIPT To handle functionality
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><select name="item_unit[]" class="item_unit form-control"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><input class="qty form-control" type="text" value="0"/></td>';
html += '<td width="33%"><span class="cubics"></span>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
$summands = $form.find('input.qty'); //*************** add this line
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.qty').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Quantity at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Select Unit at "+count+" Row</p>";
return false;
}
count = count + 1;
});
});
});
function total() {
var total1 = 0;
$('span.cubics').each(function () {
var n = parseFloat($(this).text());
total1 += isNaN(n) ? 0 : n;
});
$('.totalcubics').text(total1.toFixed(2));
}
$(document).on('keyup' , 'input.qty' , function () {
var val = parseFloat($(this).val());
val = (val ? val * $(this).data('cubics') : '');
$(this).closest('td').next().find('span.cubics').text(val);
total();
});
var $form = $('#insert_form'),
$summands = $form.find('input.qty'),
$sumDisplay = $('span#totalquantity');
$form.keyup(function () {
var sum = 0;
$summands.each(function () {
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.text(sum);
});
$('input').on({
focus: function () {
if (this.value == '0') this.value = '';
},
blur: function () {
if (this.value === '') this.value = '0';
}
});
$(function() {
$('.qty').change(function() {
var p = $(this).parent().parent()
var m = p.find('input.qty')
var mul = parseInt($(m[0]).val()).toFixed(2)
var res = p.find('.qty')
res.html(mul);
var total = 0;
$('.qty').each(function() {
total += parseInt($(this).text());
})
parseInt(total).toFixed(2);
$('.cubics').html(parseInt(total).toFixed(2));
});
});
$('.item_unit').change(calcVal);
function calcVal() {
$(".cubics").html($(this).children(':checked').data('cubics') * $('input.qty').text().trim())
}
// call on document load
calcVal();
</script>
Sorry couldn't narrow it down to the culprit lines. html += '<td width="33%"><span class="cubics"></span>'; is getting NaN as result
SELECT OPTIONS generated by PHP
<td><select name="item_unit[]" class="item_unit form-control">
<option value="">Select Unit</option>
<option value="Bags" data-cubics="40000" >Bags</option>
<option value="Bottles" data-cubics="20000" >Bottles</option>
<option value="Box" data-cubics="30000" >Box</option>
<option value="Dozens" data-cubics="90000" >Dozens</option>
</select></td>

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.

Weird JS Behavior With Bootstrap Sliders

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>

Categories