2

So I am in the process of attempting to use some simple code injection to populate a form and submit it, in most cases, I am able to have the textbox revalidate by firing the blur event, but in the case of a react form build on redux, it does not validate in the same manner.

I tried using the following code, but it does not work:
top.jQuery('input#last-name-\\[0\\]').val('Smith').attr('value','Smith').trigger('blur');

Is there an event that I should be firing instead of the input event?

The values are not detected as firing the click event on the submit fails validation, as though no data has been entered in the form.

I tried a number of triggers including keyup, keydown, keypress, focus, blur, and changed.

Please note that using default values are not an option, because I am injecting the form data into a website that is not my own.

This is the code that react is using to build the component:

function LastNameComponent(_ref) {
    var index = _ref.index,
        isFirstField = _ref.isFirstField,
        formatValue = _ref.formatValue;

    var minLength = 2;
    var maxLength = 80;
    return _react2.default.createElement(
        'div',
        { className: 'form--item span3' },
        _react2.default.createElement(
            'label',
            { className: 'search-label small field__icon_group' },
            _react2.default.createElement(
                'span',
                null,
                '*'
            ),
            'Last Name',
            _react2.default.createElement(_TextInput2.default, {
                id: "last-name-[" + index + "]",
                model: "searchParams.searches[" + index + "].fields.lastName",
                validators: { required: function required(value) {
                        return !value || value.length < minLength || value.length > maxLength;
                    } },
                formatValue: formatValue
            }),
            _react2.default.createElement(_ErrorMessage2.default, {
                model: "searchParams.searches[" + index + "].fields.lastName",
                messages: { required: "Please enter the member's Last Name" }
            })
        )
    );
}
7
  • Can you post the component / redux code that's doing this? It's a little hard to imagine Commented Jun 28, 2017 at 13:57
  • I added the component source, let me know if it makes sense. (I have never worked with react or redux myself so I'm sorry if it wasn't what you needed!) Commented Jun 28, 2017 at 14:03
  • Um, why on earth are you not using JSX? Commented Jun 28, 2017 at 14:04
  • Not my code, @Chris, I'll ask the devs if I ever have a chance to meet with them :P My implementation is limited to injecting form data from the client side. Commented Jun 28, 2017 at 14:06
  • @Bitz, sorry my bad. I skimmed through your post and thought that was your code. I missed the part where you said this is part of the source. Commented Jun 28, 2017 at 14:07

3 Answers 3

6

This does the trick

var target = $('input')[0]
var event = document.createEvent("HTMLEvents");  
$('input').val('Smith')
event.initEvent("input", true, true);
target.dispatchEvent(event);

Working example with same code here: https://codesandbox.io/s/W66Z4RA3E

Refer to https://github.com/facebook/react/issues/3249

Seems like event triggering is non trivial because dom and react events are not one to one.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! i will test this when I get to work, but it seems correct!
3

Out of all the answers and a lot of googling, I found this to be working

function changeValue(input,value){

    var nativeInputValueSetter = Object.getOwnPropertyDescriptor(
      window.HTMLInputElement.prototype,
      "value"
    ).set;
    nativeInputValueSetter.call(input, value);

    var inputEvent = new Event("input", { bubbles: true });
    input.dispatchEvent(inputEvent);
}

We are using window.HTMLInputElement.prototype that is HTMLInputElement. An interface that provides special properties and methods for manipulating the options, layout, and presentation of input elements.

Then we will use Object.getOwnPropertyDescriptor() method to set input value. Last we will dispatch change event on the input to simulate with React onChange

Here is a detailed explanation of this answer: https://hustle.bizongo.in/simulate-react-on-change-on-controlled-components-baa336920e04

1 Comment

This is the only approach that worked for me.
1

event.initEvent("input", true, true); is now deprecated. The proper way is:

const runInject = (inputElement, value) => {
  $(inputElement)
    .val(value)
    .attr('value', value);
  const event = new Event('input', { bubbles: true, cancelable: true });
  inputElement.dispatchEvent(event);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.