Disabled a button based on credit date expiry date validation in jquery - php

I have fields of credit card expiry date.Below code user enter a month and year
<input class="expiry-month exp" name="card_exp_month" id="card_exp_month" required>
<input class="expiry-year exp" name="card_exp_year" id="card_exp_year" required>
I am getting current month and year from php date() function.
<?php
$month= date('n');
$year= date('y');
?>
<input type="text" name="curr_month" id="curr_month" value="<?php echo $month;?>"/>
<input type="text" name="curr_year" id="curr_year" value="<?php echo $year;?>"/>
This button will be disabled when user enter a expiry month or year less to current month or year
<input type='button' class='btn btn-next btn-fill btn-rose btn-wd' name='next' value='Next' id="billing_nxtBtn" />
and jquery code
$( ".exp" ).keyup(function() {
var exp_month = $("#card_exp_month").val();
var exp_year = $("#card_exp_year").val();
var curr_month = $("#curr_month").val();
var curr_year = $("#curr_year").val();
if(exp_month < curr_month || exp_year < curr_year){
$("#billing_nxtBtn").attr("disabled",true);
}else if(exp_month > curr_month || exp_year > curr_year) {
$("#billing_nxtBtn").attr("disabled",false);
}
});
I want that when user enter a expire month or year less then to current month or year then button will be disabled and when user enter a expire month or year greater then to current month or year then button will be enabled.
Issue is that button is not disbaled when user enter a expire month or year less then to current month or year

There's a couple of issues. One is because you're not removing the disabled attribute; you need to use removeAttr(). Your logic is also flawed, as if I selected 01/2019 then the button would be disabled as the month is less than the current month - you're not taking in to account years.
There is also a couple of logical improvements you can make, such as using input instead of keyup (in case people copy+paste values, or use other entry methods for accessibility) and use prop() instead of attr(). That way you can simply provide the boolean condition as the argument.
Also just FYI, this is not secure in the slightest; it's ridiculously easy to break. You should provide this client side validation as a courtesy to users only and do the business critical date check on the server side.
With all that said, try this:
$(".exp").on('input', function() {
var exp_month = $("#card_exp_month").val();
var exp_year = $("#card_exp_year").val();
var curr_month = $("#curr_month").val() || 0;
var curr_year = $("#curr_year").val() || 0;
$("#billing_nxtBtn").prop('disabled', exp_year < curr_year || (exp_year == curr_year && exp_month < curr_month));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="expiry-month exp" name="card_exp_month" id="card_exp_month" required>
<input class="expiry-year exp" name="card_exp_year" id="card_exp_year" required><br />
<input type="text" name="curr_month" id="curr_month" value="6" />
<input type="text" name="curr_year" id="curr_year" value="18" />
<input type='button' class='btn btn-next btn-fill btn-rose btn-wd' name='next' value='Next' id="billing_nxtBtn" disabled/>

You should place your jquery constant value with PHP constant date, not get it from input field (which is dynamic value by user input), example code as below:
$( ".exp" ).keyup(function() {
var exp_month = $("#card_exp_month").val();
var exp_year = $("#card_exp_year").val();
var curr_month = parseInt('<?= date("n");?>');
var curr_year = parseInt('<?= date("Y");?>');
if (exp_year < curr_year) {
$("#billing_nxtBtn").attr("disabled", true);
} else if (exp_year > curr_year) {
$("#billing_nxtBtn").removeAttr("disabled");
} else {
if (exp_month >= curr_month) {
$("#billing_nxtBtn").removeAttr("disabled");
} else {
$("#billing_nxtBtn").attr("disabled", true);
}
}
});

Have u try to use Jquery.change Method
$("#card_exp_month,#card_exp_year").change(function(){
var exp_month = $("#card_exp_month").val();
var exp_year = $("#card_exp_year").val();
var curr_month = $("#curr_month").val();
var curr_year = $("#curr_year").val();
if(exp_month < curr_month || exp_year < curr_year){
$("#billing_nxtBtn").attr("disabled",true);
}else if(exp_month > curr_month || exp_year > curr_year) {
$("#billing_nxtBtn").attr("disabled",false);
}
});

Related

Get values inserted for field dynamically

I would like to insert up to 10 fields dynamically 10 into my form :
<form action="" method="post">
...
<div id="dynamicInput">Entry 1
<br>
<input type="text" name="myInputs[]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
...
<input type="submit" class="btn btn-primary" />
</form>
JS code :
var counter = 1;
var limit = 10;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
After clicking submit in form ( with post method ) I hope to get values inserted in this field in my php page?
For example I inserted 3 values dynamically using the JS code above, so I hope to get in my php page an array like this :
Array(
[0] => value1, [1] => value2, [2] => value3
)
Your initial form :
<div id="dynamicInput">Entry 1
<br><input type="text" name="myInputs[]">
</div>
and your javascript :
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
Give this dynamically generate field the name name='myInputs[]'> myInputs
Therefore when you receive the forms data back into your PHP code you will receive this in the $_POST array:
$_POST['myInputs'][0] = data in the first field
$_POST['myInputs'][1] = data in the second field
$_POST['myInputs'][2] = data in the third field
...
$_POST['myInputs'][9] = data in the tenth field
I don't know how to do with javascript but by using jquery you can do achieve it easily
please add script jquery.js in your site
HTML
<div id="dynamicInput">Entry 1
<input type="text" name="myInputs[]" class="myInputs" />
<input type="button" class="add_input" value="Add another text input" />
</div>
jQuery
$(document).ready(function(){
var limit = 10;
$(".add_input").on('click', function(){
if( $(".myInputs").length == limit ){
alert("You have reached the limit of adding " + limit + " inputs");
return false;
}
$(".myInputs:last").after("<br>Entry "+ ( $(".myInputs").length + 1 )+" <input type='text' name='myInputs[]' class='myInputs' />");
});
});
you can also check example at JSFiddle

Setting value with Javascript

I have this code:
<html>
<head>
<script type="text/javascript">
/***********************************************
* Drop Down Date select script- by JavaScriptKit.com
* This notice MUST stay intact for use
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and more
***********************************************/
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield){
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=0; i<31; i++)
dayfield.options[i]=new Option(i, i+1)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=1920; // fixed start year of 1900
var nowyear = 1994;
var diff = nowyear - thisyear +1; // number of years from 1900
for (var y=0; y<diff; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
}
</script>
<script>
function getcombined(){
var year = document.getElementbyId("yeardropdown").value;
var month = document.getElementById("monthdropdown").value;
var day = document.getElementById("daydropdown").value;
var combineddob = year + "-" + "month" + "-" + day;
document.getElementById("hidden1").value=combineddob
}
</script>
</head>
<body>
<form action="" name="someform">
<select id="daydropdown" name='day' value="daydropdown">
</select>
<select id="monthdropdown" name='month' value="monthdropdown">
</select>
<select id="yeardropdown" name='year' value="yeardropdown">
</select>
<input type='hidden' id='hidden1' name='dob' value="" />
<input type='submit' />
</form>
<script type="text/javascript">
window.onload=function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
}
</script>
</body>
</html>
I need the <input type='hidden' id='hidden1' name='dob' value='' /> to update to var combineddob when the form is submitted.
I have tried several methods, but I do not know much about javascript so I am not good with these kinds of fixes.
I may be over looking something, but I have not yet figured out what is wrong here.
If you want something to happen before a user submits the form, you should set the onsubmit property of the form. In this case:
<script>
<!--
function getcombined(){
var year = document.getElementById("yeardropdown").value;
var month = document.getElementById("monthdropdown").value;
var day = document.getElementById("daydropdown").value;
var combineddob = year + "-" + month + "-" + day;
document.getElementById("hidden1").value=combineddob;
return true;
}
-->
</script>
</head>
<body>
<form action="" name="someform" onsubmit='return getcombined();'>
I've added "return true" to the function to indicate that the form should actually submit afterwards. Also I fixed two typos, namely a lower case b in getElementbyId and a missing semicolon.
change your html
<input type='submit' />
to this
<input type='submit' id="submitButton" />
and in your script
window.onload = function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown");
var submitBtn = document.getElementById("submitButton");
submitBtn.onsubmit = function(){getcombined();};
};
This will allow you to run the function in onsubmit when the submit button is clicked. It will in turn call the function getcombined(); and then submit the form.
EDIT
Perhaps you should change these two lines:
var combineddob = year + "-" + "month" + "-" + day;
document.getElementById("hidden1").value=combineddob
to
var combineddob = year + "-" + month + "-" + day;
document.getElementById("hidden1").value=combineddob;
and
var year = document.getElementbyId("yeardropdown").value;
to (note that getElementbyId is not a function)
var year = document.getElementById("yeardropdown").value;
First of all:
var year = document.getElementbyId("yeardropdown").value;
to:
var year = document.getElementById("yeardropdown").value;
Add onclick in submit button:
<input type='submit' onclick="getcombined();alert(hidden1.value);" />

disabling/enabling the form values in php based on the if condition on the same page

here what i want to do is based on the if condition's value the total form should be disabled, how can i do that, here is the code i tried....
if ($today1 >= $saturday && $today1 <= $season1)
{
document.getElementById('season').disabled = false;
}
else if($today1 >= $startdate_offseasona1 && $today1 <= $enddate_offseasona1 )
{
document.getElementById('season').disabled = true;
}
else if($today1 >= $startdate_seasona2 && $today1 <= $season2)
{
document.getElementById(seasons).disabled = false;
}
and my form goes as follows:
<form action="" method="POST" id="season" name="season">
Min_Custom_League_size<input type="text" name="min_custom_league_size" size="40"/><br/>
Max_Custom_League_size:<input type="text" name="max_custom_league_size" size="40"/><br/>
Ranked_League_size:<input type="text" name="ranked_league_size" size="40"/><br/>
Screen_Capacity:<input type="text" name="screen_capacity" size="40"/><br/>
Wide_Release_Screens:<input type="text" name="wide_release_screens" size="40"/><br/>
Limited_Release_Screens:<input type="text" name="limited_release_screens" size="40"/><br/>
Starting_Auction_Budget:<input type="text" name="starting_auction_budget" size="40"/><br/>
Weekly_Auction_Allowance:<input type="text" name="weekly_auction_allowance" size="40"/><br/>
Minimum_Auction_Bid:<input type="text" name="minimum_auction_bid" size="40"/><br/>
<input type="submit" value="submit" name="submit" />
</form>
how can i do this based on the if condition value...what's wrong with my code??
You are mixing PHP (server-side) with JavaScript (client-side), and you can't do that. In any case, you have to disable the <input> elements, not the form itself.
Here is how to do that with PHP only:
<?php
$disableForm = $today1 >= $startdate_offseasona1 && $today1 <= $enddate_offseasona1;
?>
<form action="" method="POST" id="season" name="season">
Min_Custom_League_size<input type="text" <?php if($disableForm) echo 'disabled="disabled"'?> name="min_custom_league_size" size="40"/><br/>
<!-- repeat for all input elements -->
</form>
And here is a pure JavaScript way to disable the inputs unconditionally:
<script>
window.onload = function() {
var frm = document.getElementById('season');
var inputs = frm.getElementsByTagName('input');
for(var i=0; i<inputs.length; i++) {
inputs[i].disabled = true;
}
}
</script>
Note: you also have a typo inside your last else if block, it should be disabled, not diabled.
Use this for disable all elements in the form. likewise you can enable form elements
var theform = document.getElementById('seasons');
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (true) {
formElement.disabled = true;
}
}

Adding multiple rows to database from dynamic field event

I have a dynamic event in JS in my form which adds another block of fields so my users can add another address:
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id',
'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*11 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
if (newNum == 3) $('#btnAdd').attr('disabled', 'disabled');
});
$('#btnDel').click(function() {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
</script>
However, when I put my form action the page just refreshes when I click my 'add another address' button:
<form action="address.php" method="post" name="regForm" id="regForm" >
These are my fields:
if(empty($err)) {
for($i = 0; $i < 10; $i++)
{
$Street = $_POST['Street'][$i];
$Line2 = $_POST['Line2'][$i];
$Line3 = $_POST['Line3'][$i];
$Town = $_POST['Town'][$i];
$Postcode = $_POST['Postcode'][$i];
$Country = $_POST['Country'][$i];
$Tele = $_POST['Tele'][$i];
$Fax = $_POST['Fax'][$i];
$Type = $_POST['Type'][$i];
$Mobile = $_POST['Mobile'][$i];
$sql_insert = "INSERT into `address`
(`Street`,`Line2`,`Line3`,`Town`, `Postcode` ,`Country`,`Tele`,`Fax`,`Type`
,`Mobile` )
VALUES
('$Street','$Line2','$Line3','$Town','$Postcode','$Country',
'$Tele','$Fax','$Type', '$Mobile'
)";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
I want all addresses to go to mysql database.
I hope this is clear
Define buttons as followed: <input type="button" value="ButtonLabel" />.
My short test resulted in my <button> getting treated as submit type input by firefox. This means <button>FooBar</button> and <input type="submit" value="FooBar" /> are equivalent.
You might also want to simplify your javascript code. You can use the array notation for input names:
<input type="text" name="street[]" />
<input type="text" name="zip[]" />
<input type="text" name="street[]" />
<input type="text" name="zip[]" />
will result in $_POST["street"][0] and $_POST["street"][1] beeing filled with the user's input. This is what you want judging from your php code, anyway.
You don't need ids for all your input tags. Just keep one full set of inputs for one address and append this to your form. Maybe something like:
$('#address').append(
'<div>' +
'<input type="text" name="street[]" />' +
'<input type="text" name="zip[]" />' +
'</div>'
);
Or just have a full set hidden on your page and clone it, then append. I'm sure our jQuery pros will know a better solution.
And finally: Please sanatize your input with mysql_real_escape_string
$Street = mysql_real_escape_string($_POST['Street'][$i]);
// and so on for the other values.

Can validate an array of date[] but not process it?

I have a problem with this now, on the end of my mydate I have put [] so I can have an array to process and on the other page, I have process.php.
In the process.php, I have
foreach($_POST["mydate"] as $mydate ){
if($mydate != ''){
Date processed...etc etc....
}
If I put the [], it will store it but wont validate and if I dont put [], it will validate but not post?
Any thoughts?
<script type="text/javascript">
function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0]
var dayfield=input.value.split("/")[1]
var yearfield=input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false) input.select()
return returnval
}
function CheckDates(inputs)
{
var i, len;
if (inputs.length) {
len = inputs.length;
for (i = 0; i < len; i++) {
if (!checkdate(inputs[i])) return false;
}
return true;
}
return checkdate(inputs);
}
function add(tbl1) {
var tbl = document.getElementById(tbl1);
var rowCount = tbl.rows.length;
var row = tbl.insertRow(rowCount);
var colCount = tbl.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newCell = row.insertCell(i);
newCell.innerHTML = tbl.rows[1].cells[i].innerHTML;
}
}
</script>
<form name "enter" action="enter.php" onSubmit="return Checkdate(this.mydate)" method="post">
<table id="day" border="1">
<tr><b>Valid date format:</b><br></tr>
<tr><td>
<input type="text" name="mydate" />
</table><br>
<input type="submit" value="submit" />
<input type="button" value="Add Row" onclick="add('day')"/>
</form>
EDITTED
removed the space but still doesnt work
If there are more than one of the input field, the name must be mydate[] so they are placed in an array, and in your processing code you have an extra space... $_POST['mydate '] won't work it must be $_POST['mydate']
edit: this line <input type="text" name="mydate" /> must be <input type="text" name="mydate[]" />
Try this construction:
foreach ($_POST["mydate"] as $mydate ) {
if(!empty($mydate) && !is_null($mydate)) {
}
}

Categories