HTML input element does not recognize value when I put value programmatically

Viewed 1490

I have a Google Chrome extension that retrieves data from one site and paste the data in another site.

To get the data from the first site I use this code:

$('#copy').click(function() {   
       var newClipboard = {
      "name": $('#buyercontactname').val(),
  }
chrome.runtime.sendMessage({newClipboard: newClipboard});
});

To paste the data in another site I use this code:

$(document).ready(function() {
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.paste) {
            if (!(request.clipboard.name === '')) {
                var nameParts = request.clipboard.name.split(' ');
                $('[id="shippingFirstName"]').val(nameParts[0])
                $('[id="shippingLastName"]').val(nameParts[1]);
            }
          }
        }
    });
});

I replace the id value regarding the second site div or input.

The problem:

If I paste the value on div it works great, but If I paste the value on input is not recognized and I need to press on a key for that.

For example:

After I paste the values:

enter image description here

After I click "Save" (I get an error the fields are empty):

enter image description here

After I press a key on the fields (even I press on "space"):

enter image description here

The input elemant look like this:

<input ng-model="user.first_name" id="shippingFirstName" name="shippingFirstName" prefix-attrs-with="shipping" value="" pattern="(?!^\d+$)^.+$" autocapitalize="off" autocomplete="off" maxlength="100" xo-error-tooltip="" ng-required="true" data-test-id="user.first_name" class="ng-pristine ng-empty ng-valid-pattern ng-invalid ng-invalid-required ng-valid-maxlength hasErrorTooltipRequired ng-touched focused" required="required" aria-describedby="nbafrxk" aria-invalid="true">

How can I solve it?

2 Answers

Create and dispatch an input event after setting the value of input box.You can get information about input event from this link.

document.querySelector('[id="shippingFirstName"]').value=nameParts[0];
document.querySelector('[id="shippingLastName"]').value=nameParts[0];
document.querySelector('[id="shippingFirstName"]').dispatchEvent(new Event("input", { bubbles: true }));
document.querySelector('[id="shippingLastName"]').dispatchEvent(new Event("input", { bubbles: true }));

Check out this question: val() doesn't trigger change() in jQuery

In summary, it looks like .val() by itself might not trigger the text field's change event, but you can trigger it manually by running this after you change the value:

$('[id="shippingFirstName"]').trigger("change");

If change() doesn't trigger it, you could try a bigger list of events to trigger the change in the put field:

$('[id="shippingFirstName"]').keydown();
$('[id="shippingFirstName"]').keypress();
$('[id="shippingFirstName"]').keyup();
$('[id="shippingFirstName"]').focus();
Related