Alright, so i have textbox where I enter grades, and then they're saved in localstorage and i can see them under my textbox. But if I want to add more text boxes in which i can add more grades, and they will be saved in localstorage but they will be in another array or something how i can do that? I will be grateful for any help.
$(document).ready(function () {
var i = 0;
for (i = 0; i < localStorage.length; i++) {
var gradeID = "grade-" + i;
$('#gradeList').append("<b id='" + gradeID + "'>" + localStorage.getItem(gradeID) + "</b>, ");
}
$('#clear').click(function () {
localStorage.clear();
});
$('#gradeEntryForm').submit(function () {
if ($('#gradeInput').val() !== "") {
var gradeID = "grade-" + i;
var gradeMessage = $('#gradeInput').val();
localStorage.setItem(gradeID, gradeMessage);
$('#gradeList').append("<b class='task' id='" + gradeID + "'>" + gradeMessage + "</b>, ");
var grade = $('#' + gradeID);
task.slideDown();
$('#gradeInput').val("");
i++;
}
return false;
});
$('#gradeList').on("click", "b", function (event) {
self = $(this);
gradeID = self.attr('id');
localStorage.removeItem(gradeID);
self.remove();
});
});
DEMO
You can set dynamic id to your LocalStorage keys which you can relate to your generated TextBoxes
Something like below
localStorage['grade_' + some_id] = value;
You could use the following example:
document.getElementById("addGrade").onclick = function() {
var gradeCell = document.getElementById("gradeCell");
var input = document.createElement("input");
input.type = "number";
var br = document.createElement("br");
gradeCell.appendChild(input);
gradeCell.appendChild(br);
}
EXAMPLE
Related
I have this code where I can fill different amounts ir order. I can create more inputs in order to create more amounts to calculate them. But for some reason, when I press enter in one of them in order to create another input/entry, it goes to the Reset function, which erases every field. It shouldn't call the reset function on the key press.
var intId = 0;
var maindiv = $("#maindiv");
var divpeso ="";
var inputnumber ="";
var fieldname = "";
var removeButton = "";
function anadir_input() {
// var lastField = $("#container div:last");
intId = intId + 1;
divpeso = $("<div class=\"input-group mb-3\" id=\"divpeso" + intId + "\"/>");
inputnumber = $("<input id=\"peso" + intId + "\" type=\"number\" class=\"form-control\" name=\"peso" + intId + "\" maxlength=\"5\" size=\"5\" step=\".01\" />");
fieldname = $("<div class=\"input-group-append\"><span class=\"input-group-text\">Peso" + intId + "</span></div>");
removeButton = $("<input type=\"button\" class=\"btn btn-outline-danger\" value=\"Quitar\" />");
removeButton.click(function () {
$(this).parent().remove();
});
inputnumber.keypress(function (e) {
if (e.which == 13) {
console.log("enter apretado");
}
});
divpeso.append(inputnumber);
divpeso.append(fieldname);
divpeso.append(removeButton);
$("#container").append(divpeso);
};
$(document).ready(function () {
$("#anadir").click(function () {
anadir_input();
});
$("#reset").click(function () {
console.log("reset");
$('[id*=divresultado]:visible').each(function () {
$(this).remove();
});
$('[id^=peso]:visible').each(function () {
$(this).val('');
});
$('[id^=divpeso]:visible').each(function () {
$(this).remove();
});
intId = 0;
});
$("#resultado").click(function () {
var pesosordenados = [];
var capacidad = Number($("#capacidad").val());
var pesos = [];
capacidad = $("#capacidad").val();
$('[id*=divresultado]:visible').each(function () {
$(this).remove();
});
$('[id^=peso]:visible').each(function () {
if ($(this).val() != 0 || $(this).val() != null || $(this).val() != undefined)
pesos.push($(this).val());
pesosordenados = pesos.sort(function (a, b) {
return b - a
});
});
var contenedores = [];
var sobrepesos = [];
//algoritmo para rellenar los contenedores con los distintos pesos.
while (pesosordenados.length > 0) {
var unidadcontenedor = [];
var pesosnousados = [];
var restcapacidad = Number(capacidad);
for (var i = 0; i < pesosordenados.length; i++) {
if (Number(pesosordenados[i]) > capacidad) { //si el peso es mas grande que la capacidad del contenedor
sobrepesos.push(Number(pesosordenados[i]));
} else {
if (Number(pesosordenados[i]) <= restcapacidad && restcapacidad >= pesosordenados[pesosordenados.length - 1]) {
unidadcontenedor.push(Number(pesosordenados[i]));
restcapacidad = restcapacidad - Number(pesosordenados[i]);
} else {
pesosnousados.push(pesosordenados[i]);
}
}
}
contenedores.push(unidadcontenedor);
pesosordenados = pesosnousados;
}
for (var m = 0; m < contenedores.length; m++) {
var divresultado = $("<div id=\"divresultado\" class=\"calculadora\"></div>");
var titulo = $("<h5 class=\"card-title\">Contenedor " + (Number(m) + 1) + "</h5>");
var contpesorelleno = $("<h5 class=\"card-title\">Peso cargado: " + contenedores[m].reduce((a, n) => (a + Number(n)), 0) + "</h5>");
var contpesolibre = $("<h5 class=\"card-title\">Peso libre: " + (Number(capacidad) - Number(contenedores[m].reduce((a, n) => (a + Number(n)), 0))) + "</h5>");
divresultado.append(titulo);
divresultado.append(contpesorelleno);
divresultado.append(contpesolibre);
for (var n = 0; n < contenedores[m].length; n++) {
var resultfield = $("<div class=\"input-group-append\"><span class=\"input-group-text\">" + contenedores[m][n] + "</span></div>");
divresultado.append(resultfield);
}
maindiv.append(divresultado);
}
//para sumar toda una array: arrayloquesea.reduce((a, n) => (a + Number(n)), 0)
});
});
You have the JSFiddle here.
Steps to reproduce:
-Press the green button "AƱadir peso".
-Click on the created input field and press enter.
Another input field is created but also reset function erases them all.
EDIT:
I solved the issue with type="reset" in the html and also with e.preventDefault(); in the keypress function in the js. However, it does not show the div maindiv.append(divresultado); with the results.
Everything is fine just type="reset" is missing in reset button.
<button type="reset" id="reset" class="btn btn-danger cincuw">Reset</button>
No, it's not reseting, you are not providing the input value to begin with, your js $("#anadir").click() function should look like this:
$("#anadir").click(function () {
anadir_input($('input[name="capacidad"]').val());
});
and anadir_input function should put the passed input value:
function anadir_input(inputValue) {
// var lastField = $("#container div:last");
intId = intId + 1;
divpeso = $("<div class=\"input-group mb-3\" id=\"divpeso" + intId + "\"/>");
inputnumber = $("<input id=\"peso" + intId + "\" type=\"number\" class=\"form-control\" name=\"peso" + intId + "\" maxlength=\"5\" size=\"5\" step=\".01\" value='"+inputValue+"' />");
fieldname = $("<div class=\"input-group-append\"><span class=\"input-group-text\">Peso" + intId + "</span></div>");
removeButton = $("<input type=\"button\" class=\"btn btn-outline-danger\" value=\"Quitar\" />");
removeButton.click(function () {
$(this).parent().remove();
});
inputnumber.keypress(function (e) {
if (e.which == 13) {
console.log("enter apretado");
}
});
divpeso.append(inputnumber);
divpeso.append(fieldname);
divpeso.append(removeButton);
$("#container").append(divpeso);
};
I have changed your fiddle to see the output difference: https://jsfiddle.net/z4sgnr28/
I hope it makes sense
while click the save button i am running the dynamic table in each function inside handler to save the dynamic row upload file after it save i am saving in json the value.
After the value saved in hiddenfield it clear the hidden field value . its not store in the hidden field.
i need the hiddenfield json value to save in the database
$('#tblPower tbody tr').each(function () {
debugger;
var stre = $(this).children('td:nth-child(4)').find('input[type="file"]').attr("id");
var country = $(this).children('td:nth-child(1)').find('.Country').val() || 0;
var validity = $(this).children('td:nth-child(2)').find('.validity').val() || 0;
var clavalidity = $(this).children('td:nth-child(3)').find('.clavalidity').val();
var POAID = $(this).children('td:nth-child(2)').find('span').text() || 0;
var FileName = "";
var uploadfiles = $("#" + stre + "").get(0);
var uploadedfiles = uploadfiles.files;
var fromdata = new FormData();
for (var i = 0; i < uploadedfiles.length; i++) {
fromdata.append(uploadedfiles[i].name, uploadedfiles[i]);
}
var choice = {};
choice.url = "UploadHandler.ashx";
choice.type = "POST";
choice.data = fromdata;
choice.contentType = false;
choice.processData = false;
choice.success = function (result) {
FileName = result;
if (power == '') {
power = '{"POAID":"' + POAID + '","Country":"' + country + '","Validity":"' + validity + '","Notes":"' + clavalidity + '","UploadId":"' + stre + '","FileName":"' + FileName + '"}';
}
else {
power += ',{"POAID":"' + POAID + '","Country":"' + country + '","Validity":"' + validity + '","Notes":"' + clavalidity + '","UploadId":"' + stre + '","FileName":"' + FileName + '"}';
}
power = '[' + power + ']';
dynamic(power);
**$('#hfAttorney').val(power);**
};
choice.error = function (err) {
alert(err.statusText);
};
$.ajax(choice);
});
I am trying to use dynamically created IDs in javascript function, but it's not working. I thought that prepending # to string id should work, but it's not.
Code:
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("'#" + idCheckBoxToCompare + "'").prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("'#" + textBoxID + "'").val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("'#" + idInputBox + "'").val();
if ($("'#" + idCheckBox + "'").prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("'#" + idCheckBox + "'").prop('checked', false);
}
}
}
}
}
I've tried to build same id as this is:
'#testid'
so usage would be:
$('#testid')
But it's not working. How to use properly dynamically created IDs?
Your code is look complicated with too many " and '. Also Javascript can concat string and number by just use +. No need to convert it to string first. So, I updated it to make it more readable.
Try this
var IterateCheckedDatesAndUncheckWithSameValue = function(elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber;
if ($('#' + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber;
textBoxValue = $('#' + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i;
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i;
inputBoxValue = $('#' + idInputBox).val();
if ($('#' + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$('#' + idCheckBox).prop('checked', false);
}
}
console.log('#' + idCheckBox); //print here just to see the id results
}
}
}
ID in html can be only one element per page. So please make sure that the ID you generate from this method not match with other.
Jquery selector can read String variable.
So you can just do var id = "#test". Then put it like this $(id).
Or
var id = "test"; then $("#"+test).
Use this,
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("#" + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("#" + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("#" + idInputBox).val();
if ($("#" + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("#" + idCheckBox).prop('checked', false);
}
}
}
}
}
I face the same problem using Jquery .Try $(document).getElementbyId('myid'). Hope help.
Edit
Change :
$("#" + idCheckBoxToCompare) by $(document).getElementbyId(idCheckBoxToCompare)
I have been following an online tutorial to autocomplete textboxes with database values after the user enters a code greater than 7 characters. I have completed most of what I am trying to achieve however I cannot seem to select a value from the combobox to autocomplete the textbox.
I dont have much javascript experience but I am hoping the problem is something small in what I already have, can someone please recommend the change I need to make to select the value from the combobox.
public ActionResult MultiColumnComboBox(string SearchFor, string ControlId)
{
ViewBag.ProcId = SearchFor.Trim();
ViewBag.ControlBlockId = "block" + ControlId.Trim();
ViewBag.ControlId = ControlId.Trim();
ViewBag.ControlTxtId = "txt" + ControlId.Trim();
return View();
}
public JsonResult LoadComboData(string strSearch, string SearchFor)
{
efacsdbEntities db = new efacsdbEntities();
strSearch = strSearch.Trim();
if (SearchFor.Trim() == "employee" && strSearch.Length>7)
{
var res = (from E in db.allpartmasters
where E.partnum.ToLower().Contains(strSearch.ToLower()) || E.partdesc.ToLower().Contains(strSearch.ToLower())
select new
{
E.partnum,
E.partdesc
}).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
<input type="hidden" id="#ViewBag.ProcId" name="#ViewBag.ProcId" value="" />
<input type="hidden" id="#ViewBag.ControlId" name="#ViewBag.ControlId" value="" />
<input type="text" name="#ViewBag.ControlTxtId" id="#ViewBag.ControlTxtId" autocomplete="on" />
<div class="#ViewBag.ControlTxtId renderpart">
<div class="DataBlock">
<div id="#ViewBag.ControlBlockId" style="max-width: 520px;">
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../Scripts/json.debug.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".renderpart").hide();
var txtid = "#" + '#ViewBag.ControlTxtId';
var renderpart = "." + '#ViewBag.ControlTxtId';
var selectlinkvalueid = ".Get" + '#ViewBag.ProcId';
$(selectlinkvalueid).on("click", function () {
var value = $(this).attr('id');
var valueText = $(this).attr('title');
$("##ViewBag.ControlId").val(value);
$(txtid).val(valueText);
$(renderpart).slideUp("slow");
});
$(txtid).keyup(function () {
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var activecols = $("#hdnActiveColumns").val();
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
$(txtid).focusin(function () {
var txtid = "#" + '#ViewBag.ControlTxtId';
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
function CreateDynamicTable(objArray, tempprocId) {
var array = JSON.parse(objArray);
var str = '<table style="width:100%;">';
str += '<tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr>';
str += '<tbody>';
var flag = false;
var ids;
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr>' : '<tr>';
for (var index in array[i]) {
if (flag == false) {
ids = array[i][index];
flag = true;
}
str += '<td><a id="' + ids + '" class="Get' + tempprocId + '" title="' + array[i][index] + '" href="#">' + array[i][index] + '</a></td>';
}
str += '</tr>';
}
str += '</tbody>';
str += '</table>';
return str;
}
});
$(document).click(function (evt) {
var renderpart = "." + '#ViewBag.ControlTxtId';
var theElem = (evt.srcElement) ? evt.srcElement : evt.target;
if (theElem.id == "main" || theElem.id == "sub1") {
$(renderpart).slideUp("fast");
}
});
</script>
Here is the link to the tutorial I was following as well.
Create Multiple column autocomplete combobox
I'm trying to get and sort all the items in localStorage and output it to an HTML page.
This is what I'm doing:
<script>
function ShoppingCart() {
var totalPrice = 0;
var output;
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
productName = result.name
productAlbum = result.album;
productQuantity = result.quantity;
productPrice = parseFloat(result.price).toFixed(2);
productSubTotal = parseFloat(productQuantity * productPrice).toFixed(2);
outputName = "<div id='cart-table'><table><tr><td><b>NAME: </b>" + productName + "</td></tr></div>" ;
outputAlbum = "<tr><td><b>ALBUM: </b>" + productAlbum + "</td></tr>" ;
outputQuantity = "<tr><td><b>QUANTITY: </b>" + productQuantity + "</td></tr>";
outputPrice = "<tr><td><b>PRICE: </b> EUR " + productPrice + "</td></tr>";
outputSubTotal = "<tr><td><b>SUB-TOTAL: </b> EUR " + productSubTotal + "</td></tr></table><br><br>";
var outputTotal = "<table><tr><td><b>TOTAL:</b> EUR " + totalPrice + "</td></tr></table>";
var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal + outputTotal;
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
}
}
alert(TotalOutput);
}
window.onload = ShoppingCart;
</script>
The only item that is being output is the item named 'Proudct_0' in localStorage. Others are not being displayed!
This is what I have in localStorage: http://i.imgur.com/sHxXLOL.png
Any idea why this is happening ?
something wrong in your code.
What do you think if Product_0 not in the localStorage?
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
may be null and throw an error.
Try this:
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem(keyName);
//do your code here
}
}
Update
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
it's replace, not append
Hope this help!