form text Input field value not changing with javascript

117 Views Asked by At

The problem is very simple but is driving me crazy. I am trying to automate a task on an existing website using a javascript injection with tampermonkey. All is working well until i try to change the value of some input fields in a form which is working and not working at the same time.

This is the element I'm trying to set the value for:

<input type="text" name="fighter">

This is the code i'm using to do this alteration:

document.querySelector("input[name='fighter']").value = 1;

The weird thing is when i run this code i can visually see a 1 in the text input field enter image description here but if i press forward on the form or anywhere on the page for that matter the number disappears and the value is considered nothing. It is like nothing is happening.
If i just put the cursor on the input field and type it with my keyboard it works fine. and if for example, in one field i type 3 and in the other i use javascript to change the value to 5 (which again shows the value in the input field ), and then i press next on the form, only the 3 gets registered with the form submission.
I can read the value from the input field when written with the keyboard with the selector above and it also works fine.
If i try using the .focus() method, the cursor doesn't shift into the input field.

I've looked a lot online and doesn't seem to find the same problem. If anyone has any ideas or needs further information please let me know.

I didn't post the webpage because it is a game that needs an account and progress to be able to see.

2

There are 2 best solutions below

1
user3931093 On

You should try to set the value of a form field and not to the element. Check this for https://www.javascript-coder.com/javascript-form/javascript-form-value/

1
jadjoud On

I was able to resolve this. I looked within the webpage's built in scripts using search keywords and found a function with a descriptive name "selectShips(id, amount)" which takes ID and amount of ships as input. I used it and the input was updated and registered as if i typed with the keyboard.
I don't have enough javascript experience to understand why this works and setting the value of the text input field doesn't , but I guess for my purposes as a hobbyist, I don't need to know..