Increment In my Jquery No Working Fine? - javascript

i wanna increment hidden field value append in jquery but its not incrementing just printing "2" when i print value beforing initializing it to hidden field my code is,
<script type="text/javascript">
var k=0,j=0;
$(document).ready(function () {
$("#btnAdd").click(function () {
var field = $("#field").val();
var DDL_fromProfession="<select name='ParametersFromProf' id='DDL_FromProYear'>";
for(var i=1950;i<2012;i++)
{
DDL_fromProfession +="<option text='"+i+"' value='"+i+"'>"+i+"</option>";
}
DDL_fromProfession +="</select>";
var DDL_ToProfession="<select name='ParametersToProf' id='DDL_ToProYear'>";
for(var i=1950;i<2012;i++)
{
DDL_ToProfession +="<option text='"+i+"' value='"+i+"'>"+i+"</option>";
}
DDL_ToProfession +="</select>";
k+=1;
var newRow1="<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+DDL_fromProfession +" to "+DDL_ToProfession +"</td></tr>"
+"<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+"<input type='checkbox' name='chkbx_CurrPro"+k+"' value='Yes'>I currently work here</input>"
+"<input type='hidden' id='hide' name='hidden' value='"+k+"'></input>";
// alert(document.getElementByName("valPro").value);
//alert($('input').attr('hidden'));
//alert($('input#hide').val());
var input = "<input name='parameters' id='field' type='text' />";
var input1="<input name='parametersCompany' id='field' type='text'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " +input1 +"</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
var value = parseInt($(":hidden[name='hidden']").val()) + 1;
alert(value);
});
});
</script>
Hidden Field:
+"<input type='hidden' id='hide' name='hidden' value='"+k+"'></input>";
Printing Value:
var value = parseInt($(":hidden[name='hidden']").val()) + 1;
alert(value);
Hopes for your suggestion

I think you want the hidden value(:hidden[name='hidden']) = 2 (value writtent in alert)?
Then you must write a line after var value = parseInt($(":hidden[name='hidden']").val()) + 1; => $(":hidden[name='hidden']").val(value);
In this case your hidden value is 1 as you can test by alert(parseInt($(":hidden[name='hidden']").val()))

Related

how to get the text of an html input generated by javascript?

I'm having a problem I'm using a numeric keypad that I found in codepen this one
https://codepen.io/matthewfortier/pen/ENJjqR
my objective is to store the generated pin in a database but it's a little difficult to do that because I'm taking the generated pin to an input but it looks like this
<input hidden="" id="pin" value="" name="pin">9345</input>
how do i get this generated pin and save it in database
the code is the same as the link
In your html you have this:
<input type="hidden" id="pin" value="9345" name="pin" />
In your Javascript you have this:
let value = document.getElementById('pin').value;
console.log(value);
$(function() {
var container = $(".numpad");
var inputCount = 6;
// Generate the input boxes
// Generates the input container
container.append("<div class='inputBoxes' id='in'></div>");
var inputBoxes = $(".inputBoxes");
inputBoxes.append("<form class='led' class='form-group' action='cadastro.php' method='post'></form>");
var led = $(".led");
// Generates the boxes
for(var i = 1; i < inputCount + 1; i++){
led.append("<input type='password' maxlength=1 class='inp' id='" + i + "' />");
}
led.append("<input type='password' maxlength=12 name='numero' value='93445566' id='numero' />");
led.append("<input type='text' name='te' id='te' placeholder='' />");
led.append("<button id='btn1' type='submit' onclick=''>enviar</button>");
container.append("<div class='numbers' id='inb'><p id='textoo'><span class='bolded'>PIN</span> do serviço MULTICAIXA</p></div>")
var numbers = $(".numbers");
// Generate the numbers
for(var i = 1; i <= 9; i++){
numbers.append("<button class='number' type='button' name='" + i + "' onclick='addNumber(this)'><span class='pin_font'>" + i + "</span></button>");
}
addNumber = function take(field,vall) {
if (!$("#1").val())
{
$("#1").val(field.name).addClass("dot");
}
else if (!$("#2").val())
{
$("#2").val(field.name).addClass("dot");
}
else if (!$("#3").val())
{
$("#3").val(field.name).addClass("dot");
}
else if (!$("#4").val())
{
$("#4").val(field.name).addClass("dot");
}
else if (!$("#5").val())
{
$("#5").val(field.name).addClass("dot");
}
else if (!$("#6").val())
{
$("#6").val(field.name).addClass("dot");
vall = $("#1").val() + $("#2").val() + $("#3").val() + $("#4").val()+ $("#5").val()+ $("#6").val();
document.getElementById("pini").innerHTML = vall;
}
}

How to retain add rows and its value even after page reload

Good day,
I have a table where you can dynamically add/remove rows, on each row you can add an select an item from the list its working perfectly at the moment, what I want to add is for it to retain the added rows and its values even if I page reload my browser?
I have seen on my research that you can attain it by using cookies/localStorage,but would be okay if I store many items on it?
heres my table looks like:
my JS:
function addRow(){
var rowCount = document.getElementById('tblItemList').rows.length - 1 ;
var rowArrayId = rowCount ;
var toBeAdded = document.getElementById('toBeAdded').value;
if (toBeAdded=='')
{ toBeAdded = 2; }
else if(toBeAdded>10)
{
toBeAdded = 10;
}
for (var i = 0; i < toBeAdded; i++) {
var rowToInsert = '';
rowToInsert = "<tr><td><input id='itemName"+rowArrayId+"' required name='product["+rowArrayId+"][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' />"+
"<input type='hidden' class='rowId' value='"+rowArrayId+"'>"+
"<input type='hidden' name='product[" + rowArrayId + "][itemId]' id='itemId'></td>";
$("#tblItemList tbody").append(
rowToInsert+
"<td><textarea readonly name='product["+rowArrayId+"][description]' class='form-control description' rows='1' ></textarea></td>"+
"<td><input type='number' min='1' max='9999' name='product["+rowArrayId+"][quantity]' class='qty form-control' required />"+
"<input id='poItemId' type='hidden' name='product[" + rowArrayId + "][poContentId]'></td>"+
"<td><input type='number' min='1' step='any' max='9999' name='product["+rowArrayId+"][price]' class='price form-control' required /></td>"+
"<td class='subtotal'><center><h3>0.00</h3></center></td>"+
"<input type='hidden' name='product["+rowArrayId+"][delete]' class='hidden-deleted-id'>"+
"<td class='actions'><a href='#' class='btnRemoveRow btn btn-danger'>x</a></td>"+
"</tr>");
var rowId = "#itemName"+rowArrayId;
$(rowId).select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
formatNoMatches: function( term ) {
$('.select2-input').on('keyup', function(e) {
if(e.keyCode === 13)
{
$("#modalAdd").modal();
$(".select2-input").unbind( "keyup" );
}
});
return "<li class='select2-no-results'>"+"No results found.<button class='btn btn-success pull-right btn-xs' onClick='modal()'>Add New Item</button></li>";
},
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
rowArrayId = rowArrayId + 1;
};
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
$(".qty, .price").bind("keyup change", calculate);
};
the problem here is whenever Im refreshing the page the Items that I added will also be lost as well as those rows that I've added, any suggestions please? Thanks you very much for your time! Have a nice Day!
Your best bet here would be to cookies to store json data.
Your best bet here would be to cookies to store json data.
function storeRowData() {
var data = [];
$('.TABLE_NAME tr').each(function () {
var $this = $(this),
pname = $this.find(PRODUCT_NAME_INPUT).val(),
desc = $this.find(PRODCUT_DESC_INPUT).val(),
quant = $this.find(PRODUCT_QUANTITY_INPUT).val(),
price = $this.find(PRODUCT_PRICE_INPUT).val();
var temp = { productName: pname, description: desc, quantity: quant, price: price };
data.push(temp);
});
$.cookie('Table_Rows', JSON.stringify(data), {OPTIONS});
}
Now whenever you add or remove rows, you can call this. And when you reload page just read the cookie and parse the string back to JSON and traverse and call addrow for each row.
NOTE: Be sure to read full documentation on jquery.cookie() Here
You can use window.location.reload(true) and $( document ).ready function where you can get current no. of rows.Define row count & column count variable as a global variable.
location.reload(true);
var rowCount,rowArrayId,toBeAdded ;
$(document).ready(function() {
rowCount= document.getElementById('tblItemList').rows.length - 1 ;
rowArrayId = rowCount ;
toBeAdded = document.getElementById('toBeAdded').value;
});

Multiple input fields using JS

Got the following JS code:
<script language="javascript">
fields = 0;
pNR = 0;
err = 0;
function addInput() {
if (fields != 40) {
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
fields += 1;
pNR += 1;
} else {
if (err == 0) {
document.getElementById('text').innerHTML += "<br />Adaugati maxim 40 ingrediente.";
err = 1;
}
document.form.add.disabled = true;
}
}
</script>
and the following HTML:
<input name="name" style="color:#ffffff;" class="name required" type="button" onclick="addInput()" value="Add" />
<div id="text">
</div>
By default, there are no fields. When I press the Add button (fields are added two by two with different names), fill in the fields and click again the Add button, the filled fields are emptied. What did I do wrong?
You aren't simply adding new inputs.
You are:
converting the existing ones to HTML (the value attribute is unchanged, it will still have the default value, not the current value)
adding the HTML for the new inputs to it
generating new DOM elements from that HTML.
Don't use innerHTML. Use createElement, appendChild and friends.
This:
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
Becomes this:
var firstInput = document.createElement("input");
var secondInput = document.createElement("input");
firstInput.type = secondInput.type = "text";
firstInput.name = "first" + pNR;
secondInput.name = "second" + pNR;
var text = document.getElementById("text");
text.appendChild(firstInput);
text.appendChild(secondInput);
text.appendChild(document.createElement("br"));
And, for the else case:
var text = document.getElementById("text");
text.appendChild(document.createElement("br"))
text.appendChild(document.createTextNode("Adaugati maxim 40 ingrediente."));
Working example: http://jsbin.com/OqIWeMum/2/edit

handling of checkboxes in an openWindow

I would like to display an infoWindow when I right click a marker.
The infoWindow must display 4 checkboxes according to values.
google.maps.event.addListener(marker,"rightclick", function()
{
html = "<table><tr><td>";
if (value1==...)
{
html = html + "<input type='checkbox' id='option1' checked>value1<br>";
}
else
{
html = html + "<input type='checkbox' id='option1'>value1<br>";
}
if (value2==...)
{
html = html + "<input type='checkbox' id='option2'checked>value2<br>";
}
else
{
html = html + "<input type='checkbox' id='option2' >value2<br>";
}
if (value3==...)
{
html = html + "<input type='checkbox' id='option3' checked>value3<br>";
}
else
{
html = html + "<input type='checkbox' id='option3' >value3<br>";
}
if (value4==...)
{
html = html + "<input type='checkbox' id='option4' checked>value4<br>";
}
else
{
html = html + "<input type='checkbox' id='option4' >value4<br>";
}
html = html + "</td></tr></table>";
marker.setContent(html)
infoWindow.open(map,marker);
});
1) Do you see a better implementation with jquery because this code is not elegant ?
2) If I click the checkbox #N, how to modify the value of the corresponding valueN ?
Something along the lines of this
var
values = [],
html = '';
for(i=1;i<n;i++) {
html += '<input type="checkbox" id="option"'+i+'" '+(values[i] == 'something' ? 'checked' : '')+'> value '+i+'<br/>';
}

Problem with jquery

I creating jquery code to generate specific html-blocks that contains html-controls (e.g. textbox, textarea, button) with two buttons - add new block and delete current block:
$(document).ready(function () {
// Constants
var SEPARATOR = "`";
var SEPARATOR_START = "<span class='Hidden'>";
var SEPARATOR_END = "</span>";
var SEPARATOR_BLOCK = SEPARATOR_START + SEPARATOR + SEPARATOR_END;
var CONTAINER = "#weContainer";
// Initialize container
InitializeDataContainer(CONTAINER);
// Buttons events
$(".AddBlock").click(function () {
AddBlock(CONTAINER);
});
$(".DeleteBlock").click(function () {
DeleteBlock(CONTAINER, GetParentId(this));
});
// Functions
function GetParentId(container) {
var id = ($(container).parent().attr("id")).replace(new RegExp("_", 'g'), "");
return id;
}
function Template() {
var uniqueId = Math.random() * 10000000;
var template = "<div class='weBlock' id='_" + uniqueId + "_'>";
template += "<input type='button' value='add' class=\"AddBlock\" />";
template += "<input type='button' value='del' class=\"DeleteBlock\" />";
template += "<br/>";
template += "<input type='text' class='weStartDate weTextbox' />";
template += " ";
template += "<input type='text' class='weEndDate weTextbox' />";
template += "<br/>";
template += "<input type='text' class='weCompany weTextbox' />";
template += " ";
template += "<input type='text' class='weJobTitle weTextbox' />";
template += "<br/>";
template += "<input type='text' class='weClients weTextbox' />";
template += " ";
template += "<input type='text' class='weProjectName weTextbox' />";
template += "<br/>";
template += "<textarea type='text' rows='4' cols='40' class='weProjectDesc weTextarea'></textarea>";
template += "<br/>";
template += "<textarea type='text' rows='6' cols='40' class='weActivities weTextarea'></textarea>";
template += "<br/>";
template += "<textarea type='text' rows='4' cols='40' class='weToolsTech weTextarea'></textarea>";
template += "</div>";
template += SEPARATOR_BLOCK;
return template;
}
function GetIdFromTemplate(template) {
var array = template.split('_');
return array[1];
}
function AddBlock(container) {
$(container).append(Template());
}
function DeleteBlock(container, id) {
var content = $(container).html();
content = content.replace(new RegExp("\<span class='Hidden'\>", "g"), "")
.replace(new RegExp("\</span\>", "g"), "");
var blocks = content.split(SEPARATOR);
content = "";
var index;
for (var i = 0; i < blocks.length; i++) {
if (GetIdFromTemplate(blocks[i]) != id && !IsNullOrEmpty(blocks[i])) {
content += blocks[i] + SEPARATOR_BLOCK;
}
else {
index = i;
}
}
$(container).html(content);
}
function IsNullOrEmpty(string) {
if (string == null || string == 'undefined' || string.length == 0) {
return true;
}
else {
return false;
}
}
function InitializeDataContainer(container) {
$(container).html(Template());
}
});
For the first time (when page load) i created first block:
function InitializeDataContainer(container) {
$(container).html(Template());
}
My problem is next - buttons Add and Delete work only for this first html-block that i created when page load, but if i add new blocks in page using Add button (from this first block that works) then buttons Add and Delete from this new blocks doesn't work!
Sorry for may be not good code, im not javascript engineer:)
Use the .live() instead:
$(".AddBlock").live("click", function () {
AddBlock(CONTAINER);
});
And same for the other class - the .click() is "static" only for the elements that exists in the time of calling it, while .live() should work for any existing or future elements.
Your jQuery code adds event handlers to the Add/Delete buttons you create uses click to do so:
$(".AddBlock").click(function () {
AddBlock(CONTAINER);
});
This only affects HTML elements that are already in the page.
One solution would be to change it to
$(".AddBlock").live('click', function () {
AddBlock(CONTAINER);
});
to make it also work for elements that get added to the page later.
Another solution would be to manually add the click event handlers to any elements you add to the page dynamically:
function AddBlock(container) {
var $template = $(Template());
$(container).append($template);
$template.find(".AddBlock").click, function () {
AddBlock(CONTAINER);
});
$template.find(".DeleteBlock").click, function () {
DeleteBlock(CONTAINER, GetParentId(this));
});
}

Categories