I'm trying to use checkbox as condition - javascript

So what I'm trying to do is this:
The user basically chooses date with input type='date', but if the user clicks a checkbox right next to it, the input type='date' will be replaced with the current date and time. And here is the code I wrote:
function myFunction() {
if($("#checkbox").checked == true) {
$("#input_date").hide();
var now = new Date();
$("#current_datetime").text(now).show();
} else if($("#checkbox").checked == false) {
$("#current_datetime").hide();
$("#input_date").show();
}
}
In the #checkbox in html code, I have onClick="myFunction".
As well, #current_datetime, which is simple text in span tag, and #input_date are located in the exactly same spot on the page.
But the function just won't work. There is no change at all, no matter how many times I click the checkbox.
I appreciate very much for your help in advance.

You can format your date according to below then you can use it in input type='date'
$(document).ready(function(){
$("#currentDate").on('change',function(){
var checked=$(this)[0].checked;
console.log(checked)
if(checked){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd;
}
if(mm<10){
mm='0'+mm;
}
today = yyyy+'-'+mm+'-'+dd;
$("#Date").val((today))
}
else{
$("#Date").val('')
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='date' id='Date'/><input type='checkbox' id='currentDate'/>

hope this help you
<input type="date" id="input_date">
<input type="checkbox" id="checkbox" >
<p id="current_datetime"></p>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$('#checkbox').click(function(){
if($(this).prop("checked") == true){
$("#input_date").hide();
var now = new Date();
$("#current_datetime").text(now).show();
}
else if($(this).prop("checked") == false){
$("#current_datetime").hide();
$("#input_date").show();
}
});
});
</script>

Checked is a property, you can read the value with .prop(). Also, to change the input value you need to use .val().
<script type="text/javascript">
function myFunction() {
if($("#checkbox").prop('checked') == true) {
$("#input_date").hide();
var now = new Date();
$("#current_datetime").val(now).show();
} else if($("#checkbox").prop('checked') == false) {
$("#current_datetime").hide();
$("#input_date").show();
}
}
</script>

Related

javascript operators do not match the input decimalx

I don't understand why when I use the condition value like a > b but it doesn't work properly, maybe because of the value a = decimal. following my code:
HTML
<input type="text" class="form-control" name="numberdays" id="numberdays" value="10.0/>
<input type="text" name="cutii" id="cutii" value="9.0">
<button class="btn btn-primary waves-effect" id="subcut" type="submit" disabled>
SCRIPT
cutifrom.addEventListener('input',()=>{
if (cutii.value > numberdays.value) {
subcut.removeAttribute('disabled');
}else{
subcut.setAttribute('disabled','disabled');
}
}) ;
the result is that my button is disabled, it shouldn't be.
here's my js. actually number days I use the datepicker and generate numbers that are automatically generated. maybe because it's the condition that I use the operator is not detected.
JS for datepicker
<script type="text/javascript">
$(document).ready(function(){
let $fromDate = $('#fromdate'),
$toDate = $('#todate');
$fromDate.datepicker().on('change', function(){
$toDate.datepicker('option', 'minDate', $(this).val());
});
$toDate.datepicker().on('change', function(){
$fromDate.datepicker('option', 'maxDate', $(this).val());
});;
});
$(function() {
let $fromDate = $('#fromdate'),
$toDate = $('#todate'),
$numberDays = $('#numberdays'),
$numberCuti = $('#cuti');
$fromDate.datepicker().on('change', function(){
$toDate.datepicker('option', 'minDate', $(this).val());
$numberDays.val(calculateDateDiff($toDate.val(), $(this).val()));
});
$toDate.datepicker().on('change', function(){
$fromDate.datepicker('option', 'maxDate', $(this).val());
$numberDays.val(calculateDateDiff($(this).val(), $fromDate.val()));
});
cutifrom.addEventListener('input',()=>{
if (parseFloat(cuti.value) >= parseFloat(numberdays.value)) {
subcut.removeAttribute('disabled');
}else{
subcut.setAttribute('disabled','disabled');
}
}) ;
function calculateDateDiff(endDate, startDate) {
if (endDate && startDate) {
let e = moment(endDate),
s = moment(startDate);
return e.diff(s, "days");
}
return null;
}
});
</script>
Your value is a String type and the comparison is not like Number, try converting the value to a number and see if it works.
You need to change the code to this form:
cutifrom.addEventListener('input',()=>{
if (Number(cutii.value) > Number(numberdays.value)) {
subcut.removeAttribute('disabled');
}else{
subcut.setAttribute('disabled','disabled');
}
}) ;
Good Luck :)

JQuery validate date between a date range [duplicate]

This question already has answers here:
Validate that end date is greater than start date with jQuery
(16 answers)
Validate end_date is after start_date [duplicate]
(1 answer)
Closed 5 years ago.
I've an input field where users can insert a date between a date range.
So I added a new method on JQuery validator object:
$.validator.addMethod("dateRange", function(value, element, from, to){
try {
var date = new Date(value);
if(date >= from && date <= to)
return true;
} catch(e) {
}
return false;
}
Then I added a new class rules:
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {fromDate, toDate}
}
});
And finally I added the class to the input:
$("#myField").addClass("myDateFieldRangeValidate");
So, how can I pass the two dates to the validation function?
UPDATE: Added a code snippet
$.validator.addMethod("dateRange", function(value, element, from, to){
try {
var date = new Date(value);
if(date >= from && date <= to)
return true;
} catch(e) {
}
return false;
});
var fromDate = new Date("2017-02-01");
var toDate = new Date("2017-12-31");
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {fromDate, toDate}
}
});
$("#myField").addClass("myDateFieldRangeValidate");
$("#btnValidate").click(function(){
$("#frm1").validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form id="frm1">
Date <input type="text" id="myField">
<input type="button" id="btnValidate" value="Validate">
</form>
Thanks to Arun P Johny, I post here his fiddle:
$.validator.addMethod("dateRange", function(value, element, params) {
try {
var date = new Date(value);
if (date >= params.from && date <= params.to) {
return true;
}
} catch (e) {}
return false;
}, 'message');
var fromDate = new Date("2017-02-01");
var toDate = new Date("2017-12-31");
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {
from: fromDate,
to: toDate
}
}
});
$("#myField").addClass("myDateFieldRangeValidate");
$("#frm1").validate();
$("#btnValidate").click(function() {
console.log($("#frm1").valid())
});
jQuery(function($) {
var validator = $('#myform').validate({
rules: {},
messages: {}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<form id="frm1">
Date
<input type="text" id="myField" value="16 Feb 2017">
<input type="button" id="btnValidate" value="Validate">
</form>
Here is a way to have jQuery validator with the feature to give the start date and the end date
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.js"></script>
<script>
$( document ).ready(function() {
// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
var startDate= new Date(jQuery(element)[0].attributes['data-rule-startDate'].value);
var endDate= new Date(jQuery(element)[0].attributes['data-rule-endDate'].value);
var d = new Date(value);
console.log(d)
return (d.getTime() <= endDate.getTime() && d.getTime() >= startDate.getTime())
}, "Please enter a valid date."
);
$('#frm1').validate();
});
</script>
<html>
<form id="frm1">
Date <input type="text" id="myField" name="myField" data-rule-optdate="true" data-rule-startDate="2017-12-12" data-rule-endDate="2018-12-12">
</form>
</html>

how to input current date in text box value with show my additional data

how to input current date in text box value with show my additional data in the text field.
my code is.
html input box
<input type="text" id="lro" class="form-control" name="lrno" value="<?php echo $_SESSION["con_branch_name"]; ?>LR151210<?php echo $_SESSION["con_branch_code"]; ?>">
my script is
<script type="text/javascript">
document.getElementById('lro').value = Date();
</script>
how to i show either the two data in text box value
<script type="text/javascript">
var date = Date();
var ele = document.getElementById('lro');
ele.value = ele.value + date;
</script>
Try this :
<script type="text/javascript">
var x = document.getElementById("lro").value;
document.getElementById('lro').value = x + Date();
</script>
<script type="text/javascript">
document.onload = function(){
var date = Date();
var valElem = document.getElementById('lro');
valElem.value = valElem.value + date;
}
</script>
Try this using jQuery:
var current_date= Date();
$('#lro').val($('#lro').val() + current_date);

Javascript form validation, check if date is passed

I'm trying to validate a form here and I'm almost done. The only issue is I can't figure out a way of validating the dates field to check whether the date that has been put in hasn't passed. It has to be done through Javascript... btw, here is the HTML:
<label for="reservationDate">Date of reservation (DD/MM/YYYY):</label>
<input type="text" id="date" name="date" onblur="validateDate(date)">
<span id="dateError" style="display: none;">Please enter your date of reservation in this format DD/MM/YYYY</span>
Here is the Javascript:
function validateDate(x) {
var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
if(re.test(document.getElementById(x).value)){
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
} else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
Hope someone can help :)
Here's some code to make this a specific answer to suit your needs:
function validateDate(x) {
var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
var entered = new Date(document.getElementById(x).value);
var today = new Date();
if( entered > today ) {
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
} else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
Here is the working, tested code: http://jsfiddle.net/digitalextremist/rwhhg/1/
Some past answers which are pieces but not really the whole deal:
Check if date is in the past Javascript
Validate that end date is greater than start date with jQuery
Javascript to validate date entered

Validation with KendoUI datetime

Hi i have an app where user can select for start datetime and end datetime if they want to create an event.
Now this is an html where i use KendoUI datetime plugin:
<div class="demo-section" style="width: 535px;">
<label for="start">Start date:</label>
<input id="start" value="01/01/2013" />
<label for="end" style="margin-left:3em">End date:</label>
<input id="end" value="01/01/2013"/>
</div>
</li>
<script type="text/javascript">
$(document).ready(function(){
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
}
}
function endChange() {
var endDate = end.value();
if (endDate) {
endDate = new Date(endDate);
endDate.setDate(endDate.getDate());
start.max(endDate);
}
}
var start = $("#start").kendoDateTimePicker({
change: startChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
var end = $("#end").kendoDateTimePicker({
change: endChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
start.max(end.value());
end.min(start.value());
});
Issues is i cant get validation as i want. Suppose user select From date the To date should display date which is greater that currently selected From date.My currrent code seems not works well. Thanks
Are you saying that you want to be able to select a From date greater than To, and that when you do To should automatically update to be greater than From?
If so you're almost there. You just need to update the startChange function to update the To date relative to From.
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
var endDate = end.value();
if (endDate && endDate <= startDate) {
endDate.setDate(startDate.getDate() + 1);
end.value(endDate);
}
}
}
Check this jsFiddle for a full working example.

Categories