how to take input text from alert box - javascript

I have a form in which there are input fields for mobile number ,name and email.I have two buttons add and group.Add button add new records of the selected records.Group button is used to create a group of selected fields on the records.So when you click on group button it will ask whether to create a group or not.If yes then it will create a group named as 0 or 1.But I want to give some name(user should type the name to be given) to the group.Please tell me how to do.This is the fiddle and this is the screenshot
This is the jquery
var val = 0;
var groupTrCount = 0;
$(document).ready(function () {
var obj={};
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" checked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
});
$(document).on('click', '#btn2',function () {
var creat_group = confirm("Do you want to creat a group??");
if (creat_group) {
console.log(obj);
$("#groupsTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >" + groupTrCount + "</td>");
var userColumn = "<ul>";
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
$(this).find('td').each(function() {
if(count == 1){
userColumn+= "<li>" + $(this).html() + "</li>" ;
}
count++;
});
});
userColumn+="<ul>";
$tr.append("<td >" +userColumn+ "</td>");
groupTrCount++;
}
});
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
alert(key);
obj[key]=null;
}
});
});

If you want to add a named group use prompt instead of confirm. This will open a popup where the user can enter a group name. Fiddle
$(document).on('click', '#btn2',function () {
var creat_group = prompt("Name your group??");
if (creat_group) {
console.log(obj);
$("#groupsTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >" + creat_group + "</td>");
var userColumn = "<ul>";
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
$(this).find('td').each(function() {
if(count == 1){
userColumn+= "<li>" + $(this).html() + "</li>" ;
}
count++;
});
});
userColumn+="<ul>";
$tr.append("<td >" +userColumn+ "</td>");
groupTrCount++;
}
});

Update Fiddle :
http://jsfiddle.net/4GP9c/175/
var val = 0;
var groupTrCount = 0;
$(document).ready(function () {
var obj={};
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" checked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
});
$(document).on('click', '#btn2',function () {
var creat_group = confirm("Do you want to creat a group??");
if (creat_group) {
console.log(obj);
$tr.append("<td >" + groupTrCount + "</td>");
$("#groupsTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >Group:" + groupTrCount + "</td>"); // or you can use whatever name you want in place of "Group:"
var userColumn = "<ul>";
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
$(this).find('td').each(function() {
if(count == 1){
userColumn+= "<li>" + $(this).html() + "</li>" ;
}
count++;
});
});;
userColumn+="<ul>";
$tr.append("<td >" +userColumn+ "</td>");
groupTrCount++;
}
});
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
alert(key);
obj[key]=null;
}
});
});

You are adding groupTrCount only as the column text so you are getting the 0, 1... as indexes. You can try something like this
$tr.append("<td >Group: " + groupTrCount + "</td>");
instead of
$tr.append("<td >" + groupTrCount + "</td>");
$("#groupsTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >Group:" + groupTrCount + "</td>"); // or you can use whatever name you want in place of "Group:"
var userColumn = "<ul>";
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
$(this).find('td').each(function() {
if(count == 1){
userColumn+= "<li>" + $(this).html() + "</li>" ;
}
count++;
});
});
UPDATE
For using the custom popup either you can made it by having a separate div on your page. Make it like an overlay with the help of CSS. Or you can easily do thi with JQUERY UI DIALOGUE.

Related

I need a way to keep selected combobox values after page refresh

I have a number of comboboxes they all look like this:
<select name="cb1" size="1" id="kuz1" style="position:absolute;left:19px;top:96px;width:144px;height:69px;z-index:2;">
<option>Пусто</option>
</select>
then i obtain options for them from txt file using a simple js script.
I need a way to store selected information and keep it even if page is refreshed. I tried to use localstorage and cookie options, but they didn't work for some reason.
i tried to set variables like this var kuz1var=document.getElementById('kuz1').value;
but console always returns as "undefined"
I need somebody's advice to resolve this issue
Here is how i managed to obtain values for comboboxes
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$.get("мм.txt", function (data) {
var lines = data.split('\n').map(function(line){
return line.trim();
});
var select = $("select[name=cb1]")
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function(line){
if(line.endsWith(" -")){
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
select.append("<optgroup id='" + currentGroup + "' label='" + currentGroup + "'>")
} else if(line === ""){
select.append("</optgroup>");
} else {
select.append("<option type='checkbox' id='"
+ (currentGroup + optionCounter) + "' name='"
+ (currentGroup + optionCounter) + "' value='"
+ line + "'>" + line + "</option>");
}
});
console.log(lines);
});
</script>
For some reason the right answer was deleted, so here's the answer
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$.get("мм.txt", function (data) {
var lines = data.split('\n').map(function(line){
return line.trim();
});
var select = $("select[name=cb1]")
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function(line){
if(line.endsWith(" -")){
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
select.append("<optgroup id='" + currentGroup + "' label='" + currentGroup + "'>")
} else if(line === ""){
select.append("</optgroup>");
} else {
select.append("<option type='checkbox' id='"
+ (currentGroup + optionCounter) + "' name='"
+ (currentGroup + optionCounter) + "' value='"
+ line + "'>" + line + "</option>");
}
});
// Get the selected value from local storage
var cb1val = localStorage.getItem("cb1val");
if (cb1val) {
select.val(cb1val);
}
select.on("change", function () {
// Save the selected value to local storage
localStorage.setItem("cb1val", select.val());
});
console.log(lines);
});
</script>

JavaScript TypeError only in IE 11

When loading a js e-form in IE getting an error 'loadForm: if GroupDocList>0: TypeError: Unable to get property 'length; of undefined or null reference
This only occurs in IE not Chrome or Edge.
This form was coded by someone else and I don't have much experience with JS
Update * Through debugging I was able to find that it is the CompList object that is undefined and causing this error. Wondering why this is being undefined at this point within IE but working within Chrome and Edge or at least not throwing the error.
for (var i = 0; i < CompList.length; i++) {
function CreatePopulateDataSet() {
//*************************************************************************
//Company/Division/SubCat/Plan dataset populate - BEGIN********************
//*************************************************************************
var g_CompanyList = {};
var g_DivisionList = {};
var g_SubCatList = {};
try {
if ($("#selCompanyList").find("option").length > 0) {
try {
$("#selCompanyList option").each(function () {
var Comp = $(this).text().split("|")[0];
var Div = $(this).text().split("|")[1];
var SubCat = $(this).text().split("|")[2];
var Plant = $(this).text().split("|")[3];
var CompList = g_CompanyList[Comp];
var DivList = g_DivisionList[Comp + Div];
var SubList = g_SubCatList[Comp + Div + SubCat];
try {
if (hasCompanyAccess(Comp)) {
if (!CompList) { CompList = new Array(); }
if ($.inArray(Div, CompList) == -1) {
CompList.push(Div);
g_CompanyList[Comp] = CompList;
}
if (!DivList) { DivList = new Array(); }
if (SubCat != null) {
if ($.inArray(SubCat, DivList) == -1) {
DivList.push(SubCat);
g_DivisionList[Comp + Div] = DivList;
}
}
if (!SubList) { SubList = new Array(); }
if (Plant != null) {
if ($.inArray(Plant, SubList) == -1) {
SubList.push(Plant);
g_SubCatList[Comp + Div + SubCat] = SubList;
}
}
}
}
catch (err) {
alert("Unable build global lists used to populate drop downs. " + err);
}
});
}
catch (err) {
alert(err);
}
$("#selPARCompany").html("<option value=''>Please Select...</option>");
for (var Comp in g_CompanyList) {
$("#selPARCompany").append("<option value='" + Comp + "'>" + Comp + "</option>");
}
$("#selPARCompany").addClass("fullwidth");
//Cascade Reload - BEGIN
//Re-loads/populates the cascading data set if the form has been submitted.
if ($("#OBPropertyItemNum").val()) {
//re-sets the Company drop down box on load of a submitted form.
var tempComp = $("#txtPARCompany").val();
$("#selPARCompany option").each(function () {
if ($(this).text().toUpperCase() == tempComp.toUpperCase()) {
$(this).attr("selected", "selected");
}
});
//Calls the CompanyTabOverride method to set access to the corrct tabs based on the saved value.
CompanyTabOverride(tempComp);
var CompList = g_CompanyList[$("#selPARCompany option:selected").text().toUpperCase()];
var tempDiv = $("#txtPARDivision").val();
//re-load and populate the Division drop down box
for (var i = 0; i < CompList.length; i++) {
if (i == 0)
$("#selPARDivision").html("<option value=''>Please Select...</option>");
if (CompList[i].toUpperCase() == tempDiv.toUpperCase()) {
$("#selPARDivision").append("<option selected=selected label='" + CompList[i] + "' value='" + CompList[i] + "'>" + tempComp + CompList[i] + "</option>");
} else {
$("#selPARDivision").append("<option label='" + CompList[i] + "' value='" + CompList[i] + "'>" + tempComp + CompList[i] + "</option>");
}
}
if ($("#selPARDivision option").length > 1) {
$("#selPARDivision").closest("td").show();
$("#selPARDivision").addClass("required");
} else {
$("#selPARDivision").closest("td").hide();
$("#selPARDivision").removeClass("required");
$("#selPARDivision").removeClass("requiredInput");
}
DivisionTabOverride(tempComp, tempDiv);
//re-load and populate the Sub Category drop down box
var tempSubCat = $("#txtPARSubCat").val();
var DivList = g_DivisionList[$("#selPARDivision option:selected").text().toUpperCase()];
var Div = $("#selPARDivision option:selected").html();
if (tempSubCat != "") {
for (var i = 0; i < DivList.length; i++) {
if (i == 0)
$("#selPARSubCat").html("<option value=''>Please Select...</option>");
if (DivList[i].toUpperCase() == tempSubCat.toUpperCase()) {
$("#selPARSubCat").append("<option selected=selected label='" + DivList[i] + "' value='" + DivList[i] + "'>" + Div + DivList[i] + "</option>");
} else {
$("#selPARSubCat").append("<option label='" + DivList[i] + "' value='" + DivList[i] + "'>" + Div + DivList[i] + "</option>");
}
}
if ($("#selPARSubCat option").length > 1) {
$("#selPARSubCat").closest("td").show();
$("#selPARSubCat").addClass("required");
} else {
$("#selPARSubCat").closest("td").hide();
$("#selPARSubCat").removeClass("required");
$("#selPARSubCat").removeClass("requiredInput");
}
}
//re-load and populate the Plant drop down box.
var tempPlant = $("#txtPARPlant").val();
var SubList = g_SubCatList[$("#selPARSubCat option:selected").text().toUpperCase()];
var SubCat = $("#selPARSubCat option:selected").html();
if (tempPlant != "") {
for (var i = 0; i < SubList.length; i++) {
if (i == 0)
$("#selPARPlant").html("<option value=''>Please Select...</option>");
if (SubList[i].toUpperCase() == tempPlant.toUpperCase()) {
$("#selPARPlant").append("<option selected=selected label='" + SubList[i] + "' value='" + SubList[i] + "'>" + SubCat + SubList[i] + "</option>");
} else {
$("#selPARPlant").append("<option label='" + SubList[i] + "' value='" + SubList[i] + "'>" + SubCat + SubList[i] + "</option>");
}
}
if ($("#selPARPlant option").length > 1) {
$("#selPARPlant").closest("td").show();
$("#selPARPlant").addClass("required");
} else {
$("#selPARPlant").closest("td").hide();
$("#selPARPlant").removeClass("required");
$("#selPARPlant").removeClass("requiredInput");
}
}
}
//Cascade Reload - END
try {
$("#selPARCompany").bind("change", function () {
var Comp = $(this).val();
$("#selPARDivision").html("<option value=''>Please Select...</option>");
$("#txtPARDivision").val("");
$("#selPARSubCat").html("<option value=''>Please Select...</option>");
$("#txtPARSubCat").val("");
$("#selPARPlant").html("<option value=''>Please Select...</option>");
$("#txtPARPlant").val("");
if ($(this)[0].selectedIndex > 0) {
var CompList = g_CompanyList[Comp];
for (var i = 0; i < CompList.length; i++) {
//$("#selPARDivision").append("<option value='" + Comp + CompList[i] + "'>" + CompList[i] + "</option>");
$("#selPARDivision").append("<option label='" + CompList[i] + "' value='" + CompList[i] + "'>" + Comp + CompList[i] + "</option>");
}
}
$("#selPARDivision").addClass("fullwidth");
$("#txtPARCompany").val($("#selPARCompany").val());
if ($("#selPARDivision option").length > 1) {
$("#selPARDivision").closest("td").show();
$("#selPARDivision").addClass("required");
$("#selPARSubCat").closest("td").hide();
$("#selPARSubCat").removeClass("required");
$("#selPARSubCat").removeClass("requiredInput");
$("#selPARPlant").closest("td").hide();
$("#selPARPlant").removeClass("required");
$("#selPARPlant").removeClass("requiredInput");
} else {
$("#selPARDivision").closest("td").hide();
$("#selPARDivision").removeClass("required");
$("#selPARDivision").removeClass("requiredInput");
$("#selPARSubCat").closest("td").hide();
$("#selPARSubCat").removeClass("required");
$("#selPARSubCat").removeClass("requiredInput");
$("#selPARPlant").closest("td").hide();
$("#selPARPlant").removeClass("required");
$("#selPARPlant").removeClass("requiredInput");
}
CompanyTabOverride(Comp);
IsEngineeringLevelRequired(Comp);
IsUniqPlanIDRequired(Comp, $('#selPARExpenditureinBusinessPlan').find(":selected").text());
//$('#selPARExpenditureinBusinessPlan').change();
});
$("#selPARDivision").bind("change", function () {
var Div = $("#" + $(this).attr("id") + " option:selected").html();
$("#selPARSubCat").html("<option value=''>Please Select...</option>");
$("#txtPARSubCat").val("");
$("#selPARPlant").html("<option value=''>Please Select...</option>");
$("#txtPARPlant").val("");
if ($(this)[0].selectedIndex > 0) {
var DivList = g_DivisionList[Div];
if (DivList) {
for (var i = 0; i < DivList.length; i++) {
//$("#selPARSubCat").append("<option value='" + Div + DivList[i] + "'>" + DivList[i] + "</option>");
$("#selPARSubCat").append("<option label='" + DivList[i] + "' value='" + DivList[i] + "'>" + Div + DivList[i] + "</option>");
}
}
}
$("#selPARSubCat").addClass("fullwidth");
$("#txtPARDivision").val($("#selPARDivision").val());
if ($("#selPARSubCat option").length > 1) {
$("#selPARSubCat").closest("td").show();
$("#selPARSubCat").addClass("required");
$("#selPARPlant").closest("td").hide();
$("#selPARPlant").removeClass("required");
$("#selPARPlant").removeClass("requiredInput");
} else {
$("#selPARSubCat").closest("td").hide();
$("#selPARSubCat").removeClass("required");
$("#selPARSubCat").removeClass("requiredInput");
$("#selPARPlant").closest("td").hide();
$("#selPARPlant").removeClass("required");
$("#selPARPlant").removeClass("requiredInput");
}
DivisionTabOverride($("#selPARCompany").val(), $(this).val());
});
$("#selPARSubCat").bind("change", function () {
//var SubCat = $(this).val();
var SubCat = $("#" + $(this).attr("id") + " option:selected").html();
$("#selPARPlant").html("<option value=''>Please Select...</option>");
$("#txtPARPlant").val("");
if ($(this)[0].selectedIndex > 0) {
var SubList = g_SubCatList[SubCat];
if (SubList) {
for (var i = 0; i < SubList.length; i++) {
//$("#selPARPlant").append("<option value='" + SubCat + SubList[i] + "'>" + SubList[i] + "</option>");
$("#selPARPlant").append("<option label='" + SubList[i] + "' value='" + SubList[i] + "'>" + SubCat + SubList[i] + "</option>");
}
}
}
$("#selPARPlant").addClass("fullwidth");
$("#txtPARSubCat").val($("#selPARSubCat").val());
if ($("#selPARPlant option").length > 1) {
$("#selPARPlant").closest("td").show();
$("#selPARPlant").addClass("required");
} else {
$("#selPARPlant").closest("td").hide();
$("#selPARPlant").removeClass("required");
$("#selPARPlant").removeClass("requiredInput");
}
});
$("#selPARPlant").bind("change", function () {
$("#txtPARPlant").val($("#selPARPlant").val());
});
}
catch (err) {
alert("loadForm: if GroupDocList>0: bind Group Change:" + err);
}
}
}
catch (err) {
alert("loadForm: if GroupDocList>0: " + err);
}

Javascript button delete and edit

I can add a user just fine, but when I try to delete or edit someone my button doesn't work. I tried to put an alert to see what's wrong but I can't find anything.
As you can see it creates the button delete and edit when you add someone to the table.
Here's my js code:
var nextId = 1;
var activeId = 0;
$(document).ready(function() {
$("#addBtn").on("click", function() {
var name = $("#txtNome").val();
if (name.trim().length < 3 || $("#txtIdade").val() == "") {
alert("Dados Incorretos, Por favor, digite o seu nome e idade.");
$("#txtNome").focus();
return false;
} else {
addt();
formClear();
}
});
$("#btnDelete").on("click", function(delete_button) {
$(delete_button).parents("tr").remove();
});
$("#btnEdit").click(function() {
var row = $(edit_button).parents("tr");
var cols = row.children("td");
activeId = $($(cols[2]).children("button")[0]).data("id");
$("#txtNome").val($(cols[0]).text());
$("#txtIdade").val($(cols[1]).text());
$("#edt").css("display", "inline-block");
$("#addBtn").prop("disabled", true);
})
function addt() {
if ($("#tblUser tbody").length == 0) {
$("#tblUser").append("<tbody></tbody>");
}
$("#tblUser tbody").append(addUserToTable(nextId));
nextId += 1;
}
function addUserToTable(id) {
var row =
"<tr>" +
"<td>" + $("#txtNome").val() + "</td>" +
"<td>" + $("#txtIdade").val() + "</td>" +
"<td>" +
"<button type='button' style='margin-right:20px;' " + "id='btnEdit' " + "class='btn btn-default'" + "data-id='" + nextId + "'>" + "<span class='glyphicon glyphicon-edit'></span>" +
"</button>" +
"<button type='button' " + "id='btnDelete'" + "class='btn btn-default'" + "data-id='" + nextId + "'>" + "<span class='glyphicon glyphicon-remove'></span>" +
"</button>" +
"</td>" +
"</tr>"
return row;
nextId += 1;
}
function formClear() {
$("#txtNome").val("");
$("#txtIdade").val("");
}
function attTable(id) {
var row = $("#tblUser button[data-id='" + id + "']").parents("tr")[0];
$(row).after(addUserToTable());
$(row).remove();
formClear();
$("#edt").css("display", "none");
}
});
As you are adding String content(in form of HTML) to a table, so these are the new content for document, and Jquery has bind all event at time of page load,
So when you add dynamic content to table, you explicitly need to bind the events to DOM elements (in your case edit and delete button)
Please try following code,
<script>
var nextId = 1;
var activeId = 0;
$(document).ready(function(){
$("#addBtn").on("click",function(){
var name = $("#txtNome").val();
if (name.trim().length < 3 || $("#txtIdade").val() == "") {
alert("Dados Incorretos, Por favor, digite o seu nome e idade.");
$("#txtNome").focus();
return false;
} else {
addt();
formClear();
}
});
$("#btnDelete").on("click",deletebutton);
function deletebutton(){
$(this).parents("tr").remove();
}
$("#btnEdit").click(editButton);
function editButton(){
var row = $(this).parents("tr");
var cols = row.children("td");
activeId = $($(cols[2]).children("button")[0]).data("id");
$("#txtNome").val($(cols[0]).text());
$("#txtIdade").val($(cols[1]).text());
$("#edt").css("display", "inline-block");
$("#addBtn").prop("disabled" , true);
}
function addt(){
if ($("#tblUser tbody").length == 0) {
$("#tblUser").append("<tbody></tbody>");
}
var btn = $(addUserToTable(nextId));
$(btn).find("#btnEdit").bind('click', editButton);
$(btn).find("#btnDelete").bind('click', deletebutton);
$("#tblUser tbody").append($(btn));
nextId += 1;
}
function addUserToTable(id) {
var row =
"<tr>" +
"<td>" + $("#txtNome").val() + "</td>" +
"<td>" + $("#txtIdade").val() + "</td>" +
"<td>" +
"<button type='button' style='margin-right:20px;' " + "id='btnEdit' " + "class='btn btn-default'" + "data-id='" + nextId + "'>" + "<span class='glyphicon glyphicon-edit'></span>" +
"Edit </button>" +
"<button type='button' " + "id='btnDelete'" + "class='btn btn-default'" + "data-id='" + nextId + "'>" + "<span class='glyphicon glyphicon-remove'></span>" +
"Delete</button>" +
"</td>" +
"</tr>"
return row;
nextId += 1;
}
function formClear() {
$("#txtNome").val("");
$("#txtIdade").val("");
}
function attTable(id) {
var row = $("#tblUser button[data-id='" + id + "']").parents("tr")[0];
$(row).after(addUserToTable());
$(row).remove();
formClear();
$("#edt").css("display", "none");
}
});
</script>
I hope this will solve your problem
I have tried with following HTML content
<table id="tblUser"></table>
<input type="button" id="addBtn" value="addBtn"/><br/>
<input type="button" id="btnDelete" value="btnDelete"/><br/>
<input type="button" id="btnEdit" value="btnEdit"/><br/>
txtNome: <input type="text" id="txtNome" value="Name 1" /><br/>
txtIdade: <input type="text" id="txtIdade" value="Name 2"/><br/>

How to sum Total JSON Results?

i have this script to take data from JSON Results, also this script filter results by ID
$(document).ready(function () {
//Call EmpDetails jsonResult Method
$.getJSON("/smetkis/getTrosokList",
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
if (json[i].skID == '#Html.DisplayFor(model => model.smID)') {
tr = $('<tr />');
tr.append("<td >" + json[i].Artikal + "</td>");
tr.append("<td>" + json[i].kol + "</td>");
tr.append("<td>" + json[i].cena + "</td>");
tr.append($('<td class="vkupno1">' + json[i].vkupnot + '</td>'));
$('table').append(tr);
}
}
});
});
Also i have this script sor SUM Of column with class vkupno1, but not understand the results from cell.
$(document).ready(function () {
colSum();
});
function colSum() {
var sum = 0;
$(".vkupno1").each(function () {
sum += parseFloat($(this).text());
});
$('#result').html((sum).toFixed(2).replace(/(\d)(?=(\d{6})+(?!\d))/g, "$1.") + " €");
}
How to sum (json[i].vkupnot)-value or cell classed "vkupno1"
here is JSON Results:
[{"smetki":null,"trId":1,"skID":1,"Artikal":"gdfgsdgfdg","kol":4.00,"cena":4.00,"vkupnot":16.00},{"smetki":null,"trId":4,"skID":4,"Artikal":"kjhkjhkjhk","kol":7.00,"cena":7.00,"vkupnot":47.00},{"smetki":null,"trId":5,"skID":4,"Artikal":"lkjlkjlk","kol":8.00,"cena":8.00,"vkupnot":64.00},{"smetki":null,"trId":6,"skID":5,"Artikal":"gdfg","kol":5.00,"cena":5.00,"vkupnot":25.00},{"smetki":null,"trId":7,"skID":6,"Artikal":"gdfg","kol":5.00,"cena":5.00,"vkupnot":25.00},{"smetki":null,"trId":8,"skID":7,"Artikal":"gagaggag","kol":5.00,"cena":55.00,"vkupnot":275.00},{"smetki":null,"trId":9,"skID":7,"Artikal":"ggg","kol":4.00,"cena":65.00,"vkupnot":260.00}]
You can add the values from response itself without reading from DOM.
Try this
$(document).ready(function() {
//Call EmpDetails jsonResult Method
$.getJSON("/smetkis/getTrosokList",
function(json) {
var tr;
var sum = 0; //initialising sum
for (var i = 0; i < json.length; i++) {
if (json[i].skID == '#Html.DisplayFor(model => model.smID)') {
tr = $('<tr />');
tr.append("<td >" + json[i].Artikal + "</td>");
tr.append("<td>" + json[i].kol + "</td>");
tr.append("<td>" + json[i].cena + "</td>");
tr.append($('<td class="vkupno1">' + json[i].vkupnot + '</td>'));
$('table').append(tr);
sum += parseFloat(json[i].vkupnot); //adding directly from the response
}
}
$('#result').html((sum).toFixed(2).replace(/(\d)(?=(\d{6})+(?!\d))/g, "$1.") + " €");
});
});
And you need to wait for the response before reading the dynamically created DOM elements.

Jquery open/close variable for adding and removing class

As you can see i want to do and if/else statement for adding and removing classes. But the if/else statematen below isn't really working for me, it adds the classes but it doesn't remove them again, when i click second time.
function showAndHidediv(id, liName) {
$("#" + id).toggle(function () {
$("#" + id).animate({
display: 'block'
}, 500);
var open = "closed";
if (open == "open") {
$("#" + liName + " a").removeClass('color');
$("#" + liName + " a div").removeClass('block');
$("#" + liName + " img").removeClass('block');
open = "closed";
} else {
$("#" + liName + " a").addClass('color');
$("#" + liName + " a div").addClass('block');
$("#" + liName + " img").addClass('block');
open = "open";
}
});
}
You can use toggle class to resolve your problem.
In above code snippet you have taken local JS variable.i.e.var open = "closed";
So everytime its gatting reset.
Try declaring 'open' variable globally and then check. It will work.
Since you are using jQuery it would be more convenient to use built-in function toggleClass():
$( "p" ).click(function() {
$( this ).toggleClass( "highlight" );
});
DEMO FIDDLE
And your case:
function showAndHidediv(id, liName) {
$("#" + id).toggle(function () {
$("#" + id).animate({
display: 'block'
}, 500);
$("#" + liName + " a").toggleClass('color');
$("#" + liName + " a div").toggleClass('block');
$("#" + liName + " img").toggleClass('block');
});
}
Try like this
function showAndHidediv(id, liName) {
$("#" + id).toggle(function () {
$("#" + id).animate({
display: 'block'
}, 500);
var open = false;
if (open == "open") {
$("#" + liName + " a").removeClass('color');
$("#" + liName + " a div").removeClass('block');
$("#" + liName + " img").removeClass('block');
open =false;
} else {
$("#" + liName + " a").addClass('color');
$("#" + liName + " a div").addClass('block');
$("#" + liName + " img").addClass('block');
open = true;
}
});
}

Categories