Why do I get `undefined` when using `document.getElementsByClassName(...).value`? - javascript

Why do I get undefined as result of console.log(tes_val)? How can I fix it?
var tes = document.getElementsByClassName('a_b_1');
var tes_val = tes.value;
console.log(tes_val);
<input type="hidden" class="a_b_1" name="c_d_1" value="1|2|3">
Thank you.

getElementsByClassName returns an HTMLCollection, so in order to access first found element in this collection you need to use [0] index:
var tes_val = tes[0].value;
However, this is clumsy way to use API. If you are only interested in the first element with class a_b_1 use Document.querySelector method:
var tes = document.querySelector('.a_b_1');
var tes_val = tes.value;
console.log(tes_val);

getElementsByClassName(...) returns a list of elements. Note the plural s in the name of the method! Use getElementsByClassName(...)[0] to access the first element in the list.
var tes = document.getElementsByClassName('a_b_1')[0]
var tes_val = tes.value
console.log(tes_val) //=> "1|2|3"
<input type="hidden" class="a_b_1" name="c_d_1" value="1|2|3">

document.getElementsByClassName array-like object of all child elements.
So you have to select the specific element by passing the index
var tes = document.getElementsByClassName('a_b_1');
var tes_val = tes[0].value;
console.log(tes_val);
DEMO

var tes = $('.a_b_1');
var tes_val = tes.val();
console.log(tes_val);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="a_b_1" name="c_d_1" value="1|2|3">
Use .val() for jquery

Related

Putting element names in a list "[]" with Javascript

I want to put all input element names of a specific parent to a list with Jquery.
<form id="got">
<input name="jon">
<input name="oberyn">
<input name="tyrion">
</form>
var inputs = ["jon", "oberyn", "tyrion"];
So i can manipulate them with forEach.
How can i do that?
You could use .map method.
var inputs = $('#got').find('input').map(function() {
return $(this).attr('name');
}).get();
Try using arrays - jQuery .each().
Demo Fiddle
var arr = [];
$('#got input').each(function(){
arr.push($(this).prop('name')); //a simple way : arr.push(this.name);
console.log(arr);
});

get id of textarea using type selector didn't work

http://jsfiddle.net/bBgbR/1/
var catId = $("input[type='text']:visible").attr('id');
is my selector correct? I want to get the visible textarea's id.
<textarea type="text" id="text_lp1"></textarea>
you can use like
var catId = $("textarea:visible").attr('id');
catId = catId.replace('text_lp', '');
alert(catId);
Try,
var catId = $("textarea:visible").attr('id');
Please note that the element that you are targeting is textarea but you had written a selector that will select an input element.
Try this :
var catId = $("textarea:visible").attr('id');
You need to use:
var catId = $("textarea:visible").attr('id');
because you've used textarea not input, you also need to remove type="text" from your textarea element
Updated Fiddle
If you want to use it as an input element then your HTML should look like:
<input type="text" id="text_lp1" />
Fiddle Demo
Solution:
var cartIdAttribute = $("textarea:visible").attr('id');
The problem, you search INPUT element, but you need TEXTAREA element.
use:
var catId = $("textarea:visible").attr('id');
Working Demo
You are using input[type='text'] which wrong. use like:
var catId = $("textarea:visible").attr('id');

targetting form elements using array values in javascript

I have a small form in javascript with two Input values with the same class name. I know that you can target them by giving them ids but is there a way to target them using array values?
<td>
<input class="inputtextb" type="text" name="adults" maxlength="3"> Adults
<input class="inputtextb" type="text" name="children" maxlength="3"> Children above 5 years
You can use document.getElementsByClassName() for that:
var inputs = document.getElementsByClassName('inputtextb');
inputs[0] // the first input
inputs[1] // the second input
In case that doesn't work - can i use getElementsByClassName - you could iterate over all <input> elements using document.getElementsByName() and filter out the ones you want; or use jQuery ;-)
Use the following code:
var adults = document. getElementsByClassName('inputtextb')[0].value
var children = document. getElementsByClassName('inputtextb')[1].value
In Firefox 3, you can convert it into an Array and then call forEach on it:
var inputVals = document.getElementsByClassName("inputtextb");
var elsArray = Array.prototype.slice.call(inputVals, 0);
elsArray.forEach(function(el) {
console.log(el.tagName);
});
Note : It does not return an Array, it returns a NodeList objects.

Get values of all textboxes with same name attributes in jquery

I need to get values of all textboxes with same name attributes using jquery.
<input type="text" id="text1" name="text[]">
<input type="text" id="text2" name="text[]">
<input type="text" id="text3" name="text[]">
How can I get all values of textbox text[] and compare it using jquery.
I tried using
var values = $("input[name='text[]']")
.map(function(){return $(this).val();}).get();
but am no successful.
You can use map method and store the values into an array.
$(function(){
var values = $('input[name="text[]"]').map(function(){
return this.value
}).get()
})
http://jsfiddle.net/UugWW/
This one should work :
$('input[name="text[]"]');
You can loop on it to get all values.
$('input[name="text[]"]').each(function() {
alert($(this).val());
});
Let's split the requirement into smaller problems.
First you want to select all those inputs.
var $inputs = $("input[name='text[]']")
It returns a jQuery object, containing all the input named text[].
You also might not need to use square brackets into the name.
var inputs = $inputs.get();
Extract the matching elements into a plain Array, so that we can now access Array's prototype methods, such as Array.prototype.map.
var values = inputs.map(function takeValue(input) {
return input.value;
});
Use a selector like this:
$('input[type="text"][name="text[]"')
var textboxcount = document.getElementsByName("text").length;
var textvalue="";
for (var i = 0; i < textboxcount ; i++) {
textvalue= textvalue + document.getElementsByName("text").item(i).value;
}
alert(textvalue);

How to parse a variable in Javascript

I'm trying to use this code:
var field="myField";
vals[x]=document.myForm.field.value;
In the html code I have
<form name="myForm">
<input type='radio' name='myField' value='123' /> 123
<input type='radio' name='myField' value='xyz' /> xyz
</form>
But this gives me the error:
document.myForm.field is undefined
How can I get field to be treated as a variable rather than a field?
Assuming that your other syntax is correct (I havne't checked), this will do what you want:
var field="myField";
vals[x]=document.myForm[field].value;
In JS, the bracket operator is a get-property-by-name accessor. You can read more about it here.
Use the elements[] collection
document.forms['myForm'].elements[field]
elements collection in DOM spec
BTW. If you have two fields with the same name, to get the value of any field, you have to read from:
var value = document.forms['myForm'].elements[field][index_of_field].value
eg.
var value = document.forms['myForm'].elements[field][0].value
and, if you want to get value of selected radio-button you have to check which one is selected
var e = document.forms['myForm'].elements[field];
var val = e[0].checked ? e[0].value : e[1].checked ? e[1].value : null;
You have to do it like this:
var field = "myField";
vals[x] = document.myForm[field].value;
or even
vals[x] = document.forms.myForm.elements[field].value;
Based on your tags, it seems that you are using jQuery. If so, you can just do this and it will make your life much easier:
var vals = new Array();
$("form[name='myForm'] :radio").each(function() {
vals.push($(this).val());
});
:-D

Categories