Unique NAME to clone() elements - javascript

How do I give an unique NAME or other ATTR to a element that is cloned?
Thank you in advance.

Use Math.random:
$('.some_element').each(function() {
var id = (Math.floor(Math.random()*10000000000000000));
$(this).clone().attr('id', id);
});
Or, if you'd like a "handle" on the original element, you could create a new id in this format:
ORIGINAL_ELEMENT_ID + SEPARATOR + RANDOM_NUMBER
E.g.,
$('.some_element').each(function() {
var id = [
this.id,
(Math.floor(Math.random()*10000000000000000))
].join('-');
$(this).clone().attr('id', id);
});

A hack-ish way to do this would be to use a global counter and keep incrementing it by One before adding the value to the name of the cloned element.
ex.
var count =1;
func some_func() {
var cloneElement = $(form).clone();
cloneElement.attr('name', cloneElement.attr('name') + count++);
}

$('.some_element').clone().attr('id','some_unique_id');

Related

each() with counter - const names

I am trying to loop through some HTML elements, extract the content and set them as a const value with the index number like this...
jQuery('.myitems').each(function (index) {
const myitem + index = [jQuery(this).text()];
console.log(myitem + index);
});
This is not working, can anyone tell me the correct way to achieve?
You can use object instead of count. And your code will be broken.
See the following solution.
jQuery('.myitems').each(function (index) {
const count = {}
count[myitem + index] = [jQuery(this).text()];
console.log(count[myitem + index]);
});
Shouldnt you store the values in an array instead?
const myitem = [];
jQuery('.myitems').each(function (index) {
myitem[index] = jQuery(this).text();
console.log(myitem[index]);
});
You cannot do what you're attempting in JS. An alternative would be to populate an array with the values by using map():
var arr = $('.myitems').map(function() {
return $(this).text();
}).get();
If you still want to use the 'myitem' + index prefix on the values then you could instead use an object:
var obj = {};
$('.myitems').each(function(i) {
obj['myitem' + i] = $(this).text();
});
Here, I have first set constant and then on looping I have set value with index number. Currenlty , I have made output on console. You can check it. Let me know if you do not understand
const staff=[];
$('.staff').each(function(index){
staff[index]=$(this).text();
})
console.log(staff);

How to get value from text box by name which is dynamic

I need a value of text box for that I am using document.getElementsByName("elemntName") but the problem is the the name itself is dynamic, something like below.
for(temp = 0 ; temp < arracid.length ; temp++){
cell1=mynewrow.insertCell(4);
cell1.innerHTML="<input type='hidden' name='ACID"+index+"' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
index++;
}
When I tried var acidCount = document.getElementsByName('ACID') its not working and I tried
var acidCount = document.getElementsByName('ACID"+index+"') still not working
For every loop the name is changing like ACID1,ACID2 etc.. can anyone help me how to get the value of this text box?
Since you are already assigning an ID to your inputs, it's recommended to use getElementsById which is faster than getElementsByName (and more accurate because the IDs are supposed to be unique, while the names don't have to be). Try this:
var acidCount = document.getElementById("ACID" + index);
If you still want to use getElementsByName, try this:
var acidCount = document.getElementsByName("ACID" + index);
But remember that getElementsByName returns a list of elements, but the list has only one element, because your names are unique. If you want to get that element in the list, you can use it's index like this:
var acidCount = document.getElementsByName("ACID" + index)[0];
Alternatively, if you want to get the list of all your inputs, first remove the index from the name:
cell1.innerHTML="<input type='hidden' name='ACID' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
Then use:
var acidCount = document.getElementsByName("ACID");
Note: all the above return the DOM element(s). If you're only interested in the value, use the value property:
var acidCount = document.getElementById("ACID" + index).value;
or
var acidCount = document.getElementsByName("ACID" + index)[0].value;
(This is a jquery solution, since the question was initially tagged with jQuery)
You can use the selector of input elements with name starting with ^= ACID:
$("input[name^=ACID]").each(function(){
console.log($(this).val());
});
Issue is with single quoutes and double quotes :
var acidCount = document.getElementsByName("ACID"+index)
Since there can be more than one element with same name, so we need to get first element with that name, I have corrected your query check this, it will work.
var acidCount = document.getElementsByName('ACID'+index)[0].value
Try using wildcard * in the selector which will return all matched elements
document.querySelectorAll('[id*=ACID]')
You can try using class name.
$(document).find(".tblrows").each(function(){
console.log($(this).val());
});
Since you are naming your elements 'ACID' + index, you can utilize the querySelector method as follows:
for (var i=0; i < arracid.length; i++) {
var $el = document.querySelector('#ACID' + i));
}

Javascript: string regex

I am calling a function getParentElm(idStr,element) which accepts an id and an element, and searches up the html tree until it finds a parent element which has an id equal to idStr.
Calling code:
var s = "someId";
var el = getParentElm(s,element);
I would like the idStr parameter to work with strings that match to "someId", for eg "someId123".
I tried :
var s = "/someId/";
but it did not work. Ideally, i do not want to touch the getParentElm function.
Update: Thanks vbranden.
I tried: var s = /someId/ and that worked. I upvoted your comment. Thanks all :)
no regex needed.
use closest to traverse up the dom, and id* to match id's which contains your idStr.
function getParentElm(idStr,element){
return $(element).closest('[id*="' + idStr + '"]');
}
Here, this should work :
function getParentElm(idStr,element) {
var patt = new RegExp(idStr +".*");
while(element.parentNode)
{
if(patt.test(element.parentNode.id))
return element.parentNode;
element=element.parentNode;
}
return false;
}
And just call the function in this way :
var el = getParentElm("someId",document.getElementById('foo'));

How to automatically generate input-array index in jQuery?

For example, I have such HTML:
<input name="someinput[]">
I made a function to clone/remove this input but now I want to assign indexes to name dynamically - when I make an element clones, its new names should be someinput[1], someinput[2] etc. - how to make this?
You could just replace [] with [index] using the attr callback:
var i = 0;
$('button').click(function(){
$('input:first').clone().attr('name',function(a,e){
i++;
return e.replace("[]","["+i+"]");
}).insertAfter($('input:last'));
});
example: http://jsfiddle.net/niklasvh/c9G7c/
Keep the index of the next input in a global variable, and then use that in your cloning function. Is that what you do?
var source = $('#source')
var copy = source.clone().attr('name', 'some[' + index + ']')
$('body').append(copy);

How to identify the chosen selector in jQuery?

$('#select_id1, #select_id2, #select_id3').change(function() {
// If '#select_id1' has changed, 'str' should be equal to 'select_id1'.
// If '#select_id2' has changed, 'str' should be equal to 'select_id2'.
// If '#select_id3' has changed, 'str' should be equal to 'select_id3'.
str = <what should be here ?>
});
You can get the id of the element that invoked the change by this.id.
$('#select_id1, #select_id2, #select_id3').change(function() {
str = this.id;
});
Or (less efficiently):
$('#select_id1, #select_id2, #select_id3').change(function() {
str = $(this).attr("id");
});
But basically this is set to the element on which the event took place.
For the more general case, where not only IDs are used, as suggested by #Anurag, you can do the following:
// Save the selector
var selector = ".someClass, #someId, tr.someTrClass";
$(selector).change(function () {
var selectors = selector.split(","),
matching = []; // Remember that each element can
// match more than one selector
for (var i = 0, s; s = selectors[i]; i++) {
if ($(this).is(s)) matching.push(s);
}
str = matching.join(","); // Your list of all matching selectors
});
You can either look at this.id directly or indirectly via a passed in event object:
$('#select_id1, #select_id2, #select_id3').change(function (e) {
alert(e.target.id + ' == ' + this.id + ' ... ' + (e.target.id == this.id));
});
Most people just look at this but there are times when you might be interested in more than just the target of your event.

Categories