which getElement function to click button? - javascript

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.

Related

How to click a HTML element with javascript

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;})();

Is there a way to skip a specific CSS selector in HTML when using querySelector in JavaScript?

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" />

How to simulate a mouse click in Javascript

I have the following elements:
<input type="submit" name="add" value="add item" class="btn btn-add" onclick="addItem('add');return false;">
I want to write a Javascript to simulate a click of a mouse to add item to my shopping basket
I know you can use document.getElementById('add').click() but there's no Id here
I am very new to this and any help would be much appreciated
If you only have on element with name "add" you can also use:
document.getElementsByName('add')[0].click()
You can use Jquery library https://jquery.com
and in the code:
$( "input[name='add']" ).click();
Try using below javascript code.
document.addEventListener("click", function(){
document.getElementById("ID").innerHTML = "Click Event";
});
Get the element by class
var elem = document.getElementsByClassName('btn-add');
Then call click on it
elem[0].click()
Here are some possibilities
document.getElementsByName("add")[0].click();
where 0 is the first element on the page named add.
var form = document.getElementsByTagName("form")[0]; // change 0 to reflect the form
form.elements[form.elements.length-1].click(); // clicks the last button in the form
Alternative
document.forms[n].elements[m].click();
where n is the 0 based index of the form on the page and m is the 0 based index of the element in that form
You might want to use jQuery for this.
Using jQuery you can trigger a click like this:
$('#id').trigger('click');
In case you don't have an id but do have a class it might look like this:
$('.btn-add').trigger('click');
And of course with jQuery you can look at the parent dom element and 'find' the element you are looking for. eg:
$('#parentElement').find('button').trigger('click');
kudo's to mplungjan who came with:
$("input[name='add']").trigger('click');
another way you can find here:
see the fiddle

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.

How do I change the value of an input element?

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');
});
});

Categories