Home > front end >  How to change input text value and store data in Chrome Console with JS
How to change input text value and store data in Chrome Console with JS

Time:07-03

Background: I am doing website automation. I want to use JS to update some input text data. Now I write codes below in the chrome console, this only changed value on the textbox, but when i clicked the textbox again, it changed back to the default value. I think maybe i should trigger some events.

Question: what i should do to change input text value and store data?

Input Text HTML

var bc=document.getElementsByClassName('css-13lt97d')[0];
bc.value='25';
var event = document.createEvent(“HTMLEvents”); 
event.initEvent(“change”, true, true);   
bc.dispatchEvent(event);

CodePudding user response:

I'm not sure if you are asking for if you want the text to disappear or not so I'll answer both

Want to disappear:

Don't use JavaScript, HTML works just fine with the placeholder attribute

<input type="text" placeholder="This is a textbox" />

Don't want to disappear:

Don't use JavaScript, HTML works just fine with the value attribute

<input type="text" value="Default value" />

If you want the text to change based on elsewhere in your JavaScript but be persistent through refreshes you need to have actual JavaScript instead of just using the chrome console

<script>
// Your JavaScript goes here
</script>

Sidenote:

I don't know how document.createEvent() works but I recommend using the simpler

bc.addEventListener('input', function() {
  // Something when the text changes
}

Also document.getElementsByClassName()[] is not a very good way of doing this, you should assign the element an id and use

// Pick one
var bc = document.getElementById("instertID");
var bc = document.quereySelector("#insertID"); // The # is important

CodePudding user response:

This block of code should do exactly what you want:

var bc=document.getElementsByClassName('css-13lt97d')[0];
bc.value='25';

And this block of code is not necessary at all:

var event = document.createEvent(“HTMLEvents”); 
event.initEvent(“change”, true, true);   
bc.dispatchEvent(event);

Maybe you are using a library or framework (like Angular or Vue.js) and if it's right, you have to change your input value in the way your library or framework says.

For example in Vue.js you have something like :

<input type="text" v-model="username">

in this line you have a Model which is binded to your input and if you want to change your value, you have change "username" variable value...

  • Related