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???

Recommended Answers

All 7 Replies

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

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

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;
}

@gon1387 it is not working???

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

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;
    }
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.