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);
Related
I'd like to create a const variable that is equal to the number of checked checkboxes with a certain class. This is my code to do that(which is not working):
const blocksUserAddLineCBs = $(".useradd"+blockIdEnding);
const blocksUserAddLinesActiveCBCounter = blocksUserAddLineCBs.reduce((currentTotal, item) => {
return $(item).prop('checked') === true + currentTotal;
}, 0);
Is the reduce method not working with a Field created with a jQuery Selector? How could i that without having to create a let Variable and a $().each Loop which increases the variable every time it recognizes one of the elements is checked ($(this).prop('checked'))
.reduce doesn't work on jQuery objects, and in any event it's overkill:
const count = $('.useradd' + blockIdEnding + ':checked').length;
or alternatively:
const $els = $('.useradd' + blockIdEnding);
const count = $els.filter(':checked').length;
(variables renamed to prevent window overflow)
reduce is a method found on arrays.
A jQuery object is not an array.
You can get an array from a jQuery object using its toArray method.
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));
}
So I save my array as a variable: var arrayContents = contentData;
and my array: ['content_1', 'content_2', 'content_3', 'content_4']
So i've got my array, I then want to place it into my HTML which i've done via using text like such: $('.container').text(arrayContents);
I need to break my text up so it currently looks like:
And i'm trying to get it to look like :
How can I break my array up so each item drops onto a new line? As when I use .text I print the whole array as one not each separate item.
Use a foreach loop and add a <br> tag to go to next line:
var contentToInsert;
$.each(arrayContents,function(value){
contentToInsert += value + "<br>";
});
$('.container').html(arrayContents);
You need to use html() instead of text(), check this
var htm = '';
var arrayContents = ['content_1','content_2','content_3'];
arrayContents.forEach(function(item){
htm += item + '<br />'; // break after each item
});
$('.container').html(htm);
Actually .text() works with a string value. You passed an array, which leads the "engine" to call arrayContents.toString() to get a string from the array. As you can see there, this function separates each entry by a comma.
If you want to produce an output on one column, you have to generate HTML (as shown in this answer), or editing the div object through javascript DOM functions (fiddle) :
for (var i = 0; i < arrayContents.length; i++) {
var currentElement = document.createElement("DIV"); // "DIV" or block-type element
var currentText = document.createTextNode(arrayContents[i]);
currentElement.appendChild(currentText);
document.getElementById("container").appendChild(currentElement);
}
Be sure of what kind of HTML you want to produce.
I have a question regarding Javascript array.
I have the following javascript array:
var startTimeList= new Array();
I've put some values in it. Now I have the following input (hidden type):
<input type="hidden" value"startTimeList[0]" name="startTime1" />
Hoewever, this is obviously not correct because the javascript array is not recognized in the input hidden type. So I cant even get one value.
Does anyone know how I can get a value in the input type from a javascript array?
You need to set the value in Javascript:
document.getElementById(...).value = startTimeList[0];
Use this :
<script>
window.onload = function() {
document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>
You have to set value from javascript.
Something like document.getElementById (ID).value = startTimeList[0];
You execute javascript from body oload event.
You need to set the value through JavaScript itself so.
document.getElementById("startTime1").value = startTimeList[0];
Or JQuery
$("#startTime1").val(startTimeList[0]);
Assign "startTime1" as the id above.
You can find your element by name with:
document.getElementsByName(name)[index].value = 'new value';
OR
You should identify your element and then change the value;
Give your element an ID for example id="ex"
Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
Change the value with element.value = 'your value';
You'd need to split the array into a delimited string and then assign that string to the value of the hidden input.
Then, on postback or similar events you'd want to parse the value back into an array for use in JavaScript:
var startTimeList = [1,2,3,4,5];
var splitList = '';
for(var i = 0; i < startTimeList.length; i++)
{
splitList += startTimeList[i] + '|';
}
and back again:
var splitList = '2|4|6|8|';
var startTimeList = splitList.split('|');
I have a javascript that has custom indexes, I created them like so:
var rand = event.timeStamp; //jquery on click event object
freeze_array[rand] = month + ',' + model_name + ',' + activity;
To remove the above element I have this:
freeze_array.splice(rand, 1);
But this does not remove the element as I can see it in my firebug dom object viewer. Here is an example of the array:
My indexes are in the form: 1283519490632 - too long to be an integer that is required by the splice method?
Thanks all for any help
As you mentioned, the index argument must be an integer. Maybe you can use an object that holds indices as follows:
var lastIndex=0; // that shall be global...
var pointer = {};
....
pointer[rand] = lastIndex;
++lastIndex;
Then use it as follows:
freeze_array = freeze_array.splice(pointer[rand], 1);
Yes the index must be an integer. Your value is too large for a integer.
See at w3schools
index: Required. An integer that
specifies at what position to
add/remove elements
Try this:
delete freeze_array[ rand ];