Reputation:
I know this sounds a little stup.. but I would like to know if I can create a javascript that can automate some simple commands so that I can easily test some feature in the webpage I am making. Let's say that I have a text area in my page that looks like:
<textarea class="some-class"></textarea>
Now I would like to open the javascript console and paste a command that does the following:
I know I could use some other automation like Selenium but this is just a simple task that I would like to shortcut. How can I do this? I prefer pure javascript but can also work using jquery if its really required.
Upvotes: 1
Views: 306
Reputation: 35491
With jQuery it's pretty easy to do this:
function example() {
$('.mytextarea')
.focus() // Sets focus on the text-area
.val('CHANGE') // Changes the value of the textarea
.trigger("keydown", { // Trigger Enter (key 13)
which: 13
});
}
$('button').on('click', example);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="mytextarea"></textarea>
<button type="button">Run</button>
If you want each event to be fully processed before the next one happens, you can make each step async:
function step(cb, text) {
$('#step').text(`${text}...`);
return new Promise(
resolve => setTimeout(() => {
cb();
resolve();
}, 500)
);
}
function example() {
const $textarea = $('.mytextarea')
step(() => $textarea.focus(), 'focusing')
.then(() =>
step(() => $textarea.val('CHANGE'), 'changing')
)
.then(() =>
step(() => $textarea.trigger("keydown", {
which: 13
}), 'triggering')
);
}
$('button').on('click', example);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="mytextarea"></textarea>
<button type="button">Run</button>
<i id="step"></i>
Upvotes: 1