How to insert the value of javascript into html [duplicate] - javascript

This question already has answers here:
How to Add Two Days from Current Date to the Value of a Hidden Input
(3 answers)
How to insert Javascript variables into a database
(1 answer)
Closed 5 years ago.
I want to get the javascript value into my html input value and insert it into the database after the user click the submit
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("display").innerHTML = someFormattedDate;
</script>
<?php
echo $_GET['someFormattedDate'];
?>
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" value="<?php echo " someFormattedDate " style="border: 3px double #CCCCCC; " disabled/>

Since your input id is sd,
document.getElementById("sd").value = someFormattedDate;
Note: Elements with Disabled attribute are not submitted, enable it before submit.
Full Code:
<?php
echo $_GET['due_date'];
?>
<form name="myform" id="myform" method="GET">
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC; " readonly/>
<input type="submit" name="btn_submit" value="Submit">
</form>
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("sd").value = someFormattedDate;
</script>

First, put the JavaScript code after the input you want to use. That way the input exists on the page when the code executes.
Second, use the actual id of the input.
Third, set the .value property.
Fourth, put the input in a form.
Fifth, don't disable the input.
Something like this:
<form>
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC;" disabled/>
<input type="submit" value="Submit" />
</form>
<script>
// The rest of your JavaScript code, formatting your date value
document.getElementById("sd").value= someFormattedDate;
</script>
Unless otherwise specified, this <form> will submit a GET request to the current URL by default when the submit button is clicked.
Aside from that it's not really clear to me what you're trying to do with the PHP code here. Why you're trying to output a value that hasn't been submitted yet, or output a literal string, or whatever you're attempting.

<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("sd").innerHTML = someFormattedDate;
</script>
Description:- You are binding data with wrong element.

Related

time wont formatt correctly when using inputs

<?php
$date = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date']))))));
$date2 = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date2']))))));
?>
<!doctype html>
<html lang="en">
<head>
<title>date</title>
</head>
<body>
<form action="" method="post">
<label for="message" class="form-label">Date:</label>
<input type="date" class="form-control" id="date" name="date">
<br>
<label for="message" class="form-label">Date2:</label>
<input type="date" class="form-control" id="date2" name="date2">
<input id="saveForm" onclick="" class="button_text" type="submit" name="submit" value="Submit " />
</form>
<script>
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = month + "-" + day + "-" + year;
document.getElementById('date').value = today;
console.log(today);
//date works but output is diffrent
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById('date2').value = today;
console.log(today);
</script>
</html>
So the bottom one works when loaded and displays correctly however when submitted or console logged looks like this 2023-01-13 and when I change it to the correct format it stops working but will then console log correctly but will still echo out wrong... What is going on here? how can I make the date auto populate when page is loaded and still console log and echo out correctly like month/day/year ?????
```
<!doctype html>
<html lang="en">
<head>
<title>date</title>
</head>
<body>
<form action="" method="post">
<label for="message" class="form-label">Date:</label>
<input type="date" class="form-control" id="date" name="date">
<br>
<label for="message" class="form-label">Date2:</label>
<input type="date" class="form-control" id="date2" name="date2">
<input id="saveForm" onclick="" class="button_text" type="submit" name="submit" value="Submit "/>
</form>
<script>
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = month + "-" + day + "-" + year;
document.getElementById('date').value = today;
console.log(today);
//date works but output is diffrent
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById('date2').value = today;
console.log(today);
</script>
</html>
<?php
$date = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date']))))));
$date2 = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9- ]/', ' ', urldecode(html_entity_decode(strip_tags($_POST['date2']))))));
echo '<hr><br>';
echo $date;
echo '<br>';
echo $date2;
?>
```
I assume when i change this it should output correctly but instead only makes it half work
var today = month + "-" + day + "-" + year;

How can I get future date month and year by inputting opening date and duration month using JavaScript

when I select date and input month duration then other field will display the target date
how can I implement this,Please anybody help me to do that.my form is that
// I have tried to do that
$("#duration").keyup(function(){
var duration = $(this).val();
var open_date = $("#openDate").val();
// i want to use same function and method
// here will next code
var targetDate = new Date(open_date);
targetDate.setMonth(targetDate.getMonth() + duration);
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateString = dd + "/" + mm + "/" + yyyy;
$('#targetDate').val(dateString);
// i have do that but do not get my espect out put
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Open Date :
<input type="date" id="openDate"><br><br>
Duration Month:
<input type="text" id="duration" placeholder="mm"><br><br>
Target Date :
<input type="text" id="targetDate" placeholder="dd-mm-yyyy">
Please try this:
$("#duration").keyup(function(){
var duration = $(this).val();
var open_date = $("#openDate").val();
// i want to use same function and method
// here will next code
var targetDate = new Date(open_date);
targetDate.setMonth(targetDate.getMonth() + parseInt(duration));
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateString = dd + "/" + mm + "/" + yyyy;
$('#targetDate').val(dateString);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Open Date :
<input type="date" id="openDate"><br><br>
Duration Month:
<input type="text" id="duration" placeholder="mm"><br><br>
Target Date :
<input type="text" id="targetDate" placeholder="dd-mm-yyyy">

Why does my Javascript code only calculate my age only on the first click of the submit button only?

I have a java-script code which calculates a person age.
A user will enter his/her identity number in an input field and clicks submit. then the java-script code will calculate their age.
i do not understand why the java-script code does not calculate a different age when i change the identity number.
eg identity number 1: 7810104455082, identity number 2: 8001013355088 and identity number 3: 9502242235086
my html code below:
<input id="IDNumber" type="text" name="idnumber" placeholder="ID number" />
<input onclick="return validateID();" id="submit" type="submit" value="Submit" />
<p id="demo">demo</p> <p id="demo2">demo2</p>
<div id="screen" style="width:600px; height:400px; background-color:gray;"></div>
<button id="display">Display</button>
my javascript code below:
<script>
function validateID() {
var ex = /^(((\d{2}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012])(0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|([02468][048]|[13579][26])0229))(( |-)(\d{4})( |-)(\d{3})|(\d{7}))/;
var idNumber = document.getElementById("IDNumber").value;
if (ex.test(idNumber) == false) {
// alert code goes here
document.getElementById("demo").innerHTML = "Please supply a valid ID number" ;
alert('Please supply a valid ID number');
return false;
}
//Pull out Year and Month and Day for IDNumber
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
// set variable of fullDate to insert in math calculation
var fullDate = id_year + "/" + (id_month + 1) + "/" + id_date;
//math time calculation to give mil and convert to years
var d1 = new Date(); //"now"
var d2 = new Date(fullDate) // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
var yeardiff = diff / 31536000000;
document.getElementById("demo").innerHTML = "The Age is " + Math.round(yeardiff);
}
</script>
Remove the return on your onclick
<input onclick="validateID();" id="submit" type="submit" value="Submit" />

when enter a date in text box start date automatically Show dates of next one year in other textbox endtextbox

I have two textboxes in my asp.net using c# code
HTML Code
<tr>
<td></td>
<td style="text-align: right"><asp:TextBox ID="TxtEndDate" runat="server"
Width="177px" AutoPostBack="True" style="height: 22px"></asp:TextBox>
</td>
<td style="text-align: right">end date</td>
<td style="text-align: right">
<asp:TextBox ID="TextStartDate" runat="server" Width="177px"
AutoPostBack="True" style="height: 22px"></asp:TextBox></td>
<td style="text-align: right; direction: rtl;">
start date
</td>
</tr>
I want that when I enter date in dd/mm/yyyy in first text box (TxtStartDate), it will automatically fill the second text box (TxtEndDate) by adding plus one year in above entered date.
I tried This JavaScript but it is not working
<script type="text/javascript">
$('#TextStartDate').blur(function () {
var value = $(this).val();
var regex = /^\d{2}\/\d{2}\/\d{4}$/;
if (regex.test(value)) {
var myDate = new Date(Date.parse(reformat(value)));
var year = myDate.getYear() + 1;
var month = myDate.getYear() + 1;
if (month < 10) {
month = '0' + month;
}
var day = myDate.getDate();
if (day < 10) {
day = '0' + day;
}
$('#TxtEndDate').val(day + '/' + month + '/' + year);
} else {
alert('invalid date');
// this will prevent from leaving the input until the date is correct
$(this).focus();
}
});
</script>
It's your id's. ASP.NET hijacks your ids and prepends stuff on them. Change all your jquery id calls to
$("[id*=TxtStartDate]")
$("[id*=TxtEndDate]")
So, in your original script, do this:
<script>
$('[id*=TextStartDate]').blur(function () {
var value = $(this).val();
var regex = /^\d{2}\/\d{2}\/\d{4}$/;
if (regex.test(value)) {
var myDate = new Date(Date.parse(reformat(value)));
var year = myDate.getYear() + 1;
var month = myDate.getYear() + 1;
if (month < 10) {
month = '0' + month;
}
var day = myDate.getDate();
if (day < 10) {
day = '0' + day;
}
$('[id*=TxtEndDate]').val(day + '/' + month + '/' + year);
} else {
alert('invalid date');
// this will prevent from leaving the input until the date is correct
$(this).focus();
}
});
</script>
You could solve this with a more simple function:
var dateParts=value.split('/');
$('#TxtEndDate').val(dateParts[0]+'/'+dateParts[1]+'/'+(parseInt(dateParts[2])+1));
To access server controls with javascript you need to do this $('#<%=TextStartDate.ClientId%>') because asp.net controls IDs are generated at runtime.
Also set AutoPostBack to false or else the page will be refreshed every time one of the TextBox lost focus

jQuery set defaul value of date picker input

I am building a web app that uses a date picker to filter the search results of some event items.
The form submits via ajax just fine, (I am getting results) but I am having issues with setting a default value into the datepicker. The input type is text based, but it functions like a javascript DatePicker. Thanks for any help.
Note: I did not build the form from scratch, but it is customized to do what I need it to.
jQuery:
// Get current date
var date = new Date();
var month = date.getMonth()+1;
var day = date.getDate();
var year = date.getFullYear();
var currentDate = day + "-" + month + "-" + year;
$("#CAT_Custom_2_Min").val(currentDate)
$("#calendar-form").submit();
Form HTML:
<form id="calendar-form" action="/Default.aspx?CCID=17654&FID=197248&ExcludeBoolFalse=True&PageID=11940414" method="post" name="catcustomcontentform95560">
<table cellspacing="0" cellpadding="2" border="0" class="webform">
<tbody>
<tr>
<td><label>Event Start Time Min/Max:</label><br />
<input type="text" onfocus="displayDatePicker('CAT_Custom_2_Min');return false;" style="background-color: #f0f0f0;" readonly="readonly" class="cat_textbox" id="CAT_Custom_2_Min" name="CAT_Custom_2_Min" />
And <input type="text" onfocus="displayDatePicker('CAT_Custom_2_Max');return false;" style="background-color: #f0f0f0;" readonly="readonly" class="cat_textbox" id="CAT_Custom_2_Max" name="CAT_Custom_2_Max" /></td>
</tr>
<tr>
<td><input type="submit" value="Search" class="cat_button" /></td>
</tr>
</tbody>
</table>
</form>
Live Page: http://sevenclanscasino.designangler.com/warroad/warroad-calendar
jsfiddle: http://jsfiddle.net/VJQYb/
// Get current date
var date = new Date();
var month = date.getMonth()+1;
var day = date.getDate();
var currentDate = date.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
// Date for 7 days from current date
var futureDate = new Date();
futureDate.setDate(date.getDate() + week);
$("#CAT_Custom_2_Min").val(currentDate);
$("#CAT_Custom_2_Max").val(futureDate);
$("#calendar-form").submit();
I removed the variable d as it wasn't being declared, and added a # in front of CAT_Custom_2_Min and CAT_Custom_2_Max
you can try
<input type="text" id="date1" />
<script type="text/javascript">
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var cdate = month + "/" + day + "/" + year;
document.getElementById("date1").value=cdate;
</script>
just an example to clear the idea of showing date in input box...

Categories

Resources