html
<input id="1" name="myText" type="text" value="20"/>
<input id="2" name="myText" type="text" value="30"/>
<input id="3" name="myText" type="text" value="40"/>
How can I get id value by index using name?
The following code snippet is not working
var getVal = $('[name="myText"]').index(1);
jQuery holds the DOM elements in the set like an array so you can use the indexes operator([]) to get the element, or get the jQuery object that wraps the desired element with :eq(n) `.eq(n)`
$('input[name="myText"]:eq(1)').attr('id')
You should mention what to you consider to be index(1) the first or the second:
$('input[name="myText"]:eq(0)').attr('id') // First
$('input[name="myText"]:eq(1)').attr('id') // Second
Or:
$('input[name="myText"]')[0].id // First
If you want the first value, you can filter and use the attr method to get the value of the id attribute.
var getVal = $('[name="myText"]:first').attr('id'); // first id
If you want some other element, you can use eq and choose the zero-based element in the collection.
var getVal = $('[name="myText"]:eq(1)').attr('id'); // second id
My answer refers to accessing elements in the jQuery result object by index. You can use selectors such as :eq indicated in other answers.
However, you can use .get(1) instead of your index.
var id = $('[name="myText"]').get(1).id;
Is equivalent to
var id = $('[name="myText"]:eq(1)').attr('id');
Example: http://jsfiddle.net/HackedByChinese/UmKw6/1/
The second method is the preferred route, since it means you never leave the jQuery result object and thus can chain other jQuery calls in one statement.
var id = $('[name="myText"]:eq(1)').css('color', 'red').attr('id'); // example of chaining jQuery methods. sets the text color to red and then returns the id.
Related
I need to skip this querySelector('input') because in certain instances the input will come second instead of first. Is there a way to label an element in HTML as 'skip this'?
You're free to utilize the full power of CSS syntax there. In your example if you only want to get input if it's the first parent's element then query like this:
querySelector('input:first-child');
Or if you want to get precise use :nth-child selector, or even better, :nth-of-type:
querySelector('input:nth-of-type(1)');
But the best solution would be to mark your input with a class or id and use it instead:
querySelector('.myInput');
You can of course combine it with negation selector:
querySelector('.myInput:not(':nth-child(2)')');
querySelector returns the first Element that matches the selector provided in the method. And why wouldn't it? That's what it's supposed to do.
A.E. the below returns the first input tag it can find on the document from the top-down.
document.querySelector("input");
It will always return the first input tag it can find. You have two options to "skip" the node. You can either write a function to recursively check if the input should be skipped( kind of superfluous and bad looking ) or you can simply be more specific with your selector.
Either way you need to give the input element you want to skip some sort of recognizable trait. That can be a name property or a dataset property or a class or an id - anything that you can programatically check for.
//functional example
function ignoreSkippable() {
let ele, eles = Array.from(document.querySelectorAll("input"));
eles.some(elem => !elem.matches('.skippable') ? ele = elem : false);
return ele;
}
console.log( ignoreSkippable() );
// <input value="second input"></input>
//specific selector example
let ele = document.querySelector("input:not(.skippable)");
console.log(ele); // <input value="second input"></input>
<input class="skippable" />
<input value="second input" />
I have a table of elements like this:
<tr id="elementId">
<img name="img" src=""/><br/>
<input name="text" type="text"/><br/>
<input name="button" type="button"/><br/>
</tr>
Each element is exactly the same, except of its id.
I try to update the elements with javascript, but I have no clue how to get the child nodes by their name.
My code:
//get element
var element = list.rows[i];
//update nodes
element.getElementByName("img")[0].src = someImg;
element.getElementByName("text")[0].value = someText;
element.getElementByName("button")[0].value = someOtherText;
The code doesn't work, because element has no function getElementByName.
Is there any other way to get the nodes by their name?
element.querySelector('[name="thename"]') or element.querySelectorAll('[name=2thename"]')
The function is getElementsByName. Elements is plural.
Note that it returns an array-like HTML Collection, so you'll need to grab the first item off it too (with [0]).
Additionally, you might find that your elements aren't actually in your table row as you are missing table cells. Validate your markup: http://validator.w3.org/nu/
In order to select all alements with a tagname in the whole document you may use
listElements = document.getElementsByTagName();
Inside a certain element, you may use
selectedElement = element.getElementsByTagName();
Notice this functions returns an array with the elements selected. If there is only one element, it will be in
listElements[0]
in the first case, or
selectedElement[0]
in the second.
How to get element id using alias attribute in Mootools
<input type="text" alias="school_name" value="" id="test_school" name="test_school">
You can use the $$ function to return an element based on a css selector. You can use the css attribute selector syntax to retrieve elements based on an attribute.
// Returns all inputs with an alias of school_name
var els = $$('input[alias=school_name]');
This will return an array of elements.
You can then do els[0].id to retrieve the id of the first element (or loop through the elements as you see fit)
There are many input elements which IDs are
question5,question6, question7
,..., how to select these input elements using Jquery?
I do not mean $('#question5'), I mean to select the group of them.
Also How to get the the last number like 5,6,7,... using Jquery?
You can select all the input elements whose its id starts with 'question', and then you can extract the number, eg.:
$('input[id^=question]').blur(function () {
var number = +this.id.match(/\d+/)[0];
});
Just be careful because if the regular expression doesn't matchs, it will throw a TypeError, a safer version would be something like this:
$('input[id^=question]').blur(function () {
var match = this.id.match(/\d+/);
var number = match ? +match[0] : 0; // default zero
});
Try this:
$("input[id^='question']")
It will match input elements that have an id attribute that begin with question.
Once you have the elements, you can simply do a javascript substring on them to find the number:
$("input[id^='question']").each(function() {
alert(this.id.substr(8));
});
The easiest solution is probably to give the elements a common class that you can select:
<input id="question5" class="questions">
<input id="question6" class="questions">
<input id="question7" class="questions">
You cane then select all of them with $(".questions") and you can get their id:s with the jQuery .attr() function.
add a class to each input field.
<input class='questions'>
$('.questions')
using the select method on the class will do the trick
depending on what you are trying to do, using the jQuery selector for the class you can add a .each to iterate through the array, like so.
$('.questions').each(function (i){
//i = the current question number
alert('this is question '+i);
});
Also, here is further documentation on the .each method in jQuery
i have 3 hidden fields in 1 div. when I have reference to this div, how to get 1 of the hidden fields in this div.
This will also work (jQuery):
$('#my_div').find('input[type=hidden]:first')
Assuming you have a DIV, like so:
<div id="mydiv">
<input type="hidden">
<input type="hidden">
<input type="hidden">
</div>
You can use jQuery to do something like this to select all of them:
$('input:hidden','#mydiv');
With that selector, now you have all 3 hidden fields in a jQuery collection. You can pick and choose from there which one you want to use by using several methods:
$('input:hidden:first','#mydiv'); // get first one using first
$('input:hidden:last','#mydiv'); // get last one using last
$('input:hidden','#mydiv').eq(0); // get first one using eq
$('input:hidden','#mydiv').eq(1); // get second one using eq
$('input:hidden','#mydiv').eq(2); // get third one using eq
$('input:hidden:eq(0)','#mydiv'); // get first one using eq in selector
The options are:
first - get the first matched element in the collection.
last - get the last matched element in the collection.
eq(N) - get the Nth matched element, 0 based.
:eq(N) - get the Nth matched element, 0 based, inside the selector string.
I am personally a fan of option 3 as I don't like having too much crap in my selector.
One caveat of the above is that by using the :hidden selector we might match other input elements that are hidden (ie, not visible). If you expect that to happen, or even if you don't, you could do this:
$('input[type=hidden]', '#mydiv').eq(0);
Without any code it's hard to help but i'd say give the hidden field an ID and use:
var hdn = document.getElementById("id");
Or if you're using Jquery use:
var hdn = $("#id");
if it's like this:
<div id="somediv">
<input type="hidden"/>
<input type="hidden"/>
<input type="hidden"/>
</div>
and you're using jquery, you can just write this:
$("#somediv > input[type='hidden']:eq(1)")
and it should return a reference to the 1st hidden field. if you want the 2nd, use "eq(2)" and so forth.
var firstHidden = $("input[type='hidden']:first", ref);
:first pseudo-class and attribute selector
or
var firstHidden = $("input:hidden:first", ref);
:hidden pseudo-class (be careful, because :hidden finds also elements with style="display: none")
or
var firstHidden = $("input[type='hidden']", ref).eq(0);
.eq()
where 'ref' variable is a reference to the DIV element
I would assign a class to the hidden you want to find - a little easier on the programmer looking back on it in 4 years. I'm using "id" as an example of the hidden. Once you find it with jQuery - you can use .val() to get its value.
HTML:
<div id="mydiv">
<input type='hidden' name='mydiv_id' class='idField' value='test1' />
<input type='hidden' name='mydiv_hidden2' class='option2' value='test2' />
<input type='hidden' name='mydiv_hidden3' class='option3' value='test3' />
</div>
jQuery:
//execute on document ready:
$(function() {
var div = $('#mydiv'); //some jquery/dom element "div"
// use the jQuery selector with "div" as our context.
var $hidden = $('input.idField', div);
alert($hidden.val()); // should alert 'test1'
});
For a reference, if you're not using jQuery like the original poster and assuming the structure above:
<div id="mydiv">
<input type="hidden">
<input type="hidden">
<input type="hidden">
</div>
var div = document.getElementById('mydiv');
var inputs = div.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
// Match your input with inputs[i].name, etc.
}