JavaScript HTML DOM click() not working on input - javascript

I am trying to execute a click() on a certain input and the click() method doesn't do anything. Here is my code :
document.getElementsByName("op")[1].click()
I worked with the chrome console and in a AHK script I have been working with and both don't do anything. I have tried with : getElementsByName, getElementById, getElementsByClassName... They all don't do anything.
The website is : https://etudier.uqam.ca/cours?sigle=MET5201
Here are the steps you need to do before clicking the button (input):
Step 1
Step 2
From what I have seen in the HTML code of the page and from some research, I think it does not work because the input is AJAX controlled.
When you click the button, it is supposed to load and tell, for every group, if there is places available.

If you click slowly on the button, you'll notice it does not react on click, but on mousedown. To trigger this event, you can use dispatchEvent:
// Create a mousedown event and dispatch it
document.getElementsByName("op")[1].dispatchEvent( new Event('mousedown') );

Related

Trying to click() a button with no onclick event

I'm trying to click Medium's clap button with .click().
Here's what I've tried:
On a medium post, I run let btn = document.getElementsByClassName('clapButton')[0]; to get the clap button, then run btn.click();.
After inspecting the button, it doesn't have an onclick event, so i'm not sure if i'm getting the wrong element, or if there's some other way to trigger it.
Is there some jquery code or something that's attaching the event to the button differently? Thanks!
Edit
Sorry for missing details, i'm trying to run the code through a firefox extension. The code also doesn't work through firefox developer's console (I ran the code above). I'm not sure why it seems to work on Chrome just fine.
Your question is pretty vague, but I'll try to address it from as many angles as I can.
One: if you check the value of btn.onclick and get null or undefined, that doesn't necessarily mean the button doesn't have a click handler. There are two ways to add event listeners to elements:
btn.onclick = function() { ... };
btn.addEventListener('click', function() { ... });
In the latter case, the function won't be assigned to the onclick property of the element. addEventListener can actually be used to add multiple listeners to the same object, all of which will trigger when the event occurs.
Two: it's also possible that the button itself really doesn't have any click handlers at all. However, if any of its ancestors do, then those handlers will also be triggered when the button is clicked. This is called event propagation or bubbling, if you want to read up on it.

.Click in a Onchange not working on Mac OS but works on Windows/linux

so I have an HTML part which is like
<select name="espece-prise" id="espece-prise" size="1" onchange="selectespece();">
<option value="{liste.espece}">{liste.espece}</option>
</select>
then I have an input type='file' in order to upload an image, this input is hidden and has the class 'btn_poster_photo'.
What I want
when the user uses the select (and click on an option) it triggers the 'onchange' and through the 'selectespece()' function a click on the hidden button thanks to the .Click function in selectespece().So after all these js function the result is:
select an option => it opens a window where you choose the file to upload
What I did
function selectespece() {
especeprise = $("#espece-prise").val(); //just a variable getting the value of my select (it works)
document.getElementById("btn_poster_photo").click();
}
I also did it in many different ways with jQuery
$("#espece-prise").on('change', function(){
especeprise = $("#espece-prise").val();
$(".btn_poster_photo").click();
})
What is happening?
When I select an option it triggers the click so it asks me to upload an image which is alright. This works on Chrome/Firefox/Opera... when I do it from a Windows/Ubuntu/archlinux computer
BUT
When I try it on safari/chrome from a MacOS it doesn't work, no error in console, I just select something and nothing happens. I tried to put an alert in my function 'onchange' it works, all works but not the .Click function...
I made several searches on Google but only found a few topics talking about an onclick after an onchange but not a .click in an onchange.
You can only programmatically trigger a file dialog window from a user-initiated event.
https://blog.mariusschulz.com/2016/05/31/programmatically-opening-a-file-dialog-with-javascript
In this case, I'm not sure if a change event would count, as typically a user-initiated event would be something like click, mousedown, mouseup, scroll, resize, keyup, etc.
Perhaps try to refactor to react to one of the above events (from your <select>) instead.

jQuery only ignoring a click trigger during a trigger chain

I have the following code:
$( "#check-button" ).on( "click", function() {
$("#button_cart").click();
$('.checkout-button').click();
});
I have this jQuery click event. What I want to do is, on clicking the check-button, the first line inside the function is updating the cart (which reloads the page) and then the second line inside the function is the checkout button, which takes me to the next (checkout) page.
But here only the first event is firing. Is this because the page is reloaded on "button-cart" clicking? How do I solve it?
That's correct. The second click actually could be working but in some kind of limbo between the click and the load and you wont see it.
The solution is to "handle" the reload event, I put it between "" because this event can't be handled ( as far as I know) but you can make some hacks.
First, why is reloading the page? Are you adding new content?
In this case just call the click in the content added with a load handler like $(document).ready();
Here is how i did it: Using localstorage.
Just saved the value of someVariable on check-button click ( along with button-cart click) and on page reload i checked if the value is set. If it is set, i unset it and clicked the next button.
Here is the link
This was really great help from SO. Thank u SO

jquery event added multiple times

I have a fairly large javascript class that generates an complete ajax-generated application. In one version of the ajax page there are a number of dropdown menus. These menus can get created and destroyed at various points during the life cycle of the application.
This is the behaviour I see:
User opens page version 1: no dropdowns
User goes to page version 2: dropdowns added with jQuery onchange event. Work as intended.
User returns to version 1 of page, dropdowns removed.
User returns to version 2 of page, dropdowns added again (using same element IDs)
dropdowns will now have 'double' event handling, triggering the event for each onchange.
The behaviour I'm struggling with is as follows.
On the initial page load, I add an onchange event:
function myClass(){
//Initiate once for current and future elements.
jQuery(document).on('change',".mydropdowns",
function(e){
self.submitDescriptionChange(this);
}
);
}
myClass.prototype.submitDescriptionChange = function (el){
doSomeAjaxStuff();
}
This works fine, except that each time the user goes to pages version 1 and returns to page version 2, the event gets multiplied. Very quickly you can end up with the event firing 20 times per change event, which in this case creates 20 ajax calls.
Logically, by using jQuery.off() I should be able to avoid this. But what happens instead is that the event is removed from both past and future elements, which means that when I recreate page version 2, the dropdowns won't work.
Every way I have tried this (and I've tried LOADS), I either end up with no event firing, or multiple events firing. I cannot seem to find a way to add/replace the elements whereby the event is only ever fired once.
Any ideas how I can solve this?
UPDATED
Yeah, so it turns out I misdiagnosed the problem. It actually came from repeatedly rebinding a 'hashchange' event, rather than rebinding the onchange event. Apologies for misdirection. Moving to bind() function to somewhere where it only executed once fixed the issue.
Since you do not want .off() to remove your events from other pages, I would suggest using namespaces for your events. For example, something like this:
function myClass(pageno) {
var pref_ev = 'mypage' + pageno + '.' + 'change';
$(document).off(pref_ev).on(pref_ev, ".mydropdowns", function(e) {
self.submitDescriptionChange(this);
});
}
This way, each page will have its own "change" event such as "mypage1.change". The event is still registered normally as a change event; the prefix namespace "mypage1" is used to only perform the .off() call on the right events.
I am not sure what plugin you are using for your dropdown menus but there should be a "destroy" method on that plugin. If you call that when removing the dropdowns that should work. Also, if you are only hiding the second page and not actually removing it from the DOM you dont have to re-invoke the plugin as the plugin will still be saved on the element.

DOM problem with click initiating a focusout event on a different input

I have an <input type=text> with focusout event handler
I have a <button> with click event handler
Focusout checks whether format in input box is correct. It does so by testing input value against a regular expression. If it fails it displays a message (a div fades-in and -out after some time) and refocuses my input by calling
window.setTimout(function() { $(this).focus(); }, 10);
since I can't refocus in focusout event handler. focusout event can't be cancelled either. Just FYI.
Click collects data from input elements and sends it using Ajax.
The problem
When user TABs their way through the form everything is fine. When a certain input box failes formatting check it gets refocused immediately after user presses TAB.
But when user doesn't use TAB but instead clicks on each individual input field everything works fine until they click the button. focusout fires and sets time-out for refocusing. Since time-out is so short focusing happens afterwards and then click event fires and issues an Ajax request.
Question
I have implemented my formatting check as an independent jQuery plugin that I want to keep that way. It uses .live() to attach focusout on all input fields with a particular attribute where format regular expression is defined.
Data submission is also generic and I don't want to make it dependant on formatting plugin. They should both stay independent.
How can I prevent click event from executing without making these two plugins dependant?
Example code I'm fiddling with
After some searching I've seen that all major browser support document.activeElement but I can't make it work in Chrome. FF and IE both report this being the active element, but Chrome always says it's BODY that is active even though click fired on the button element.
Check this code http://jsfiddle.net/Anp4b/1/ and click on the button. Test with Chrome and some other browser and see the difference.
You could use a flag...
Live demo: http://jsfiddle.net/Anp4b/4/
So your question is:
How can I prevent click event from executing without making these two plugins dependent?
Well, you obviously cannot prevent the click event. If the user wants to click the button, he will, and the click event will trigger. There's nothing you can do about that.
So the answer to the above question is: You cannot.
Based on the current conditions, you have to - inside the click handler - retrieve the validation result, and based on that result, decide if form submission should or should not occur.
JS Code:
$("#Name").focusout(function(){
var that = this;
valid = this.value.length ? true : false;
!valid && window.setTimeout(function() {
$(that).focus();
}, 0);
});
$("#Confirm").click(function(e) {
if ( !valid ) { return false; }
e.preventDefault();
alert('AJAX-TIME :)');
});
HTML Code:
<input type="text" id="Name">
<button id="Confirm">OK</button>
Is there are reason you use .focusout instead of .blur?
Using a flag is a good idea, but I would rather use a class on the element. By using classes to determine the state you can also style it accordingly. Here's my example based on your fiddle.
Another solution that hopefully gives the result you are looking for.
1) Create a named click handler:
var clickHandler = function(e){ /** submit form or whatever you want to do**/ };
$("button").click(clickHandler);
2) Add the following to the focusout event when it's failing validation:
$("button").unbind("click", clickHandler).one("click", function(){ button.click(clickHandler); return false;});
You can find an example of this here.

Categories