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 :)
Related
I am trying to output value of a button in a div when the button is clicked. On clicking it one time the value is outputted properly but what I am trying to do is output the value as many times the button is clicked in comma separated format.
For example -
<button class="click" value="car">Button</button>
<div class="demo"></div>
If I click this button 3 times then the output should be like car,car,car.
I am trying to do it this way but it's not working.
<script>
$(".click").click(function() {
$(this).addClass("selected");
var data=$(".click").map(function () {
return this.value;
}).get().join(",");
$(".demo").text(data);
});
</script>
(function($){
jQuery.fn.isEmpty = function() {
return !$.trim(this.html()).length;
};
}(jQuery));
$(".click").click(function() {
$(this).addClass("selected");
const limit = 3, sep = ',', $demos = $(".demo");
if($demos.html().split(sep).length < limit){
$demos.append(($demos.isEmpty() ? '' : sep) + $(this).val());
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="click" value="car">Button</button>
<div class="demo"></div>
You can append ,car to the textContent every time the user clicks the button. You'll also need to store whether this was the first click in a boolean, and if it is, trim off the first character.
var isFirst = true;
$(".click").click(function() {
$(this).addClass("selected");
$('.demo').text(($('.demo').text() + ',car').substring(isFirst ? 1 : 0))
isFirst = false
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="click" value="car">Button</button>
<div class="demo"></div>
if you need comma separated value each time then try this
var result = '';
$(".click").click(function () {
$(this).addClass("selected");
var data = $(".click").map(function () {
return this.value;
}).get();
if ($(".demo").text() == "") {
result = data;
} else {
result = result + ',' + data;
}
$(".demo").text(result);
});
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>
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>
MY CODE
function validate(e, id) {
var reg = new RegExp('^\\d+$');
if (reg.test($("#" + id).val())) {
var value = $("#" + id).val();
alert(value);
} else {
alert("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="number" id="number-input" oninput="validate(event,'number-input');">
This accept 1.(dot after any digits) value rest all is good.
You can try using <input type="tel" ...>. This way when user types 1. you will receive 1. only and not 1 and it will also open number keypad on mobile.
function validate(e, id) {
var reg = /^[0-9]*(\.(?=[0-9]+))*[0-9]+$/;
var value = $("#" + id).val();
if (reg.test(value)) {
console.log(value);
} else {
console.log("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="tel" id="number-input" oninput="validate(event,'number-input');">
You can also refer to How to get the raw value an <input type="number"> field? for more information in why 1. returns 1 and not 1.
It work as fallow:
1 pass
1. fail
1.1 pass
function validate(e, id) {
var value = $("#" + id).val() + "";
if (new RegExp('^[0-9]+\.[0-9]+$').test(value)
|| ((new RegExp('^[0-9]+').test(value) && !value.includes(".")))
) {
var value = $("#" + id).val();
alert($("#" + id).val() + "->" + value);
} else {
alert("fail " + $("#" + id).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="text" id="text-input" oninput="validate(event,'text-input');">
Here is a code that might help you.In the below code when the user types . it is replaced by null.It only accepts digits.This is for input type="text".The variable currValue has the value of the input.
The search() method searches a string for a specified value, and returns the position of the match.The search value can be string or a regular expression.This method returns -1 if no match is found.
Then I am using .replace()
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
Here I am replacing it with null if the regex doesn't match.The regex [^0-9] checks if not digit.
JSFIDDLE
Here is the code:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label>Digits Only:
<input type="text" />
</label>
<br>
<br>
EDIT :
In input type="number" we have to force it to always accept the updated val since many events does not work in it.So for that reason I have to update the existing value with the updated value after each event.
So I added
var v = $(this).val();
$(this).focus().val("").val(v);
So that each time the input is focused the value get updated with the existing value.
UPDATED FIDDLE FOR INPUT TYPE NUMBER
Updated snippet:
$(function() {
$('input').bind('keyup input', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" />
</label>
<br>
<br>
EDIT 2 : For special case + and -.I think its a bug I am not sure but check the below snippet.It works for all the cases.Hope it helps.
FINAL FIDDLE
$(function() {
$('input').bind('keyup', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
$(this).val(currValue.replace(/[^0-9]/, ''));
alert(v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" name="test" min=0 save="" oninput="validity.valid ? this.save = value : value = this.save;">
</label>
<br>
<br>
Hope it helps.For any other doubt feel free to ask.
I am trying to run a simple if-statement that checks if the input's value (what is typed in) is at least 5 and then to show the submit button. I tried using the keyup function to detect the value as it is being typed in.
Does anyone see what I am doing wrong?
jQuery.fn.fadeBoolToggle = function(bool) {
return bool ? this.fadeIn(400) : this.fadeOut(400);
}
$('#submit-package').hide();
$('#package-name-input').on('keyup', function() {
var nameInput = $(this).val().length;
if (nameInput => 5) {
$('#submit-package').fadeBoolToggle();
}
//$('#package-name-input').val().fadeBoolToggle(length > 5);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="gen-input" id="package-name-input">
<div class="proceed-btn sans-pro" id="submit-package">
<span class="proceed-btn-text">SUBMIT</span>
</div>
You can pass condition as your function parameter, also you should change => to >=
jQuery.fn.fadeBoolToggle = function(bool) {
return bool ? this.fadeIn(400) : this.fadeOut(400);
}
$('#submit-package').hide();
$('#package-name-input').on('keyup', function() {
var nameInput = $(this).val().length;
$('#submit-package').fadeBoolToggle(nameInput >= 5);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="gen-input" id="package-name-input">
<div class="proceed-btn sans-pro" id="submit-package">
<span class="proceed-btn-text">SUBMIT</span>
</div>
Do it like:
use keyup() method
var i = 0;
$('#target').hide();
$('#text').keyup(function(event) {
i++;
if(i == 5)
{
$('#target').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="text">
<div id="target">
<input type="button" value="submit">
</div>
This looks like a syntax error. Greater than or equal to is expressed as >=, not =>.