Using element.click() to simulate a Button Click in Javascript - javascript

I'm trying to write an extension for Opera that automatically sends specific chat messages. (Commands, to be exact.) For that, I want to enter the message into the textarea, simulate a button click to send the message and read the reply I get.
I've been trying to use the Element.click() function of JavaScript to simulate the click, but it doesn't work.
My code goes something like this:
document.getElementsByClassName("text-area")[0].value = "test";
document.getElementsByClassName("send-chat-button")[0].click();
The textarea gets filled in with the value I want, but it doesn't click the button.
I am also not getting any output on the console. I'd be glad about any help I can get.
Regards, Kileraptor1
UPDATE: You were right, the button does not have an OnClick event like I thought it had. I'm honestly not sure how it submits a message. Since I am writing a plugin for a website I do not own, I can not edit the source or anything.

The easiest way would be with the trigger() function in jQuery:
$(".send-chat-button:first").click(function()
{
// Whatever actions you want to perform on click
});
$(".send-chat-button:first").trigger("click"); // Executes the click event handler
trigger(event) will execute whatever specified events that are attached to an element at any point in the code.
If you want to use pure JavaScript, there's already a good answer here. As I said though, jQuery makes this extremely simple.

Related

Is there a way to delete a event listener that is in the DOM of a page using javascript?

I am wondering if there is a way of deleting a Event Listener using Javascript and I can't use removeEventListener() because I am not the one that made the Event Listener, it's already in the code of the website when I open it and I need it to be automatically removed so that the popup message does not prompt (It's very annoying when I have to delete 1000 things and a message comes up every time say "Do you want to delete these assets?").
My process that I take is:
I open the page (Already has an Event listener)
Proceed to delete assets (From a form)
Then when I click the submit on the page it has an Event listener attached to it (The one I need to get rid of when I open the page)
Then the Event Listener prompts and return confirm("Do you want to delete these assets?") (Very annoying)
Any idea on how I would delete this even listener that's on the page and is not opened by me?
Here is a picture of what the event listener looks like:
If you do help I thank in advance!
Found a different way of doing it with a bit of search and I am just gonna placebo confirm it with this code:
const realConfirm = window.confirm;
window.confirm = function() {
window.confirm = realConfirm;
return true;
};
Very simple and easy thanks for all the response sorry if the question was bad but thanks for the help lead me to the figuring it out.
P.S #CBroe I will read both of those for future questions sorry

How to find what intercepts my form submit?

My <form> submit is not doing anything, I think it's because the action is intercepted by some JQuery code (what else can it be?). In my reasonably complex web application, I can't even find which line of code is intercepting the action -- yes I wrote every line of them, but still I have no idea.
The question is: in general, is there an effective way to trace which piece of JavaScript code is intercepting a designated action?
console.log($('form').data('events'));
will give you a list of attached events to the given DOM element.
and you could even get the source code of it:
$.each($('form').data('events'), function () {
$.each(this, function () {
console.log(this['handler'].toString());
});
});
a quick and easy way would be using Google Chrome's developer tools.
Press Ctrl+Shift+I
Choose your element.
Click on the event to see the handler that might be "intercepting" your submit

Change value of text box using javascript (Jquery) before post back ASP.NET

I am trying to change the value of a set of text boxes (that hold greyed out suggestions in them) when the user presses the submit form button. This button runs a server side method using OnClientClick that submits the data and does a whole slew of other things.
Now my problem is that i can't either: fit in a javascript function that will change the values before the server gets hit, OR call the server side method in the javascript instead of the button OnClientClick event.
Ive tried:
$(this.form).submit(function(){
//Change value here
});
//using OnClientClick to call function
and
$("#"+"<%=submitBtn.ClientID %>").click(function(){
//Change values here
__doPostBack("<%=submitBtn.ClientID %>");
});
//not using OnClientClick to call server method
(pretty sure that won't work)
and
$("#"+"<%=submitBtn.ClientID %>").click(function(){
//Change values here
});
//using OnClientClick still to call function
Im stumped
Edit
Right I obviously didn't give enough info,
What happens when I use submit events is the server event fires before the JavaScript event, therefore when do a server side validation before I send the values away, I have the wrong values, there isn't any point in changing to client side validation because i will still have the same problem when I send the form data back to the db.
Update
So i still have a problem (both with this and mentally because of this).
Because of the idiots who worked on this before me (now i have to fix it) they removed the submit behaviour (asp.net) from the button at the bottom, because they use some server side trickery to figure out if some validators should be on or off (when really it should be client side that does that), hence they had to turn it off because it would fire validators if it didn't.
ANYWAY... So I'm still having trouble, the on click function for the button doesn't seem to fire in time or the scripts run simultaneously. I tested this by adding an alert and a breakpoint on the code behind, the breakpoint fires and the alert fires too. sooo..... yeah.
Is there any way i could maybe circumvent this by removing the "onclientclick" from the button and calling the function it calls in the CB?
Any ideas? (Please?)
Small update:
Still can't figure it out :(. Is anyone confused by the question?
Yup, this function should work
$(this.form).submit(function(){
//Change value here
});
But one culprit might be the commented part: "// Change values here." If you're using one of these,
$('#target').text('my new info');
$('#target').html('my new info');
...you will have trouble. You need to use .val()
$('#target').val('my new info');
The form is submitted before JS fires all events.
Have your button's onClientClick event change the values. You can call functions in sequence if you need to.
jQuery does some funky things with events and you can't be sure what order they will fire after they are attached. You must explicitly specify the functions to call.
<button id="some_button" onclick="SetValues(); SubmitForm();" />
Just stumbled across this. It's been a month since you first posted the question so you may have fixed it already. However, thought I'd add my thoughts anyway.
First, it's make sense your code is being ignored. When you bind to the submit and onclick events you functions are added to the list of events handles. Events handlers are processed from the first added to the last added. So the postback is started before your jquery code is called.
To solve this you need to change the code in the function that OnClientClick calls or write a wrapper function that calls your code then calls what OnClientClick called and change OnClientClick to call your wrapper function.
this function should do the trick:
$(this.form).submit(function(){
//Change value here
});
just make sure you enable the text fields again before you send them to the server, otherwise the server won't pick them up
I have used id of submit button to check for a "click"
http://jsfiddle.net/sreeprasad/7urvg/

Detect if the user has used the back button

My webpage runs a javascript function when the page is loaded. However, I don't want the function to run if the user comes back to this page using the back button. How can I prevent this using javascript?
$(document).ready(function(){
// Do not run this function if the user has arrived here using the back button
RefreshThePage();
});
I'd have thought that using cookies is the easiest way to do this
I think studying the way Struts handles duplicate form submissions could help you.
Some links:
http://www.techfaq360.com/tutorial/multiclick.jsp
http://www.java-samples.com/showtutorial.php?tutorialid=582
http://www.xinotes.org/notes/note/369/
Track when user hits back button on the browser
There are multiple ways of doing it, though some will only work in certain browsers. One that I know off the top of my head is to embed a tiny near-invisible iframe on the page. When the user hits the back button the iframe is navigated back which you can detect and then update your page. Here is another solution.
You might also want to go view source on something like gmail and see how they do it.
Here's a library for the sort of thing you're looking for by the way
The event object offers you to get the key code. so basically you register an eventlistener onKeyDown. Use the received event. if the keycode matches the key you like continue with your function.
document getElementById('elementId').onKeyDown = checkKey();
function checkKey(event) {
if (event.keyCode === keyCode) then . . .
}
play around with alert(event.keyCode); to find the right one.

Catching the specific Javascript code being executed onClick

I am working on a site that has loads of legacy Javascript and jQuery includes and there is no documentation to show what is happening when.
I have a specific problem to fix and I cannot find the relevant code that is being executed when a button is clicked. To save me from trawling through (and making sense of) hundreds of lines of legacy script, is there a feature, possibly in Firebug, that will identify what script is being executed when I click on a button?
I believe there is a feature in Firebug's console window called Profile. Click profile, click the button, then click profile again. It should give you what all functions were called in that time. Be warned that if this code includes jQuery, you might get a huge long list of functions because jQuery uses tons in its code. Unfortunately, the profiler will also show anonymous functions, which can really be a pain.
Otherwise, do a search in the code for the button's class or ID and go through them. If you have an id of fancy then you might do a search for #fancy in your code and attempt to find it. That may lead you in a general direction, at least.
You can click Firebug's "Break on next" button (in the Script tab; it looks like a pause button), then push the button that you want to debug.
The next time any JavaScript code executes, Firebug will break into the debugger and show you that line of code.
The break button didn't work for me. Instead I did edit the onclick attribute with FireBug and prepended it with "debugger;" ... then you'll break right there once you click :)
None of the above answers worked for me. I am trying to use Firebug to figure out how a feature on a page is working for a site I have no control over. Here is what worked for me.
First, got the id of the element I am clicking on from the page source, and then get a temporary reference to it by creating a watch (under the script tab):
tmp=document.getElementById("idOfElement")
Next, I assigned the current onclick value to another temporary variable.
oldfunc=tmp.onclick
Next, I defined a new onclick function. Initially I tried putting debugger; as the first thing in the function, but this does not work! So instead, I created an alert:
tmp.onclick = function() { alert("Ok"); oldfunc() }
Now, as soon as I click on the button the alert comes up, at which point I then click the "Break on next" button as outlined in another answer to this question. Then I dismiss the alert and immediately I am in the debugger at the correct place.
In my case, the "Break on next" button did not work by itself, because there are a lot of other events, just mousing over the page was causing the breakpoint to be hit, preventing me from ever clicking the button.
In Firebug you can set a breakpoint in some JS and then you get a stack which will let you know the current function call stack. So if you set the breakpoint in function used by several handlers then you can use this to discover exactly which handler you are in.
This probably won't work if you are dealing with AJAX callbacks and the like though.

Categories

Resources