how to assign unique id to elements that are created dynamically - Javascript - php

Hello im trying to generate dynamic divs with a textbox and delete button in it. On form submit i want all dynamically generated textboxes values, how can i assign unique id to the textbox element. The ID's / Name of textbox should be unique.. to get all values properly.
Pls suggest..
My Code:
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic elements</TITLE>
<SCRIPT language="javascript">
function addRow(divId) {
count = 0;
count++;
var parentDiv = document.getElementById(divId);
// create a div dynamically
var eleDiv = document.createElement("div");
eleDiv.setAttribute("name", "olddiv");
eleDiv.setAttribute("id", "olddiv");
// create a textbox dynamically
var eleText = document.createElement("input");
eleText.setAttribute("type", "text");
eleText.setAttribute("name", 'textbox' + count);
eleText.setAttribute("id", "textbox");
// create a delete button dynamically
var eleBtn = document.createElement("input");
eleBtn.setAttribute("type", "button");
eleBtn.setAttribute("value", "delete");
eleBtn.setAttribute("name", "button");
eleBtn.setAttribute("id", "button");
eleBtn.setAttribute("onclick", "deleteRow('button')");
// append new div to parent div
parentDiv.appendChild(eleDiv);
// append textbox & button to new div
eleDiv.appendChild(eleText);
eleDiv.appendChild(eleBtn);
}
function deleteRow(tableID) {
var div = document.getElementById('olddiv');
if (div) {
div.parentNode.removeChild(div);
}
}
</SCRIPT>
<form name="objForm" action="test1.php">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<div id="dataTable" width="350px"><INPUT type="text" name="txtData" /></div>
<input type="submit" value="Submit"/>
</form>

You can keep a global count variable (outside of function divId).
Each time you create a new div, you add 1 to the counter and use it as a unique ID for your textbox.
<script language="javascript">
var globalcount=0;
function addRow()
{
globalcount++;
//the rest
}
</script>
And the rest is much like you already do for the name.

To answer your question directly you could try:
var textboxCount = 0;
/* In your function */
// create a textbox dynamically
var eleText = document.createElement("input");
eleText.setAttribute("type", "text");
eleText.setAttribute("name", 'textbox' + count);
eleText.setAttribute("id", "textbox" + textboxCount);
textboxCount += 1; //Increment the count
That will create textbox's with id's textbox0, textbox1, textbox2 etc.
Or, for a more efficient option you may store all textboxs you create in an array, like so:
var textboxes = new Array();
/* In your function */
// create a textbox dynamically
var eleText = document.createElement("input");
eleText.setAttribute("type", "text");
eleText.setAttribute("name", 'textbox' + count);
textboxes.push(eleText);
Now instead of calling e = document.getElementById('textbox4'); you may call e = textboxes[4];

This function will generate a unique ID:
function uniqueId() {
var uid;
do {
uid = 'uid-' + Math.random();
} while (document.getElementById(uid));
return uid;
}

Related

I want to make this similar HTML structure in jQuery function dynamically and append to html tag id="images"

I am uploading images and want to show separate progress bar for each image.
This kind of similar structure I want to create dynamically in jQuery. Here I m trying to create img element uploaded by input file and want to create html container classname 'preview' and put into already created #images tag by using jQuery. Will you please anyone fix it? so frustrated and thanks in advance to all intelligent brains here.
<div id="images"> // already exist
<div class="preview" id="rand">
<img src="background/balance.jpg" id="rand"/>
<div class="progressbar" id="rand">
</div> // this is the preview container to create and put by dynamically in jQuery function
</div>
this is my jQuery function.
function handleFile(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileReader=new FileReader();
var rand = Math.floor((Math.random()*100000)+3); /* this is created for assign id attribute to div and img tag to differentiate each other */
var imageElem=document.createElement("img");
imageElem.id=rand;
var div = document.createElement('div');
div.className = 'preview';
div.id = rand;
var progress = document.createElement('div');
progress.className='progressbar';
progress.id=rand;
fileReader.onload = (function(img)
{
return function(e)
{
img.src = e.target.result;
};
}) (imageElem);
/* here I am trying to create that structure */
document.getElementById("images").appendChild(imageElem); /* and need to append here */
fileReader.readAsDataURL(file);
// document.getElementById("areatext").style.display = "none";
document.getElementById("submit1").style.display = "block";
document.getElementById("submit2").style.display = "block";
uploadFile(file,rand);
}
}
function uploadFile(file,rand) {
var xhr = new Array();
xhr[rand] = new XMLHttpRequest();
var formData = new FormData();
formData.append('myFile[]',file);
xhr[rand].upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
$(".progressbar[id='"+rand+"']").css("width",(e.loaded / e.total) * 100 + "%");
}
}, false);
xhr[rand].open("POST", "drop.php");
xhr[rand].overrideMimeType('text/plain; charset=x-user-defined-binary');
xhr[rand].send(formData);
}

How to select multiple checkbox in jquery datatable with pagination?

I am using jquery datatables. There I am using check box for each row inside the table. Now I want when a user click select all link which is outside of table, will select all records in the table. For that I am using this function.
function checkAll(formname, checktoggle)
{
var checkboxes = new Array();
checkboxes = document[formname].getElementsByTagName('input');
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = checktoggle;
}
}
}
Here select all link is
<a onclick="javascript:checkAll('frm_charges', true);" href="javascript:void(0);">Select All</a>
"frm_charges" is the name and id of the form.
This is the code for check box, which I am using inside the table.
<input type="checkbox" value="742" name="charges[]" class="charges" style="opacity: 0; position: absolute; z-index: -1; visibility: hidden;">
Now my problem is I have pagination it is selecting rows from first page but not all page.
Try This:
$(function () {
var oTable = $('#datatable').dataTable();
$('#selectall').click(function () {
var checkall =$('.main_table').find(':checkbox').attr('checked','checked');
$.uniform.update(checkall);
});
});
$(function () {
var oTable = $('#datatable').dataTable();
$('#deselectall').click(function () {
//alert('hi');
var checkall =$('.main_table').find(':checkbox').attr('checked',false);
$.uniform.update(checkall);
});
});
So the problem is your javascript is only getting the checkboxes on the screen. What you need to do is get the checkboxes that are in the original table data. In the following example I get all of the table data, loop through it marking the checkboxes and redraw the data table:
// var oTable - reference to your datatable object
var checkboxColumn = 14; // column number that has the checkboxes in it
function checkAll(checktoggle) {
// get all datatable data
var data = oTable.fnGetData();
// loop through all data
for (var i in data) {
// convert the input into jQuery object
var row = $('<div>' + data[i][checkboxColumn] + '</div>');
// Check the boxes as needed
row.children('input').attr('checked', (checktoggle) ? 'checked' : false);
// update the data in datatables
oTable.fnUpdate(row.html(), parseInt(i, 10), checktoggle, false, false);
}
// redraw the datatable
oTable.fnDraw();
}
You can refer below links and that will give clear functionality idea how to implement
http://datatables.net/examples/api/form.html

jquery trigger click in a loop

Hi I am trying to append facebook friends thumbnail in list item and add trigger on each of them. but now it trigger the click but it's only getting fbid of the last appended item inside the click callback. How can I attach click event on each of them correctly?
for(var i=0;i<obj.photo.length;i++) {
var img=$('<img src="https://graph.facebook.com/'+obj.photo[i]['fb_id']+'/picture" />');
var anchor=$('');
var li = $('<li></li>');
var fbul = $('#fb_friends');
anchor.append(img);
li.append(anchor);
fbul.append(li);
anchor.click(function(){
alert(anchor.attr('id'));
});
}
the problem is because, you are using a closure variable anchor inside your callback function for click event. The solution to this problem is to fetch the clicked element from the event properties as given below. Inside the event handler method this points to the element to which the handler is registered to.
anchor.click(function() {
var $this = $(this);
alert($this.attr('id'));
});
But since you are working with dynamic element I recommend using event delegation with .on()
var fbul = $('#fb_friends');
fbul.on('click', 'a', function() {
var $this = $(this);
alert($this.attr('id'));
})
for (var i = 0; i < obj.photo.length; i++) {
var img = $('<img src="https://graph.facebook.com/' + obj.photo[i]['fb_id']
+ '/picture" />');
var anchor = $('');
var li = $('<li></li>');
anchor.append(img);
li.append(anchor);
fbul.append(li);
}

Dynamically created form elements value not getting in $_POST in php

I have created some dynamic text boxes and values according to the no. of cart items selected by a user. The no. of cart items are stored in a cookie and I am trying to do the following:
1) Get the no. of cart items from the cookie named cartcounter
2) Create 'cartcounter' no of text boxes with name itemkey_skey where itemkey is the hash key of each items in user cart.
3) Submit the form
4) Get the keys of the selected items in php
Now I can create cartcounter, the number of text boxes with different values.
But the problem is that I can get only the first text box value in $_POST in PHP. I would like to get all the values of the dynamically created form elements.
Code:
$(document).ready(function() {
if (getCookie("cartcounter") != 0) {
$("#counter").val(getCookie("cartcounter"));
for (var i = 1; i <= cartcounter; i++) {
var ckey = getCookie(i + "_skey");
var element = document.createElement("input");
alert("Element=" + element);
element.setAttribute("type", "text");
element.setAttribute("value", ckey);
element.setAttribute("name", "skey_" + ckey);
var foo = document.getElementById("itmbox");
foo.appendChild(element);
$("#frm").submit();
}
}
else {
alert('Your cart is empty , please choose your product');
window.location = "http://synergiadigital.com/restaurant2/orderFood.php/"
}
});​
I have solved it. The problem was that I was calling the submit function inside the loop. I have solved it by doing:
$(document).ready(function() {
if (getCookie("cartcounter") != 0) {
$("#counter").val(getCookie("cartcounter"));
for (var i = 1; i <= cartcounter; i++) {
var ckey = getCookie(i + "_skey");
var element = document.createElement("input");
alert("Element=" + element);
element.setAttribute("type", "text");
element.setAttribute("value", ckey);
element.setAttribute("name", "skey_" + ckey);
var foo = document.getElementById("itmbox");
foo.appendChild(element);
}
$("#frm").submit();
}
else {
alert('Your cart is empty , please choose your product');
window.location = "http://synergiadigital.com/restaurant2/orderFood.php/"
}
});​

How to reload a page with combobox (select) value?

I have a combobox - combo1. Everytime a change the combobox value, I should have a button that submits that value and reloads the page. I want to start at mysite/value?v=1 and end with mysite/value?v=2. This is what I have so far:
Javascript:
function nav() {
var selObj = document.getElementById("combo1");
valor = selObj.options[selObj.selectedIndex].value;
// reload the page
}
HTML:
<input type="button" onclick="nav()" value="Ok" />
You are looking for window.location:
function nav(){
var selObj = document.getElementById("combo1");
valor = selObj.options[selObj.selectedIndex].value;
window.location = 'mysite/value?v=' + valor;
}

Categories