Javascript bugs in event handling

147 views Asked by At

I am trying to write a script which fill data(after i run the code in chrome console) in the registration form of a website.

I want a function in pure javascript which exactly work like a jquery function. See the code

Javascript:

var lastName = document.getElementById('lastName');
var event = document.createEvent('HTMLEvents');
var event2 = document.createEvent('HTMLEvents');
  event.initEvent('focus', true,false);
  lastName.dispatchEvent(event);
  lastName.value = 'Khan';
  event2.initEvent('blur');
  lastName.dispatchEvent(event2);

JQuery:

$('#lastName').focus();
$('#lastName').val("lastName");
$('#lastName').blur();

The problem is that JavaScript actually does not focus the field, where jQuery focus the field. So because of that when i try to submit the form it doesn't validate.

1

There are 1 answers

9
Adrian Nichols On

You should be able to use lastName.focus() if you need the event.

https://developer.mozilla.org/en-US/docs/Web/Events/focus