I have an input tag that is being included by a javascript. The resulting input tag looks like this:
<input class="mylivechat_prechat_name_box mylivechat_prechat_box" type="text">
Is there any way that I can add a variable to the end of the value of the input tag?
I've tried using the javascript to set the form field:
var myClassName = document.getElementsByClassName('mylivechat_prechat_name_box mylivechat_prechat_box');
i = myClassName.length;
myClassName[i].value = "TheseAreMyChanges";
However, I get the error
Uncaught TypeError: Cannot set property 'value' of undefined
Array's are zero based, so if you read the length and use that index it is one more than the highest element. Trying to read an element outside the bounds of the array will return undefined - so use length-1:
var myClassName = document.getElementsByClassName('mylivechat_prechat_name_box mylivechat_prechat_box');
var i = myClassName.length;
myClassName[i-1].value = "TheseAreMyChanges";
In your code myClassName[i] will be undefined, since i holds the length and maximum index value will be length - 1. And string can be append at the end by += which results concatenated value.
var myClassName = document.getElementsByClassName('mylivechat_prechat_name_box mylivechat_prechat_box');
myClassName[0].value += "TheseAreMyChanges";
If you want to update the last element then get element by index length -1
var myClassName = document.getElementsByClassName('mylivechat_prechat_name_box mylivechat_prechat_box');
myClassName[myClassName.length - 1].value += "TheseAreMyChanges";
You could use querySelector :
document.querySelector('.mylivechat_prechat_name_box.mylivechat_prechat_box').value+='NEW';
Add :last-child in the end of the selector if you want to get the last element :
document.querySelector('.mylivechat_prechat_name_box.mylivechat_prechat_box:last-child');
Hope this helps.
var elem = document.querySelector('.mylivechat_prechat_name_box.mylivechat_prechat_box');
elem.value += ' NEW';
<input class="mylivechat_prechat_name_box mylivechat_prechat_box" type="text" value='OLD'/>
Related
You can easily retrieve the tag name of an element using the nodeName, like this:
var atnode = document.getElementById("link-test");
alert(atnode.nodeName);
link
But how do I use the nodeName to get the attribute of the element instead?
Using the getAttribute() does not do what I want, because you have to insert the name of the attribute first, and then it just gives you back the value of the attribute. I want to get the name of the attribute just like I did with nodeName. I know nodeName can be used with attribute nodes too, but how?
const atnode = document.getElementById("link-test");
const nodes=[];
const values=[];
for (let att, i = 0, atts = atnode.attributes, n = atts.length; i < n; i++){
att = atts[i];
nodes.push(att.nodeName);
values.push(att.nodeValue);
console.log(att.nodeName + " - " + att.nodeValue);
}
link
After using attributes method you can use nodeName to get the attribute name and nodeValue to get the value of the attribute.
After pushing it to array you can get attribute and value of it using same index in both arrays.
You can get a list of the attributes with getAttributeNames() on the node. In your example, you could do like so:
atnode.getAttributeNames() This will return ["href", "id"].
Then you can loop through the list with getAttribute(<item from list as string>) to get the values of the element's attributes.
If I understood right, you just need to use the getAttributeNames method.
Follows an example:
const exampleElement = document.getElementsByTagName("example")[0];
console.log(exampleElement.getAttributeNames());
<example name="one" last="two"></example>
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));
}
Sorry to bother you with this but this is bothering me: I have the following vars:
var one = 1;
var two = 2;
var tre = 3;
I also have a input box
<input type='text' id='one' class='some'>
and I want a variable that contains the corresponding value from the variables above, based on the input box's id.
var atr = $(".some").attr("id");
var nr = ???
I want var nr to be equal to 1 (as the variable one above)
Use the following notations:
$('selector[attr]') // elements that has attribute attr
$('selector[attr=value]') // elements that has attribute attr with value `value`
$('selector[attr^=value]') // elements that has attribute attr starting with value `value`
$('selector[attr$=value]') // --~-- ending with `value`
$('selector[attr!=value]') // not equal `value`
$('selector[attr*=value]') // attribute contains `value`
$('selector[attr|=value]') // attribute has prefix `value`
$('selector[attr~=value]') // attribute contain word delimited by spaces
See complete list of jquery attribute selectors
EDIT:
There can be another thing you are asking about:
You have particular map of values and want to do this:
var map = { one: 1, two : 2 , three: 3 } ,
elem = $('.some'),
attr = elem.attr('id'),
nr = map[attr] // === 1
You can only use dynamically generated variable names for matching against object properties:
var ids = { one : 1, two : 2, tre : 3 };
var atr = $(".some").attr("id");
var nr = ids[atr]; // now contains 1
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('|');
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);