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.
Related
I need to use javascript in order to click an element from element collection. As seen the code has C# but also as seen I need to use a javascript command as I do.
I am looking for this javascript code.
This element doesn't have an ID or name. Otherwise, I could have used the ID but that doesn't work in this case. How would it be possible to use the iterating elements in order to click with javascript"?
The problems are:
1. First I need to click this input/textbox to make it possible to edit.
2. Now when the input is editable. I need to put a number value to the textbox.
foreach (Gecko.GeckoHtmlElement elements in wb1.Document.GetElementsByTagName("input"))
{
if (elements != null)
{
if (elements.OuterHtml.Contains("thisstring"))
{
//This element doesn't have an ID or name. "how to use elements in order to click with javascript"?
//1. First I need to click this input/textbox to make it possilbe to edit
//2. Now when the input is editable. I need to put a value to the textbox.
webbrowser.Navigate("javascript:void(document.getElementById('someID').click())");
}
}
}
The HTML surrounding the element I want to click is below. You can see the input there:
<td class="date-cell" cm-inventory-grid-copy-action-focus data-header-date-index="0" data-cm-inventory-grid-copy-action-focus-type='availability' ng-class="{ 'zero': roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].availability <= 0, weekend: headerDates[0].weekend, 'dirty': roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].availabilityChanged, 'copy-focused': roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].copyFocused && roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].copyFocusType == 'availability' }" ng-form="cellForm">
<input name="rtd-availability" type="number" onclick="this.select()" ng-model="roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate].availability" ng-change="handleRoomTypeDateChange(roomTypeDatesByRoomTypeId[roomType.id][headerDates[0].fullDate])" pattern="\d+" ng-disabled="::!allowAvailabilityEdit" required sm-no-scroll cm-inventory-grid-date-cell-validator/>
</td>
To get html element in javascript you can use "document.querySelector('input')" or if there are many input elements you can use "document.querySelectorAll('input')".
querySelector returns HTML node element and querySelectorAll returns array of elements.
By using document.qerySelector you can identify the correct input quite easily since you can use attributes and the html structure as criteria.
//select an input that is a child of a td with class date-cell who's name is rtd-availability
let input = document.querySelector('td.date-cell > input[name=rtd-availability]')
//no need to call .click(), you can use .select() directly
input.select();
input.value = 42;
javascript:(() => {let in = document.querySelector('td.date-cell > input[name=rtd-availability]'; in.select(); in.value = 42;})();
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.
Trying to figure out how to click this button
<input class="button" type="submit" name="checkout" value="Check out">
by using this function
document.getElementBy????('????').click()
or should another function be used?
You can use document.getElementsByName('checkout')[0].click()
You can also use document.getElementsByClassName('button')[0].click()
You can add an id in the input and use dcoument.getElementById or you can use document.getElementsByClassName which'll return you an array.
document.getElementsByClassName('classname')[0].click()
Use this for javascript
document.getElementById("nameofid");
Add an id on your element in the dom and add onclick="(javascript here)" attribute
<input class="button" type="submit" id="nameofid" name="checkout" value="Check out">
Add a function in the javascript to be called by the button using onclick attribute
function myfunction(){
var myvar = document.getElementById("nameofid");
//you may adjust its properties by calling myvar.nameofproperty
//or even call a method myvar.nameofmethod
}
First of all, to be very sure, you should just give your button a unique ID:
<input id="myCheckoutButton" class="button" name="checkout" value="Check out" />
document.getElementById("myCheckoutButton").click();
Basically for your problem and assuming you cannot modify html for some sinister reason...
document.getElementsByName
Would be your choice, howver this works only if you are 100% sure that there is only one element with this name on your document. If its not, it is a little bit tricky but works aswell:
for(var i = 0; i < document.getElementsByName("checkout").length; i++) {
if(document.getElementsByName("checkout")[i].value == "Check out") {
document.getElementsByName("checkout")[i].trigger("click");
}
}
But the very-best option if you are able to implement and use jQuery in your page:
By name:
$(".checkout[name=checkout]").trigger("click");
Or by class and comparing value if you have multiple elements:
$(".checkout").each(function() {
if($(this).val() == "Check out")) {
$(this).trigger("click");
return false;
}
}
There are several. The choice comes down to how specific do you want and/or need to be.
Most specific is getElementById() which will require you to have an id on the element. You can only have one on the page and is very specific.
If you have more than on component on the page and want to attach an event to each one the what you want is to use getElementsByClass() which will return an array of all the elements that have that class.
Finally, if you want to reference form elements you can use the name attribute to manage checkboxes and radio elements. It helps lower the specificity of using a unique id without having to add extra classes to every form element: getElementsByName() which (like getElementsByClass() returns an array of elements. Managing the difference between text inputs and checkbox inputs however is a topic for another question.
is it possible to "override/overwrite" an input element fixed value using javascript and/or jquery?
i.e. if i have an input element like this:
<div id="myDiv">
<input type="text" name="inputs" value="someValue" />
</div>
is it possible to make a jquery object of that element and then change its value to something else then rewrite the jquery object to the dom??
I'm trying but obviously I haven't got good results!
I've been trying something like this:
$('input').val("someOtherDynamicValue");
var x = $('input');
$("#myDiv").html(x);
If you just want to manipulate the value of the input element, use the first line of your code. However it will change the value of every input element on the page, so be more specific using the name or the id of the element.
$('input[name=inputs]').val("someOtherDynamicValue");
Or if the element had an id
$('#someId').val('some Value');
Check out jQuery's selectors (http://api.jquery.com/category/selectors/) to see how to get whatever element you need to manipulate with jQuery.
You can directly access the value via the $.val() method:
$("[name='inputs']").val("Foo"); // sets value to foo
Without needing to re-insert it into the DOM. Note the specificity of my selector [name='inputs'] which is necessary to modify only one input element on the page. If you use your selector input, it will modify all input elements on the page.
Online Demo: http://jsbin.com/imuzo3/edit
//Changes on the load of form
$(document).ready(function(){
$('#yourTxtBoxID').val('newvalue');
});
//Changes on clicking a button
$(document).ready(function(){
$('#somebuttonID').click(function(){
$('#yourTxtBoxID').val('newvalue');
});
});
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.
}