Send keypress event to textarea js - javascript

I am trying to automate somethings on some website
It has textarea and send btn (it all automatically generated with vue.js if it is matters, and this website is not mine)
<textarea class="index_textarea_1O4S1 mb2"></textarea>
<btn disabled='disabled> <span>send </span> </btn>
I need to set some text to textarea and press this button
But this code doesn't work
document.querySelector('textarea').textContent = "hello there"
document.querySelector('button').click()
As you can see btn stays disabled
I tried to remove disabled attribute of btn, but doesn't help also
So I guess the best option is to try to send keypress event to textarea
How do I do it?
BTW I don't know why but jquery $ functions seems to work strange from console on this website, so vanilla js is preferable

Assuming I understand correctly,
When I have run into this problem in the past, it's because there is some event listener that I'm trying to trigger and the element I send the event to is either targeting the wrong event or the wrong element. You can use dev tools to try and isolate the desired event, and you can send an event by creating it manually instead of calling the .click method.
For example:
const txtArea = document.querySelector('textarea');
txtArea.textContent = "hello there";
const inputEv = new Event("input", { bubbles: true });
const keydownEv = new Event("keydown", { bubbles: true });
const keyupEv = new Event("keyup", { bubbles: true });
txtArea.dispatchEvent(inputEv);
txtArea.dispatchEvent(keydownEv);
txtArea.dispatchEvent(keyupEv);
document.querySelector('button')
.dispatchEvent(new Event("click", { bubbles: true });
creating the event this way lets you even trigger custom events, once identified, by changing the first argument passed to the new Event constructor, and triggers parent elements by setting the option bubbles to true.

Related

How to trigger focus handler without actually focusing the element?

jQuery enables it like so:
$( "input" ).triggerHandler( "focus" );
How can I achieve the same without jQuery?
https://api.jquery.com/triggerHandler/
You use dispatchEvent on the element for which you want focus to be triggered. See the
docs and an example here.
const event = new FocusEvent('focus', {
view: window,
bubbles: true,
cancelable: true
});
const myInput = document.getElementById('myInput');
myInput.dispatchEvent(event);
#myInput:focus {
background: red;
}
<input id="myInput" type="text" onfocus="console.log('Input focused!');"/>
As you can see in the above code, the console.log statement is run based on the bound event to the input tag, but the element is not actually focused (because otherwise the input box would be red, which you can try by clicking on it).
Use the getEventListeners(node) function
In your case:
console.log(getEventListeners(document.getElementsByTagName('input')[0]));
You will get all the listeners, then you can filter those that are attached to the focus event

Button not clickable through javascript

I want to click a button (see attached) with javascript, in chrome console, but it doesn't work. I tried with ID and Class but no chance. If I want to click on an a element on the same site it's working fine with both lines..
What I tried:
document.getElementById('account-settings-save-button').click()
document.getElementsByClassName('btn-progress btn btn-primary icon-btn icon-right IDLE null')[0].click()
Sometimes click won't work for example if you use it on <a> tags it won't trigger link. You can try using MouseEvent API to simulate click event.
Here you can find nice example How to simulate a click event with vanilla JavaScript
In short, what you can try doing is:
//From the example above
var simulateClick = function (elem) {
// Create our event (with options)
var evt = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
});
// If cancelled, don't dispatch our event
var canceled = !elem.dispatchEvent(evt);
};
var buttonToClick = document.getElementById('account-settings-save-button');
simulateClick(buttonToClick);
var buttonToClick = document.getElementById('account-settings-save-button');
simulateClick(buttonToClick);
I solved it. This website is using vue. So the command is:
document.getElementById('account-settings-save-button').__vue__.onClick();
Sorry this question wasn't able to be answered by you.
What do you want to do when this button clicked. You must say onclick="your_code_here"
Working example fiddle: here
<button
id="account-settings-save-button"
onclick="alert('click event occured')">
BUTTON
</button>

Change span content using javascript

It works this way: when I click a subscribe button, it shows a message:
<span id="es_msg">
Your subscription was successful! Kindly check your mailbox and confirm your subscription. If you don't see the email within a few minutes, check the spam/junk folder.</span>
And I have to change this message using javascript cause I don't have access to the html. I tried to use the code below, but the message "Test" becomes always visible even before I click the subscribe button.
document.getElementById('es_widget_msg').innerHTML='Test';
That's because you didn't set the code up to be part of an "event handler". It's running without any user involvement, as soon as it's encountered. You said yourself you want the text to change when the span gets clicked.
// Get a reference to the span
let span = document.getElementById("es_msg");
// Set up a click event that references the correct event handling function
span.addEventListener("click", doClick);
// Define the handler function
function doClick(){
// In the DOM handler, the element that caused the event
// is available via the keyword "this". Also, if you are not
// modifying the HTML content of an element, use .textContent
// not .innerHTML
this.textContent = 'Test';
}
<span id="es_msg">
Your subscription was successful! Kindly check your mailbox and confirm your subscription. If you don't see the email within a few minutes, check the spam/junk folder.</span>
You can store the msg inside the data-* attribute of an element.
var $el_btn = $("#es_txt_button");
var $el_msg = $("#es_msg");
$el_btn.on("click", function(e) {
e.preventDefault();
// submit to backend and on succes do:
$el_msg.text($el_msg.data("msg"));
})
<button id="es_txt_button">Subscribe</button>
<span id="es_msg" data-msg="Your subscription was successful!"></span>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
or in plain JS
const el_btn = document.querySelector("#es_txt_button");
const el_msg = document.querySelector("#es_msg");
const subscribe = (e) => {
e.preventDefault();
// submit to backend and on succes do:
el_msg.textContent = el_msg.getAttribute("data-msg");
};
el_btn.addEventListener("click", subscribe);
<button id="es_txt_button">Subscribe</button>
<span id="es_msg" data-msg="Your subscription was successful!"></span>
You try below jQuery code..
$('body').on('click', '#subscribeId', function() {
$('body').find('#es_msg').text('Test');
});
If you do not use a event handling machanisum in doing this the code you have add will work on page load and rewrite the message as 'Test' very early than you expecting. So that, you have to add handler. Here we handle the click on the subscribe button with the subscribe button Id or the class name. In this case the action will take place only if the event happens, ie. Your click on button.
Hope this helps you.

Dispatch click eventon JSDOM with JavaScript

I'm trying to use JavaScript events to check an input checkbox in JSDOM.
<input type="checkbox" id="foo" />
But I can't seem to get it to check itself by dispatching an event on it:
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click", false, true);
document.querySelector('#foo').dispatchEvent(evt)
However, it does work when I use jQuery's .trigger('click')
Why doesn't this code work in jsdom? I feel there's some minor inconsistency in jsdom and likely some other browser which jQuery fixes.
There is a browser dependency on the way you can manually trigger events in JavaScript.
Here's a demo.
The Code:
document.getElementById("foo").value='500';
if (document.getElementById("foo").fireEvent) {
document.getElementById("foo").fireEvent("onclick");
} else if (document.getElementById("foo").dispatchEvent) {
var clickevent=document.createEvent("MouseEvents");
clickevent.initEvent("click", true, true);
document.getElementById("foo").dispatchEvent(clickevent);
}
Updated Fiddle
Updated Code:
if (document.getElementById("foo").fireEvent) {
document.getElementById('car-make').attachEvent('onchange', update);
document.getElementById("foo").fireEvent("onchange");
} else if (document.getElementById("foo").dispatchEvent) {
document.getElementById('foo').addEventListener('change', update, false);
var clickevent=document.createEvent("MouseEvents");
clickevent.initEvent("change", true, true);
document.getElementById("foo").dispatchEvent(clickevent);
}
function update () {
alert('changed');
}
From the specs:
The change event occurs when a control loses the input focus and its value has been modified since gaining focus. This event is valid for INPUT, SELECT, and TEXTAREA. element.
Bubbles: Yes
Cancelable: No
Context Info: None
Note how this is different from the click event, for example:
The click event occurs when the pointing device button is clicked over an element.
Thus, triggering a change event will not actually change the input value.
Loosely speaking, the Cancelable: No property says that nothing will happen by default.

Dispatching Custom Event and listening for it somewhere else (Bubbling) in IE

I can't seem to get this to work in JavaScript. I've tried using plain old JavaScript and also JQuery but nothing seems to work.
Here's my situation:
I have this PopUp "Panel" and in it I have a Button. The button has an event listener for click and I want that handler to fire off a custom event that the Panel will listen for. This is because I need to handle all the logic of the button click in the Panel.
Here's what I'm doing:
Before I launch the Panel I call a constructor for my "Class":
function PopUpStageAsssignmentTaker(content) {
PopUpStage.call(this);
this.allPagesAdded = false;
this.questionsCreated = [];// will be an array of pages that will be submitted
this.listLabel = null;
addAssignmentTakerParts.call(this);
this.popUpDiv.addEventListener("assignmentTakingSubmitEvent", handleAssignmentSubmit, true);
function handleAssignmentSubmit(event) {
alert("YESSS!");
}
}
This does quite a bit but just know that in the call to PopUpStage it creates the div that represents the Panel and saves that in this.popUpDiv. So I add a event listener to this.popUpDiv listening for some custom event that I'm making up.
Later on I have code that creates the content in the Panel and we have something like this:
SubmitQuestionTakingPage.prototype.makeContent = function(question) {
var questionWrapper = getQuestionWrapper();
var submitDiv = document.createElement("section");
submitDiv.innerHTML = "Pressing Submit will cause this Assignment to be submitted and you will be unable to make any changes after that. If this " +
"Assignment is automatically graded you will receive a Grade upon clicking submit. If this Assignment is not automatically submitted you must wait" +
" for the creator of this Assignment to assign you a Grade. To continue, please press Submit.";
submitDiv.setAttribute("class", "separatedSmaller");
questionWrapper.appendChild(submitDiv);
var submitButton = document.createElement("input");
submitButton.setAttribute("type", "submit");
submitButton.setAttribute("class", "fancyButton");
submitButton.addEventListener("click", handleSubmitButtonClick);
questionWrapper.appendChild(submitButton);
return questionWrapper;
};
function handleSubmitButtonClick(event) {
var event = document.createEvent("Event");
event.initEvent("assignmentTakingSubmitEvent", true, true);
window.dispatchEvent(event);
// $(this).trigger("assignmentTakingSubmitEvent");
}
So we create some content and in it we create a button that has a listener for click. In the click handler you can see how I fire off the event.
Problem: I'm reading that this does not work in IE under version 9+. What can I do in to make it work in all browsers? Is there a way?

Categories

Resources