How to increase the value of text field on page load in JavaScript?

I want to increase the value of text field on page load in JavaScript. For example

<input type="text" name="itemquantity[]" value="1"/>

after pageload it shoud be like

<input type="text" name="itemquantity[]" value="2"/>

Answers:

Answer

You can do this :

<input id="myid" type="text" name="itemquantity[]" value="1"/>
<script>
   localStorage['myid'] =
      document.getElementById('myid').value =
          parseInt(localStorage['myid'] || '0', 10) + 1;
</script>

At each load of the page, the value will be incremented by 1, with initial value being 1.

Answer
<input id="textField1" type="text" name="itemquantity[]" value="1"/>

<script>
window.onload=function()
{
document.getElementById('textField1').value=document.getElementById('textField1').value+1
}
Answer

You need to make the use of cookie or localStorage to achieve this. As each time the page is loaded state of web page is lost, so localStorage is at rescue

<!DOCTYPE html>
<html>
<body>

<div id="result"></div>
<script>
if(typeof(Storage)!=="undefined")
  {
 if(localStorage.itemquantity) {
  localStorage.itemquantity = parseInt(localStorage.itemquantity, 10) +1;
  document.getElementById("result").innerHTML="Value: " + localStorage.itemquantity;
}
else
{
    localStorage.itemquantity = 1;
}
  }
else
  {
alert('browser does not support local storage');
  }
</script>

</body>
</html>

As now you have the value you can assign it to the text-field

UPDATE

<script type="text/javascript">  
if(typeof(Storage)!=="undefined")  
{  
 if(localStorage.itemquantity) {  
  localStorage.itemquantity = parseInt(localStorage.itemquantity, 10) +1;  
  document.getElementById("txtFieldID").value = localStorage.itemquantity;  
}  
else  
{  
    localStorage.itemquantity = 1;  
}  
  }  
else  
  {  
alert('browser does not support local storage');  
  }  
</script>  

NOTE Keep txtFieldID as your textbox ID, at the first load the value will be set to 1 and with every load it will increment by 1
Hope this helps

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.