Why my input value is not showing in the console?

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Storage Session</title>
  </head>
  <body>
      <form id="form-element" action="#" method="post">
        <p>Enter the name</p>
        <input type="text" name="name" id="task">
        <input type="submit" name="" value="submit">
      </form>
      <script type="text/javascript" src="storage.js" charset="utf-8"></script>
  </body>
</html>



const task = document.getElementById('task').value;
console.log(task);

Browser response:

I am using document.getElementById(“id”).value. By this way I should get the value given in the input field or not??

It doesn’t have a value. You need listen for an input event, and then get the value when that happens. Because you aren’t waiting for that, it logs the value that’s there, which is nothing.

1 Like



document.querySelector("form").addEventListener("submit",function(){
	
	let name=document.getElementById("task").value;
	let age=document.getElementById("task1").value;
	let domain=document.getElementById("task2").value;
	
	//console.log(name); //not working
	
	var obj={
		nobj:name,
		aobj:age,
		dobj:domain,
	};
//	localStorage.setItem("details",JSON.stringify(obj));
	
	let details;
	if(localStorage.getItem("details")===null){
		details=[];
	}else{
		details=JSON.parse(localStorage.getItem("details"));
	}
	details.push(obj);
	localStorage.setItem("details",JSON.stringify(details));
});

Can you explain the need of JSON.parse() and JSON.stringify() ? I tried before without giving stringify() and parse() as I had already created the empty array and inserted the first value in it. After that the value were not inserting into the array. please explain

Local Storage can only store strings. JSON.stringify() converts non-strings to strings. JSON.parse() reverts the conversion.

1 Like
		details=JSON.parse(localStorage.getItem("details"));

What will be the value of details now ?
Why we are using parse when .parse() ?? What is the need of doing this when details is already an array? What if we would do

details=localStorage.getItem("details");

Local storage can only hold strings. localStorage.getItem("details") returns a string. JSON.parse() makes it array.

If we do details=localStorage.getItem("details"); then details will be a string.