How to simulate a mouse click in Javascript - 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

Related

JQuery how to get nested id inside onclick function

<button class="button" onclick="$('#4').popover('show')">Click me</button>
I have some code like above code snippet. I just need an id to pass into the onclick event.
The actual id I want to use is this button sibling's id, which I could get through
$(this).prev().attr('id')
I want to know how to replace #4 with #$(this).prev().attr('id'). Any thoughts?
Thanks Rayon! I got the answer - super straightforward!
$(this).prev().popover('show')
You can try with .parent()
Something like this:
$(this).parent('#parentId')
...if it's parent, or they are on the same level?
Of course, you can write some script where you can create variable for this parent id so you can write:
var parentID = $(this).parent('#parentId');
then you can write:
$(parentID).popover('show')
For siblings you can use:
$(this).siblings( "#siblingId" )

which getElement function to click button?

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.

How to select element relative to 'this' in javascript

I have the following:
<div class="tab-pane" id="message">
<textarea rows="4" cols="50" id="send_message" placeholder="Enter text ..."> </textarea>
OK
Cancel
I want to bind the click method to the 'div' element , and when one of the child 'a' elements is clicked do separate things. I am trying to distinguish between them using the button text, but the following is not working:
$(function(){
$('#message').click(function(){
if($(this + ">a").is(":contains(OK)")) {
console.log("OK!!");
How can I fix this?
Okay there are two ways of doing this:
.find(selector)
if(this).find("a").is(":contains(OK)")) {
console.log("OK!!");
OR
$(selector,context)
if("a",this).is(":contains(OK)")) {
console.log("OK!!");
In javascript, this is essentially the context of the current function. In jQuery event callbacks, this is set to be the source element of the event - not the selector string, which is what you are treating it as.
Instead, you want to do a test like: if($("a", this).is(":contains(OK)")) {
This works because the second parameter to the jQuery selector is the context to search in, so you are only searching for the a tags under the source element of the click.
Binding the click element to the Div, then checking the text string of the A tags will make both events happen on every click. You want to bind 2 separate click events on each A tag. Add an ID to each A tag, then try this code
$('#okLinkID').click(function(){
console.log("OK!!");
});
$('#cancelLinkID').click(function(){
console.log("Cancel!!");
});
//Attaches only one listener to the #message div and listens for any 'a' element within it to be clicked.
$('a','#message').on('click',function(){
var $this = $(this),
btnText = $this.text();
console.log(btnText);
});
http://jsfiddle.net/YA7Ds/

How to get element by javascript function

Can I select the element by its function?
for example
HTML
<button id="saveButton" onClick="javascript:fnSave(this)>
Save
</button>
then javascript
function fnSave(element){
console.log($(element).attr('id'));
}
clicking the button will result : saveButton
You can do that with using the currentTarget - like this:
save = function(object){
console.log($(object).attr('id'));
}
And, you would call this from your HTML like you mentioned - just including the quote:
<button id="saveButton" onClick="save(this)">Save</button>
To get the element you can do what you just did, add onClick='fnSave(this)' to the button, and on the function:
function fnSave(element){
//the element is in 'element'
}
But I see you are using jQuery, so you can remove the onClick and use this:
$("#saveButton").click(function(event){
var element = $(this);//the element is in 'element'
});
Note: if you are going to use this for multiple different buttons, it would be wise to select them by a clasName instead, or use the first function.
edited

How can I assign click function to many buttons using JQuery?

I have 29 buttons: todayResultsbutton0 .. todayResultsbutton28,
and 29 divs: todayResultsUrls0 .. todayResultsUrls28.
I also have a function toggleVisibility(divName) that hide/show the given div.
I am trying to use the following code:
for (var i=0; i < 29; ++i) {
var b = "#todayResultsbutton"+i;
var d = "todayResultsUrls"+i;
$(b).click(function(){toggleVisibility(d);});
}
I thought that this will cause each button click to show/hide the matching div but the actual result is that clicking on any button (0 .. 28) show/hide the last div - todayResultsUrls28.
Can someone tell me where am I wrong?
Thanks.
Use a class.
$(".myClass").click(function() {
var d = $(this).attr("id").replace("button", "Urls");
toggleVisibility(d);
});
Instead of trying to use a loop, you'd be better off using the selector to "find" your divs..
say you have something like:
<table>
<tr><td>
<input type="button" id="myButton" value="test" text="test" />
</td><td><div id="myDiv"></div></td></tr></table>
You can find myDiv by :
$('#myButton').parent().find('#myDiv').hide();
You could use the "startsWith" attribute selector with the id, then build the url from the id of the clicked item.
$('[id^=todayResultsbutton]').click( function() {
var url = this.id.replace(/button/,'Urls');
toggleVisibility(url);
});
Use
var d = "#todayResultsUrls"+i;
Instead of
var d = "todayResultsUrls"+i;
You can use this:
$('button[id^="todayResultsbutton"]').click(function() {
var index = this.id.substring(18,this.id.length);
toggleVisibility("todayResultsUrls"+index);
});
This will find all <button> tags with id's starting with todayResultsbutton. It will then get the ID for the clicked tag, remove the todayResultsbutton part of it to get the id and then call the toggleVisibilty() function.
Example here.
Edit
Notes:
Using button before the starts with selector ([id^="todayResultsbutton"]) speeds up the jQuery selector because it can use the native getElementsByTagName function to get all button tags and then only check those for the specific ID.
this.id is used instead of jQuery's $(this).attr('id') because it's faster (doesn't require wrapping this or calling the extra function attr()) and shouldn't cause any cross-browser issues.
Toggle visibility by finding the relevent div usint the event target rather than classes etc.
Assuming:
<div id='todayResultsUrls1'>
<button id='todayResultsbutton'></button>
</div>
Using the event target you can get the button element and find the div you want to hide.
var parentDiv = $(e.target).parent();
toggleVisibility(parentDiv);

Categories