1.11M Members

how to increment the input field value in javascript on page load??

 
0
 

how to increment the input field value in javascript on page load??
for example

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

after page load it should be like

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

and so on on next page loads
any help???

 
0
 

Try this

<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

</head>
<body>
<?php
session_start();
if(isset($_SESSION['pageload'])) {
    $_SESSION['pageload']=$_SESSION['pageload'] + 1;
}
else {
    $_SESSION['pageload']=1;
}


?>
<div class="fieldClass">

</div>
<script type="text/javascript">
$(function(){
          var count ='<?php echo $_SESSION['pageload'];  ?>';
         for (var i = 1; i <=count; i++) {
             $('.fieldClass').append('<input type="text" name="itemquantity[]" value="'+i+'"/><br />');
         }
});
</script>

</body>
</html>

And Unset session $_SESSION['pageload'] if you go to another page

 
0
 

@Bachov i need code only in javascript i'm not wanted to use sessions

 
0
 

Hi Mehar89

here you go, let me know if you have questions.

var form = document.getElementById("myForm"),
    incInput = form["formitemquantity[]"],
    len = incInput.length,
    ctr = 0;

for(;ctr < len; ctr++){
    incInput[ctr].value = ctr;
}
 
0
 

@gon1387 it is not working???

 
0
 

when page reloads, everything in javascript resets, So I advised you to store last number in cookie and increment and display that cookie value on every page load

http://www.w3schools.com/js/js_cookies.asp

 
0
 

have you run it when the dom's ready?

Here's an online example in JSFiddle: JSFiddle Example
I've set the onDomReady on js fiddle. Here's a sample on firing the snippet when the page finishes loading. There are many flavors on firing this up, like checking the document readystate and so on and so for. But hopefully, this explains it.

window.onload = function(){
    var form = document.getElementById("myForm"),
        incInput = form["formitemquantity[]"],
        len = incInput.length,
        ctr = 0;
    for(;ctr < len; ctr++){
        incInput[ctr].value = ctr;
    }
};
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article