how to get 1 hidden field among several within div - javascript

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.
}

Related

for each element javascript remove parent div and replace with own div

I'm trying to remove the parent div's for each input class with javascript and replace them with my own classes. However the id's of the input fields are always random. Here's my code:
<script type="text/javascript">
var filter = document.getElementsByName('filter[]');
function show() {
for (var i = 0; i < filter.length; i++) {
alert(filter[i].value)
}
}
//The .sidebar-filter-item, should not be hardcoded
//because that name can differ always.
$("<h2> test </h2>").insertBefore(".sidebar-filter-item ");
Here is how my input fields look like:
<div class="random1293">
<input id="filter_16" type="checkbox" name="filter[]" value="16">
</div>
<div class="random2423">
<input id="filter_17" type="checkbox" name="filter[]" value="17">
</div>
Even though you have not tagged this post as Jquery but still used jquery in your code in the OP, I conclude that Jquery solution is acceptable.
Select all the input elements which start with the id filter_ and then change the class of the parent div to what ever you want.
$('input[id^="filter_"]').each(function(){
$(this).parent().attr('class','yourOwnClassHere');
});
Once selected you can select a DOM elements parent element using:
element.parentElement
Regarding selecting the elements if the id attributes are going to be random/unpredictable you could instead use:
document.getElementsByTagName("input");
Which will give you an array of all your input elements which you can then loop through to perform your operation to each.
Alternatively you could give each of the elements you want selected a class (if you don't want all inputs on the page) an use:
document.getElementsByClassName("className");
which will also return an array which you can handle in the same fashion.

jquery catch previous class issue

My html is
<input type="text" class='myclass' value="start">
<div>
<input type="text" class='myclass' value="sea">
</div>
<button class="mybutton">Catch</button>
<br/>
<input type="text" value="end" class='myclass'>
and javascript is
$('.mybutton').click(function(){
var text = $(this).prev('.myclass').val();
console.log(text);
});
I want to get the value of immediate previous input value by class name. but the result is undefined.I want to get the value sea. Where is the problem? the working fiddle link is Here >> Thank you.
Immediate previous element of catch button is a div, so you need to do a find() inside that
like this:
$('.mybutton').click(function(){
var text = $(this).prev('div').find('.myclass').val();
console.log(text);
});
I want to get the value of immediate previous input
Well, that's the problem, input is not immediate. you can use prevAll method instead:
$('.mybutton').click(function(){
var text = $(this).prevAll('.myclass').val();
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class='myclass' value="start">
<div>
<input type="text" class='myclass' value="sea">
</div>
<button class="mybutton">Catch</button>
<br/>
<input type="text" value="end" class='myclass'>
Interesting. I have never used the ".prev()" function before. Anyways:
If you read here https://api.jquery.com/prev/ you will find:
"Given a jQuery object that represents a set of DOM elements, the .prev() method searches for the predecessor of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements."
Also:
If no previous sibling exists, or if the previous sibling element does not match a supplied selector, an empty jQuery object is returned.
So in other words, as has been mentioned before, the ".prev()" simply looks for the previous element.
To do what you want to do in the way you want to do it you might want to consider the ".prevAll()" function that is explained here: https://api.jquery.com/prevAll/
But then again since the element you want is actually a child of the previous element and not a direct sibling you might want to consider Beginners' suggestion:
$('.mybutton').click(function(){
var text = $(this).prev('div').find('.myclass').val();
console.log(text);
});
But in fact you should be able to make it slightly simpler by removing the 'div' selector:
$('.mybutton').click(function(){
var text = $(this).prev().find('.myclass').val();
console.log(text);
});
As long as you are certain that your '.myclass' element will be a child of the previous element this should work irregardless of what the parent element is (div, span, whatever)

Get nested element by name

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 access a hidden input with javascript

What I am attempting to do is is access hidden object in a div. What happends is a user will click on button that will then perform some task such as delete a user. This may be easier if I show what I have.
<div class="mgLine">
<input type="hidden" name="tenentID" value="1">
<p class="mgName">James Gear</p>
<input type="text" class="mgBill" value="" placeholder="Post Bill Link Here">
Submit Bill
Not Paid
Change Password
Delete User
</div>
What I want the system to do is alert the value of one which it gets from the hidden field when the "submit bill" is pressed.
function alertTest(e){
//e.parentNode
window.alert(e.parentNode.getElementsByTagName("tenentID")[0]);
}
I am attempting to use JavaScript DOM to access the element. I hope this made at least some sense. There will be many of these entries on the page.
You need to use getElementsByName instead of getElementsByTagName
function alertTest(e){
//e.parentNode
window.alert(document.getElementsByName("tenentID")[0]);
}
getElementsByTagName is for selecting elements based on its tag say div, input etc..
getElementsByName
getElementsByTagName
Realizing that you might have multiple div section and your hidden input is the first child you could use these:-
e.parentNode.getElementsByTagName("input")[0].value;
or
e.parentNode.firstElementChild.value;
if it is not the firstCHild and you know the position then you could use
e.parentNode.children(n).value; //n is zero indexed here
Fiddle
The modern method would be to use querySelector.
e.parentNode.querySelector("[name=tenentID]");
http://jsfiddle.net/ExplosionPIlls/zU2Gh/
However you could also do it with some more manual DOM parsing:
var nodes = e.parentNode.getElementsByTagName("input"), x;
for (x = 0; x < nodes.length; x++) {
if (nodes[x].name === "tenentID") {
console.log(nodes[x]);
}
}
http://jsfiddle.net/ExplosionPIlls/zU2Gh/1/
Try this:
function alertTest(e){
alert(e.parentNode.getElementsByName("tenentID")[0].value);
}
I usually set an id attribute on the hidden element, then use getElementById.
<input type="hidden" id="tenentID" name="tenentID" value="1">
then I can use...
var tenentValue = document.getElementById("tenentID").value;
In general, your best bet for accessing a specific element is to give it an ID and then use getElementById().
function alertTest(ID){
alert(document.getElementById(ID).value);
}
Names can be duplicated on a page, but the ids have to be unique.

get id value by index using name jquery

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.

Categories