Home > Mobile >  Why the value function in js is not working
Why the value function in js is not working

Time:03-08

First I created a input element which will take the text input from the user ...... <input style=" font-size: 12 px;" type="text" name="text" id="txt">

Then to this I used some javascript to get the value of the text that the user gives as an input for that I write the below code.... const text= document.querySelector('#txt').value console.log(text)

But with this I am not getting any kind of value actually I am just getting an empty null value in the console can anyone please point out the mistake in the code ...

CodePudding user response:

To read the input that a user has typed you need to add an event listener to the jnput element or to an associated submit button.

This snippet gives a simple example. It executes your Javascript when the user hits enter:

const input = document.querySelector('#txt');

input.addEventListener('change', function() {
  console.log(input.value);
});
<input style=" font-size: 12 px;" type="text" name="text" id="txt">

CodePudding user response:

I suggest you wrap your input into a form. Then, when the form has been submitted, you will be able to print the input text content. Please, check this example I made on codepen:

const onSubmit = (e) => {
 e.preventDefault();
 const text = document.querySelector("#txt").value;
 console.log(text);
};

const form = document.querySelector("form");
form.addEventListener("submit", onSubmit);

Also, you can get the value from the input text when it changes via the "change" event if you do not want to use a form. For example:

const onChange = (e) => {
 const text = e.target.value;
 console.log(text);
};

const input = document.querySelector("#txt");
input.addEventListener("change", onChange);

If this example does not satisfy what you want to achieve, please let me know ;).

CodePudding user response:

did you tried something simple by using html onkeyup/onchange events?

var handlerFunction = function() {
const text = document.getElementById("txt").value;
console.log(text);
}
<input style=" font-size: 12 px;" type="text" name="text" id="txt" onkeyup="handlerFunction()">

  • Related