Ajax form only working after first refresh - javascript

I've a form that is sent via AJAX, but AJAX only works after first refresh (F5).
The first time I open the html I send the form and I've to do a page refresh otherwise data it is not submited. After this first refresh, AJAX is working perfectly and always reflect new data on success.
The data that I append after submits the form: ( $("#fldIdLetraN") and $("#fldLetraN") ), I've to call it via $_REQUEST on php file, I think this can do some interference the first time form is sent because data isn't really insert in JSON file cause $_REQUEST is not setting correctly.
$("body").on("submit", "#frmPersonas", function(e) {
$("#fldIdLetraN").val(jQuery.inArray(RemoveAccents($("#fldNombre").val().substr(0, 1)), $aLetras));
$("#fldLetraN").val(RemoveAccents($("#fldNombre").val().substr(0, 1)));
var fd = new FormData($("#frmPersonas")[0]);
$.ajax({type: 'POST',
url: "procjson.php",
data: fd,
processData: false,
contentType: false,
success: function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
$("#form").css("display", "none");
$("#formbg").css("display", "none");
}
});
e.preventDefault();
});
The entire code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Agenda</title>
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="formbg">
<div id="form"></div>
</div>
<div id="divAgenda">
<div id="divLetras"></div>
<div id="divEditar">
<div><img src="img/ops/add.png" alt="" /></div>
<div><img src="img/ops/update.png" alt="" /></div>
<div><img src="img/ops/delete.png" alt="" /></div>
</div>
<div id="divBusqueda">
<div><img src="img/ops/hojear.png" alt="" /></div>
<div><img src="img/ops/search.png" alt="" /></div>
</div>
<div id="divPersonas"></div>
<div id="divPaginas"></div>
<div id="divDesplazar">
<div><img src="img/move/first.png" alt="" /></div>
<div><img src="img/move/previous.png" alt="" /></div>
<div><img src="img/move/next.png" alt="" /></div>
<div><img src="img/move/last.png" alt="" /></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$aLetras = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "ñ", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z");
for (var i = 0; i < $aLetras.length; i++) {
$("#divLetras").append("<a href='#" + $aLetras[i] + "' id='" + $aLetras[i] + "-" + i + "'\n\
class='tab-letra'>" + $aLetras[i].toUpperCase() + "</a>");
}
$PagActual = 0;
CargarPagina("a", 0, 0);
});
function CargarPagina(letra, id_letra, pag_actual, hojear) {
$.getJSON("datos.json", function(datos) {
$("#divPersonas").empty();
$("#divPersonas").append("<ul id='col1'></ul><ul id='col2'></ul>");
var res_pagina = 6;
for (var i = pag_actual * res_pagina; i < pag_actual * res_pagina + res_pagina; i++) {
if (datos.personas[id_letra][letra][i] === undefined) {
break;
}
var html = "<div id='per" + datos.personas[id_letra][letra][i].id + "'>";
html += "<div><img src='img/photo/" + datos.personas[id_letra][letra][i].foto + "' /></div>";
html += "<div><span>Nombre: </span><span id='nom" + datos.personas[id_letra][letra][i].id + "'>";
html += datos.personas[id_letra][letra][i].nombre + "</span><br />";
html += "<span>Apellidos: </span><span id='ape" + datos.personas[id_letra][letra][i].id + "'>";
html += datos.personas[id_letra][letra][i].apellidos + "</span><br />";
html += "<span>Edad: </span><span id='eda" + datos.personas[id_letra][letra][i].id + "'>";
html += datos.personas[id_letra][letra][i].edad + "</span><br />";
html += "<span>Teléfono: </span><span id='tel" + datos.personas[id_letra][letra][i].id + "'>";
html += datos.personas[id_letra][letra][i].telefono + "</span><br /></div></div>";
if (i >= pag_actual * res_pagina && i < pag_actual * res_pagina + res_pagina - 3) {
$("#col1").append(html);
} else {
$("#col2").append(html);
}
}
$LetraAct = letra;
$IdLetraAct = id_letra;
if (datos.personas[id_letra][letra].length % res_pagina === 0) {
$TotalPag = datos.personas[id_letra][letra].length / res_pagina - 1;
} else {
$TotalPag = Math.floor(datos.personas[id_letra][letra].length / res_pagina);
}
$("#divPaginas").empty();
for (var i = 0; i <= $TotalPag; i++) {
$("#divPaginas").append("<a href='#" + $LetraAct + ",p" + (i + 1) + "' id='pag" + i + "'>" + (i + 1) + "</a>");
}
if($TotalPag === -1) {
$("#divPersonas").html("<div id='noRes'>No se ha encontrado ningún resultado.</div>");
}
if (hojear) {
Hojear(true);
}
});
}
function GreyBox() {
$("#form").fadeIn("fast", function() {
$("#form").css("display", "block");
});
$("#formbg").fadeIn("fast", function() {
$("#form").css("display", "block");
});
}
function AbrirFormulario(crud, id_persona) {
$("#form").html("<div id='frmOp'></div>\n\
<form id='frmPersonas' name='frmPersonas'>\n\
<label for='fldNombre'>Nombre:</label>\n\
<input type='text' id='fldNombre' name='fldNombre' autocomplete='off' />\n\
<label for='fldApellidos'>Apellidos:</label>\n\
<input type='text' id='fldApellidos' name='fldApellidos' autocomplete='off' />\n\
<label for='fldEdad'>Edad:</label>\n\
<input type='text' id='fldEdad' name='fldEdad' autocomplete='off' />\n\
<label for='fldTlf'>Teléfono:</label>\n\
<input type='text' id='fldTlf' name='fldTlf' autocomplete='off' />\n\
<input type='hidden' id='fldIdLetraN' name='fldIdLetraN' />\n\
<input type='hidden' id='fldLetraN' name='fldLetraN' />\n\
<input type='hidden' id='crud' name='crud' value='" + crud + "' />\n\
<input type='submit' id='btnEnviar' value='Enviar' /></form>\n\
<div id='frmAlert'></div>");
if (crud === "C") {
$("#frmOp").html("Agregar contacto");
}
if (crud === "U") {
$("#frmOp").html("Modificar contacto");
$("#fldNombre").val($("#nom" + id_persona).html());
$("#frmPersonas").append("<input type='hidden' id='fldLetraAct' name='fldLetraAct' \n\
value='" + RemoveAccents($("#fldNombre").val().substr(0, 1)) + "' />");
$("#frmPersonas").append("<input type='hidden' id='fldIdLetraAct' name='fldIdLetraAct' \n\
value='" + jQuery.inArray(RemoveAccents($("#fldNombre").val().substr(0, 1)), $aLetras) + "' />");
$("#fldApellidos").val($("#ape" + id_persona).html());
$("#fldEdad").val($("#eda" + id_persona).html());
$("#fldTlf").val($("#tel" + id_persona).html());
$("#frmPersonas").append("<input type='hidden' id='fldIdPersona' name='fldIdPersona' value='" + id_persona + "' />");
}
}
function RemoveAccents(strAccents) {
var strAccents = strAccents.split('');
var strAccentsOut = new Array();
var strAccentsLen = strAccents.length;
var accents = 'ÁABCDÉEFGHÍIJKLMNÑÓOPQRSTÚUVWXYZ';
var accentsOut = "aabcdeefghiijklmnñoopqrstuuvwxyz";
for (var y = 0; y < strAccentsLen; y++) {
if (accents.indexOf(strAccents[y]) !== -1) {
strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
} else
strAccentsOut[y] = strAccents[y];
}
strAccentsOut = strAccentsOut.join('');
return strAccentsOut;
}
function Hojear(active) {
if (active) {
if ($TotalPag === -1) {
$TotalPag = 0;
}
if ($PagActual === $TotalPag) {
if ($IdLetraAct + 1 === $aLetras.length) {
$IdLetraAct = 0;
$LetraAct = $aLetras[$IdLetraAct];
$PagActual = 0;
} else {
$IdLetraAct++;
$LetraAct = $aLetras[$IdLetraAct];
$PagActual = 0;
}
} else {
$PagActual++;
}
$DelayHojear = setTimeout(function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual, true);
}, 1000);
} else {
clearTimeout($DelayHojear);
}
}
$("body").on("click", "#divLetras a", function() {
var letra = $(this).attr("id").substr(0, 1);
var id_letra = $(this).attr("id").substr($(this).attr("id").search(/\d/));
$PagActual = 0;
CargarPagina(letra, id_letra, $PagActual);
});
$("#divDesplazar a").click(function() {
var acc = $(this).attr("id");
if (acc === "first") {
$PagActual = 0;
}
if (acc === "prev" && $PagActual > 0) {
$PagActual--;
}
if (acc === "next" && $PagActual < $TotalPag) {
$PagActual++;
}
if (acc === "last") {
$PagActual = $TotalPag;
}
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
});
$("#divEditar a").click(function() {
var acc = $(this).attr("id");
if (acc === "update" || acc === "delete") {
if ($("[id*=per]").hasClass("selected")) {
var id_persona = $(".selected").attr("id").substr($(".selected").attr("id").search(/\d/));
if (acc === "update") {
GreyBox();
AbrirFormulario("U", id_persona);
}
if (acc === "delete") {
var crud = "D";
$.ajax({type: "POST",
url: "procjson.php",
data: {'crud': crud, 'id_persona': id_persona, 'letra_act': $LetraAct, 'id_letra': $IdLetraAct},
success: function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
}
});
}
} else {
console.log("no");
}
}
if (acc === "add") {
GreyBox();
AbrirFormulario("C", -1);
}
});
$("body").on("submit", "#frmPersonas", function(e) {
e.preventDefault();
$("#fldIdLetraN").val(jQuery.inArray(RemoveAccents($("#fldNombre").val().substr(0, 1)), $aLetras));
$("#fldLetraN").val(RemoveAccents($("#fldNombre").val().substr(0, 1)));
var fd = new FormData($("#frmPersonas")[0]);
$.ajax({type: 'POST',
url: "procjson.php",
cache: false,
data: fd,
processData: false,
contentType: false,
success: function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
$("#form").css("display", "none");
$("#formbg").css("display", "none");
}
});
return false;
});
$("body").on("click", "#divPersonas [id*=p]", function() {
$("#divPersonas [id*=per]").removeAttr("class");
var id_persona = $(this).attr("id").substr($(this).attr("id").search(/\d/));
$("#per" + id_persona).attr("class", "selected");
});
$("body").on("click", "#formbg", function() {
$("#form").css("display", "none");
$("#formbg").css("display", "none");
});
$("body").on("click", "#divPaginas a", function() {
var id_pagina = $(this).attr("id").substr($(this).attr("id").search(/\d/));
CargarPagina($LetraAct, $IdLetraAct, id_pagina);
});
$("#divBusqueda a").click(function() {
var Acc = $(this).attr("id");
if (Acc === "hojear") {
Hojear(true);
}
if (Acc === "search") {
}
});
$("body").on("mouseover", "[id*=per]", function() {
Hojear(false);
});
$("#form").click(function(e) {
e.stopPropagation();
});
$("a").click(function(e) {
return false;
e.preventDefault();
});
</script>

try disabling the cache:
$.ajax({type: 'POST',
url: "procjson.php",
cache: false
//the rest
});

Is this all of your javascript code used on this site? Because if yes, try to wrap your code like this:
$(document).ready(function() {
$("body").on("submit", "#frmPersonas", function(e) {
$("#fldIdLetraN").val(jQuery.inArray(RemoveAccents($("#fldNombre").val().substr(0, 1)), $aLetras));
$("#fldLetraN").val(RemoveAccents($("#fldNombre").val().substr(0, 1)));
var fd = new FormData($("#frmPersonas")[0]);
$.ajax({type: 'POST',
url: "procjson.php",
data: fd,
processData: false,
contentType: false,
success: function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
$("#form").css("display", "none");
$("#formbg").css("display", "none");
}
});
e.preventDefault();
});
});
Then jquery will wait before the DOM is ready before attaching the eventhandler etc., this could be an explanation why it's working on refresh (because of your browser cache dom could be ready faster then on your first load).

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.

ajax loading do not working with async:false

I'm trying to make loading appear before making a request using ajax and even then the screen is only locked.
JS:
function showEstoque(productId) {
if (url !== '' && url != '-1') {
if (active) {
hideEstoques(active);
}
var target = document.getElementById("productInfo" + productId);
target.innerHTML = generateRows(productId);
target.style.display = "block";
active = productId;
}
}
function hideEstoques(productId) {
document.getElementById("productInfo" + productId).style.display = "none";
active = null;
}
function generateRows(productId) {
var rows = '';
rows += generateRowsEstoque(productId);
rows += generateRowsReserva(productId);
return rows;
}
function generateRowsEstoque(productId) {
var textContent = searchE(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse[0].nothing : null;
if (!data)
return '<span>Nothing</span><table><tr><td>Nothing</td></tr></table>';
var rows = '<span>Nothing</span> <table><thead> <tr> <th>Nothing</th></tr> </thead> <tbody>';
for(var n=0; n < data.length; n++) {
rows += '<tr>' +
'<td>' + data[n].nothing + '</td>' +
'</tr>';
}
rows += '</tbody> </table>';
return rows;
}
function searchE(productId) {
var view_data = "[]";
jQuery.ajax({
url: url + "product/" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function generateRowsReserva(productId) {
var textContent = searchEReserva(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse : null;
if (!data)
return '<table class="info"><tr><td class="none">Nothing</td></tr></table>';
var foo = data.filter(function(p) { return p.idType === 'foo' });
var bar = data.filter(function(p) { return p.idType === 'bar' });
var fooQtd = foo.length ? foo[0].nothing : 0;
var barQtd = bar.length ? bar[0].nothing : 0;
var rows = '<br/><table class="info"><thead> <tr class="labels"> <th>Nothing</th> </tr> </thead> <tbody>';
rows += '<tr>' +
'<td>' + fooQtd + '</td>' +
'<td>' + barQtd + '</td>' +
'</tr>';
rows += '</tbody> </table>';
return rows;
}
function searchEReserva(productId) {
var view_data = "[]";
$j.ajax({
url: "url" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function startLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "";
}
}
function stopLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "none";
}
}
HTML:
<td
onclick="showEstoque(1);">
<div id="estoque_1" class="estoqueCor st-color_"/>">1</div>
<img id="imgEstoqueProduto"
style="vertical-align: middle; display: none;"
src="<c:url value="/images/ajaxLoader.gif"/>">
<div class="container-product-info">
<div onmouseout="hideEstoques(1);"
class="productInfo"
id="productInfo1"></div>
</div>
</td>
I tried to use the beforeSend, call before the ajax method starts, ajaxStart and even then it doesn't work and the screen just hangs. Could you help me please?
I called startLoading before everything and it still doesn't work
I removed async: false but, I need to wait for the data to be returned from the API

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>

Getting JSON Object then adding parts to HTML

I have been trying to get a script to work for my Github site and I am processing a JSON file to get an array to HTML in a ordered list.
My code I have been using is:
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
$.each(mods, function(i) {
var tempUrl = "";
var tempApproved = "";
if (data.mods[i].Repo[0] == 0) {
tempUrl = data.mods[i].Repo[1];
} else if (data.mods[i].Repo[0] == 1) {
tempUrl = "http://community.playstarbound.com/resources/" + data.mods[i].Repo[1] + "/";
} else {
tempUrl = data.mods[i].Repo[1];
}
if (data.mods[i].Approved == true) {
tempApproved = "checked";
} else {
tempApproved = "";
}
$("#modsList").append("<li><a href='" + tempUrl + "'>" + data.mods[i].Title + "</a> - by " + data.mods[i].Author + "<ul><li>\t- <input type='checkbox' " + tempApproved + "/> Approved</li></ul></li>");
});
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>
So what have I been doing wrong because nothing is working...
This should work:
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
$.each(data.mods, function(i, m) {
var tempUrl = "";
var tempApproved = "";
if (m.Repo[0] == 0) {
tempUrl = m.Repo[1];
} else if (m.Repo[0] == 1) {
tempUrl = "http://community.playstarbound.com/resources/" + m.Repo[1] + "/";
} else {
tempUrl = m.Repo[1];
}
if (m.Approved == true) {
tempApproved = "checked";
} else {
tempApproved = "";
}
$("#modsList").append("<li><a href='" + tempUrl + "'>" + m.Title + "</a> - by " + m.Author + "<ul style='list-style-type:none'><li>\t - <input type='checkbox' " + tempApproved + " disabled/> Approved</li></ul></li>");
});
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>
Instead of $.each(mods, function(i) { it should be $.each(data.mods, function(i, m) {. and the mods[i]. should be m..
Also there was a formatting error in the JSON file but now it is fixed. It was causing the errors to not display.

Categories