简体   繁体   中英

Local Variable to Global Variable in JavaScript

I am developing a web page where the Months will be calculated after entering the Date from the Input Field.

I want to take the value of "diffMonthsGlobe" to another function where this calculated value is going to the database.

But as I have seen few answers in StackOverflow and try to do the same but still in my case it is not possible

 var diffMonthsGlobe; function getValue() { // Getting Values...... const startDate = document.getElementById("startDate").value; const endDate = document.getElementById("endDate").value; // Calculating Time Period....... const date1 = new Date(endDate); const date2 = new Date(startDate); var diffMonth = (date2.getTime() - date1.getTime()) / 1000; diffMonth /= 60 * 60 * 24 * 7 * 4; diffMonths = Math.abs(Math.round(diffMonth)); diffMonthsGlobe = diffMonths; // Printing Values...... console.log(startDate); console.log(endDate); console.log(diffMonths + " Months"); return diffMonthsGlobe; } getValue(); console.log(diffMonthsGlobe + " Months");
 <input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required onchange="getValue()" /> <input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required onchange="getValue()" />

  1. Use a form so the required works
  2. Use the submit event to get the value and send to server

 const getValue = function() { // Getting Values...... const startDate = document.getElementById("startDate").value; const endDate = document.getElementById("endDate").value; // Calculating Time Period....... const date1 = new Date(endDate); const date2 = new Date(startDate); var diffMonth = (date2.getTime() - date1.getTime()) / 1000; diffMonth /= 60 * 60 * 24 * 7 * 4; diffMonths = Math.abs(Math.round(diffMonth)); diffMonthsGlobe = diffMonths; // Printing Values...... console.log(startDate); console.log(endDate); return diffMonthsGlobe; } window.addEventListener("load", function() { // page load document.getElementById("myForm").addEventListener("submit", function(e) { e.preventDefault(); // stop submission const monthDiff = getValue(); console.log(monthDiff + " Months"); // here you can fetch or otherwisde ajax to server }) })
 <form id="myForm"> <input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required /> <input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required /> <input type="submit" /> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM