I want to pick up date from screen, add 1 day and put back to screen.
<input type='text'value='20101231' id='from_date'>
<script>
function date_move(direction){
var from_date = document.getElementById('from_date').value;
var YYYY = from_date.substring(0,4);
var MM = from_date.substring(4,6);
var DD = from_date.substring(6,8);
var jsCurDate = new Date( parseInt(YYYY,10), parseInt(MM,10)-1, parseInt(DD,10) );
var newDate = addOrSubtracDays(jsCurDate,direction)
document.getElementById('from_date').value = newDate;
}
function addOrSubtracDays(jsCurDate,daysOffset){
var daylength= 1*24*60*60*1000;
var newDate = new Date(jsCurDate + daylength);
alert(newDate)
}
date_move(+1);
</script>
You can’t use
element.valueto get the contents of an arbitrary HTML element,.valueonly works on form elements. Useelement.innerHTMLinstead:Also, your use of
substringis wrong. I thinksubstris more clear:In
addOrSubtracDays(shouldn’t that beaddOrSubtractDays?) you want the number of milliseconds, so you should callDate.getTime. Moreover, you actually want toreturnthe new value:When changing
#from_dateyou probably want your date to be in the same format. For this, I extendDate‘s prototype with a new method (andStringwith a helper function):After this, we can simply call
toFormattedString:BTW, you don’t need to explicitly convert
YYYY,MMandDDto integers with base 10; those are converted automatically (without assuming a string beginning with0is an octal number):For the sake of clarity, the complete script now reads: