Not able to get correct date value in javascript - javascript

[I have updated this question below, please see new question on infinite looping of alert]
I have a date of birth field in my form and there is an input field as well as date picker.
After keying in the correct value, the change function is activated and runs the logic as below to do some processing to the date of birth to get age.
However, when I use alert() to prompt for the value of the date of birth, I am not able to see the value I keyed in reflected, instead, it is showing an empty string.
I tried document.getElementById("9_element14").value, but that didn't work, it showed undefined. So I switched to jQuery and now it shows empty string.
It is a Wordpress form maker form, so there is restriction in amending the HTML, but I can change the JavaScript.
Any advice is much appreciated.
The link to the form is here:
http://lionfish.vodien.com/~scforgsg/RC7/menu-parent-courses/course-application/
My codes are as below:
HTML
<tr id="9" type="type_date"><td valign="middle" align="left" id="9_label_section14" class="">
<span id="9_element_label14" class="label">Date of Birth:</span>
<span id="9_required_element14" class="required"> *</span></td>
<td valign="middle" align="left" id="9_element_section14" class=" toolbar_padding"><input type="hidden" value="type_date" name="9_type14" id="9_type14">
<input type="hidden" value="yes" name="9_required14" id="9_required14">
<input type="text" value="" class="wdform_date" id="9_element14" name="9_element14" maxlength="10" size="10" onchange="change_value('9_element14')">
<input id="9_button14" type="reset" value="..." format="%d-%m-%Y" onclick="return showCalendar('9_element14' ,'%d-%m-%Y')" class="button">
</td>
</tr>
JAVASCRIPT
// before form is load
function before_load()
{
}
$(document).ready(function() {
$('[id$=11]').hide();
$('[id$=49]').hide();
});
// before form submit
function before_submit()
{
}
// before form reset
function before_reset()
{
}
function on_choose_course() {
var course = document.getElementById("1_element14");
var selected = course.options[course.options.selectedIndex].value;
if (selected=="Canoe Polo Lvl 1" || selected=="Kayaking Orientation" || selected=="1 Star Award"){
$('[id$=49]').hide();
}
else{
$('[id$=49]').show();
}
}
$(function(){
$('[id$=9_element14]').change(function(e) {
on_date_select();
});
});
function ValidateDate(dtValue)
{
var dtRegex = new RegExp(/\b\d{1,2}[\-]\d{1,2}[\-]\d{4}\b/);
return dtRegex.test(dtValue);
}
function on_date_select() {
//calculate age
var current_year = new Date().getFullYear();
if ($('[id$=9_element14]').length) {
var dob = $('[id$=9_element14]').val();
alert($('[id$=9_element14]').val());
if (ValidateDate(dob)){
var age = current_year - substr(dob, 6, 10);
alert(substr(dob, 6, 10));
alert(age);
if (age<21){
//show declaration is 21 and above
$('[id$=11]').show();
}
if (age>=21){
//show declaration is 21 and above
$('[id$=11]').hide();
}
}//end validatedate
}//end check empty
}
==================================================================
Thanks guys for helping! Using jsfiddle and making changes here and there, I derived the conclusion that the way I was using substring for dob was not working, causing the whole function to fail.
So now I have corrected it. Only problem now is that I am getting an infinite looping of alerts when date of birth is invalid.
NEW CODES:
// before form is load
function before_load()
{
}
$(document).ready(function() {
$('[id$=11]').hide();
$('[id$=49]').hide();
});
// before form submit
function before_submit()
{
checkDetails($('[id$=15_element140]'),$('[id$=21_element14]'));
}
// before form reset
function before_reset()
{
}
function on_choose_course() {
var course = document.getElementById("1_element14");
var selected = course.options[course.options.selectedIndex].value;
if (selected=="Canoe Polo Lvl 1" || selected=="Kayaking Orientation" || selected=="1 Star Award"){
$('[id$=49]').hide();
}
else{
$('[id$=49]').show();
}
}
function checkDetails(e,f){
if (e.checked && (f.trim()).length==0){
alert("Please give details about the medical condition.");
e.focus();
}
}
$(function(){
$('[id$=9_element14]').change(function(e) {
on_date_select();
});
});
function ValidateDate(dtValue)
{
var dtRegex = new RegExp(/\b\d{1,2}[\-]\d{1,2}[\-]\d{4}\b/);
return dtRegex.test(dtValue);
}
function on_date_select() {
//calculate age
var current_year = new Date().getFullYear();
if ($('[id$=9_element14]').length) {
var dob = $('[id$=9_element14]').val();
if (ValidateDate(dob)){
var age = current_year - dob.substring(6, 10);
if (age<21){
//show declaration is 21 and above
$('[id$=11]').show();
}
if (age>=21){
//show declaration is 21 and above
$('[id$=11]').hide();
}
}else{
$('[id$=9_element14]').focus(
function() {
alert("Date of Birth is invalid");
}
);
}//end validatedate
}//end check empty
}

The ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Change your element identificators according the rules and everything will work.
More information here and here.

Related

regular expression in javascript user input

I am having a problem with regular expression in javascript. What i am trying to do is a form register in which i must validate the first name so i decided to go with javascript validation (can you please tell me if going with js is the better option or going with ajax php reg validation?). So I wrote my code by checking some tutorials and reading from google but i am still having a problem. It is not working ! It runs on blur event using jquery so I need your help please to do this.
The pattern i am trying to check is for special characters in the user input
/[\'^£$%&*()}{##~?><>,|=_+]+$/g;
here is my script:
$(document).on('blur','.first_name_input', function() {
var firstNameInput = $(".first_name_input").val();
if (firstNameInput !== '') {
//var exp = /[a-zA-Z0-9-]+$/g;
var exp = /[\'^£$%&*()}{##~?><>,|=_+]+$/g;
//if (firstNameInput.test(/^[\'^£$%&*()}{##~?><>,|=_+-]+$/)) {
//if (firstNameInput.match(/[a-zA-Z0-9]*/g)) {
if (firstNameInput.match(exp)) {
var firstnameValidity = "<div class='name_not_valid_div'>× Not allowed characters present!</div>";
$('body').prepend(firstnameValidity);
$(".name_not_valid_div").hide().fadeIn('slow');
if (!errorArray.includes("firstName")){
errorArray.push("firstName");
}
} else {
$(".name_not_valid_div").hide();
if (errorArray.includes("firstName")){
for(var i = errorArray.length - 1; i >= 0; i--) {
if(errorArray[i] === "firstName") {
errorArray.splice(i, 1);
}
}
}
}
}
});
and my html code is :
<tr>
<td class="label">First Name: </td>
<td class="input"><input type="text" name="first_name" class="input_bar first_name_input" size="30" Placeholder="First Name" /><br/></td>
</tr>
1st: use .trim() to avoid left/right whitespaces or even the spaces without any characters $(".first_name_input").val().trim();
2nd: for validation
// if the string has special characters
function string_has_spec_char(str){
var reg = /[~`!##$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\?]/g;
return reg.test(str);
}
// check if string has spaces
function string_has_spaces(str) {
var reg = /\s/g;
return reg.test(str);
}
and use it like
if(string_has_spec_char(firstNameInput) === false){
// the first name doesn't have special characters
}
if(string_has_spaces(firstNameInput) === false){
// the first name doesn't have spaces
}

Form validation woes

New to JS guy here! I feel I have understanding of what my code is doing, but it still won't work.
The bug is (supposedly) with the validation for the phone number form, I have code that -as far as I know- should work (but does not).
Note that I have not got code to validate Address, post code and CC. The Idea is that I can apply your solutions to theses, seeing as they are similar to Phone number.
Also note I did try isNaN, but it was being "weird". Hope thats not too vague, but I'm sure some of you will "know" what I'm talking about.
Here we go (Sorry if my function is a bit long, let me know if its bad practice or whatever.)
Lets stay away from blunt answers if we can? I'd like to know whats wrong so I can fix it myself, walk me through it if you have the mind to be patient :)
JS and HTML:
function detailCheck() {
var phNoLength = document.getElementById('phNo').value.length; //get value for phone number from form for checking
var cardNoLength = document.getElementById('cardNo').value.length; //get value for card number length for checking
var postCodeLength = document.getElementById("postCode").value.length //get value for post code length
var a = /^[A-Za-z]+$/;
var b = /^[-+]?[0-9]+$/;
for (var i = 0; i < 5; i++) {
details = document.getElementById("myForm")[i].value;
if (details === "") {
var i = ("Please enter ALL your details.");
document.getElementById("formTital").innerHTML=i;
return;
} else {
if(phNoLength != 7) {
var i = "Please use a phone number with a length of 7";
document.getElementById("formTital").innerHTML = i;
} else {
if(b.test(document.getElementById("phNo").value)) {
if(postCodeLength === 4){
var f_nameLength = document.getElementById('fName').value.length;
var l_nameLength = document.getElementById('lName').value.length;
if(f_nameLength < 3) {
var i = "First name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("fName").value)) {
if(l_nameLength < 3) {
var i = "Last name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("lName").value)) {
if(cardNoLength === 4) {
if(isNaN(cardNoLength)) {
var i = "Your card number must be numbers only";
document.getElementById("formTital").innerHTML=i;
} else {
//---- End result ----//
toggleContent();
//--------------------//
}
} else {
var i = "Your card number must have four numbers";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "Please only use letters in your last name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please only use letters in your first name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please use a post code with a length of four";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "only use numbers in your Phone number";
document.getElementById("formTital").innerHTML=i;
}
}
}
}
}
<form id="myForm" action="form_action.asp">
First name: <br> <input class="formInput" type="text" id="fName" name="fName"><br>
Last name: <br> <input class="formInput" type="text" id="lName" name="lName"><br>
Phone Number: <br> <input class="formInput" type="number" id="phNo" name="phNo" maxlength="7"><br>
Credit Card Number: <br> <input class="formInput" type="password" id="cardNo" name="cardNo" maxlength="4"><br>
Address: <br> <input class="formInput" type="text" id="address" name="address"><br>
Post code: <br> <input class="formInput" type="number" id="postCode" name="postCode" maxlength="4"><br>
</form>
It is not obvious when you want the validation to occur (you included a function but it is not clear whether you want it to be an event handler or not).
Your regex seems to be fine. I am including a stripped-down JSFiddle with a single input to which I attached an event handler for keyup and showed the result of .test() for your regex.
See it here.
In regards to your code, it is fairly messy. In terms of form validation. I assume you meant to display a single status message for the user, so you would want to you want to first figure out the priority of your validation. One cleaner option would be to use a function with ordered returns, for example take this pseudo-code:
function getErrorMessage(){
// if name is invalid
// return 'Your name is invalid.';
// if phone is invalid
// return 'Your phone is invalid.';
// ...
// return '';
}
Nesting so many conditional statements can lead to very messy, very non-maintainable spaghetti code. If you are new to Javascript, it is best to learn the best practices early on, as it will save you a lot of headache and facepalms in the future.
If I did not understand your question correctly, please let me know.

entry in input one by one should show added result in result field

when user select any option in radio buttons in group one and then enter any number in respective input field and then select the next any radio option and enter any value in input field then this time it should add the new result with old one and display it in result input field and now if he empty any input field then that should also minus from the total result and display it in result field.
i have so many groups like that but here i just put two of them to get the result.
here id the FIDDLE
here is the jquery code. i can work in jquery but not very good i used separate code for every group and i know there must be a way to get this whole functionality through generic code but again i am not good at jquery
jQuery("#txt_im").keyup(setValue);
jQuery('[name="rdbtn-im"]').change(setValue);
function setValue() {
var txt_value = jQuery("#txt_im").val();
var rad_val = jQuery('[name="rdbtn-im"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res = txt_value * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
var final2 = 0;
jQuery("#txt_fb").keyup(setValue2);
jQuery('[name="rdbtn-fb"]').change(setValue2);
function setValue2() {
var txt_value = jQuery("#txt_fb").val();
var rad_val = jQuery('[name="rdbtn-fb"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res2 = txt_value * rad_val;
final2 = parseInt(res2, 10) + final;
var MBresult = final2 / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
infact user is free to select any number of groups or also free to remove any number of group after selection.
i know there is error in fiddle when user select 2nd group after the select of first it removes the result which is wron and i tried to solve it but failed but i define the whole seen what i need to do. i will be very thankfull to you for this kind favour.
HTML:
<table>
<tr>
<td>
<input type="radio" name="rdbtn-im" id="rdbtn-im-day" value="25" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-im" id="rdbtn-im-week" value="175" class="rdbtn-style-social" />Weekly
<input type="text" name="txb3" id="txt_im" class="txt-email" style="width:100px;margin: 2px;" />
</td>
</tr>
<tr>
<td class="sec-td-rdbtns-social">
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-day" value="3500" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-week" value="500" class="rdbtn-style-social" />Weekly
<input type="text" name="txb1" id="txt_fb" class="txt-email" style="width:100px;margin: 2px;" /> </td>
</tr>
</table>
<br>result
<input type="text" name="final_res" id="final_res" class="" style="width:100px;margin: 2px;" />
Jquery:
jQuery(".txt-email").keyup(setValue);
jQuery('.rdbtn-style-social').change(setValue);
function setValue() {
var total = 0;
$(".rdbtn-style-social:checked").each(function () {
var myInput = $(this).siblings(".txt-email").val();
if (myInput.length) {
total += myInput * $(this).val();
}
});
if (total) {
jQuery('#final_res').val((total / 1024).toFixed(2));
} else {
jQuery('#final_res').val('');
}
}
FIDDLE
If you are using chrome, then console is your best friend ( https://developers.google.com/chrome-developer-tools/docs/console )
For firefox you have firebug, opera has dragonfly (or something like that ?). Even IE has console now. There you can see all errors popping up.
Ok, so first of all let's clean up this a little bit by wrapping it all in closure (we can now safely use the $ instead of jQuery even if there is namespace conflict outside). Also, we will use single function for both cases, because they are so similar.
!function ($) {
$(".txt-email").keyup(setValue);
$('.rdbtn-style-social').change(function(e) { setValue(e, true) });
function setValue(e, radio) {
if('undefined' === typeof radio) radio = false;
var attr = radio ? 'name' : 'id';
var tmp = e.target[attr].split('-');
var media = tmp[tmp.length - 1];
var txt_value = $("#txt-"+media).val();
var rad_val = $('.rdbtn-style-social[name="rdbtn-'+media+'"]:checked').val();
if (!txt_value.length || !rad_val.length) {
$('#final_res').val('');
return false;
}
var res = (txt_value | 0) * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
$('#final_res').val(MBresult.toFixed(2));
}
}(jQuery);
(variable | 0 is same as parseInt(variable, 10)).
So, long story short: when radio or text gets changed, the function is fired (if it's radio, additional argument is passed). We retrieve whether we want to work on im or fb, then do whatever you want. I changed id of inputs to replace _ with -'s (for split consistency)
Final jsfiddle: http://jsfiddle.net/Misiur/f6cxA/1/

javascript add number of input fields equal to the number of months

I have two input fields with date1 and date2.Below this two fields i need a button that when i press it, will create a number of input fields equal to the number of months between the 2 date fields.
For example i have date1=2012-03-21 and dat2=2012-06-21. It should generate 3 input fields
Can you help me with this one?
Let's assume the HTML looks something like this:
<div id="dateRange">
<input type="text" id="startDate">
<input type="text" id="endDate">
</div>
<div id="monthlyEntries"/>
Now, a month is not a uniform number of days ("30 days has September, April, June,and November..."), so I'm guessing the day portion of the dates don't matter.
Then, the javascript to call on change (or clicking a button, or whatever), would look something like this:
function buildMonthlyEntries() {
var startDate = new Date(document.getElementById('startDate').value);
var endDate = new Date(document.getElementById('endDate').value);
if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
var entryCount = (endDate.getMonth() + endDate.getFullYear()*12) - (startDate.getMonth() + startDate.getFullYear()*12);
var monthlyEntries = document.getElementById('monthlyEntries');
monthlyEntries.innerHTML = "";
for(var i = 0; i < entryCount; i++) {
var textElement = document.createElement('input');
textElement.setAttribute('type', 'text');
textElement.setAttribute('id', 'entry' + i);
monthlyEntries.appendChild(textElement);
}
return null;
}
You can run a loop based upon the difference in the dates. In pseudo code it would be something like
var difference = month2 - month1;
for(x=0;x<difference,x++){
add inputfield;
}

How can I validate multiple different form fields, I have searched and searched for a week

How do I validate dd/mm/yyyy, numeric loan amount, alphabetic first, last name together. I am having trouble using this forum. Thanks for responding so fast!
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
<!--//
function validate(form){
var message = 'Please fill in the following fields:\n\n\t';
for(var i=0; i<form.elements.length; i++){
if(form.elements[i].value.length == 0){
message+= form.elements[i].name.toUpperCase()+'\n\t';
}
}
message+= '\nOK submit incomplete form';
message+= '\nCANCEL return to the form';
message = confirm(message);
if(!message){ return false };
else{ return true };
}
//-->
</script>
</head>
<body>
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name: <input type="text" name="firstname" maxlength="15"><br>
Last Name: <input type="text" name="lastname" maxlength="15"><br>
Birth Date: <input type="text" name="birthdate" maxlength="8"><br>
Loan Amount: <input type="text" name="loanamount" maxlength="6" ><br>
Years: <input type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
</body>
</html>
You can use a function like this. It sets up a regular expression for each type of field and then makes a table that says which regular expression to use for which form element. It uses the named form elements to access the individual values.
function validate(form) {
var nameRE = /^[A-Za-z \.]+$/;
var dateRE = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var amountRE = /^\$?[\d\.,]+$/;
var yearsRE = /^\d+$/;
var formItems = [
{name: "firstname", re: nameRE, tag: "First Name"},
{name: "lastname", re: nameRE, tag: "Last Name"},
{name: "birthdate", re: dateRE, tag: "Birth Date", isDate: true},
{name: "loanamount", re: amountRE, tag: "Loan Amount", min: 50000, max: 750000},
{name: "years", re: yearsRE, tag: "Years", min: 5, max: 30}
];
var item, val, num, month, day, year, valid, matches, incomplete = false;
var msg = 'Please fill in the following fields:\n\n\t';
for (var i = 0; i < formItems.length; i++) {
item = formItems[i];
// strip leading or trailing whitespace
var val = form[item.name].value.replace(/^\s+|\s+$/g, "");
form[item.name].value = val;
// see if it matches the regex
valid = item.re.test(val);
if (valid && item.isDate) {
matches = val.match(item.re);
month = parseInt(matches[1], 10);
day = parseInt(matches[2], 10);
year = parseInt(matches[3], 10);
if (month <= 0 || month > 12 ||
day <= 0 || day >= 31 ||
year < 1900 || year > 2020) {
valid = false;
}
}
if (!valid) {
incomplete = true;
msg += item.tag + '\n\t';
} else {
if (item.min && item.max) {
// clear out non-numeric chars
val = val.replace(/[,\$\s]/g, "");
// convert to a number
num = parseInt(val, 10);
// compare to min and max
if (num < item.min || num > item.max) {
incomplete = true;
msg += item.tag + " (must be between " + item.min + " and " + item.max + ")\n\t";
}
}
}
}
if (incomplete) {
msg += '\nOK submit incomplete form';
msg += '\nCANCEL return to the form';
return(confirm(msg));
}
return(true);
}
​
Working demo here: http://jsfiddle.net/jfriend00/GChEP/
A way to do would be to use classes to know what kind of validation you need for a given input. Also, you can use the title attribute to have a more human-friendly representiation of the input.
Your HTML would then look like:
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name (text only): <input class="validate-text" title="First Name" type="text" name="firstname" maxlength="15"><br>
Last Name (text only): <input class="validate-text" title="Last Name" type="text" name="lastname" maxlength="15"><br>
Birth Date (format dd/mm/yyyy): <input class="validate-date" title="Birth Date" type="text" name="birthdate" maxlength="8"><br>
Loan Amount (US dollars, numeric only): <input class="validate-number" title="Loan Amount" type="text" name="loanamount" maxlength="6" ><br>
Years (numeric only): <input class="validate-number" title="Years" type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
And your JavaScript function (regular expressions seem to be the best way to go):
function validate(f) {
var message=new Array(); //will contain the fields that are misfilled
var reText=new RegExp("^[a-z \-'\.]+$", "i"); //a RegExp to match names: only letters, "-", "'" and "." allowed
var reDate=new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{4}$"); //a RegExp to match a date in the format dd/mm/yyyy
var reNumber=new RegExp("^[0-9]+$"); //a RegExp to match a number
for(var e in f.elements) { //loop on every input of the form
var test=null; //set or reset the RegExp to use for the current input
var input=f.elements[e]; //assign the input to a var (easier to type, not needed)
if(!input.className) //if this input doesn't have any class declared
continue; //then we skip the rest of the loop to keep going with the next input
var classes=input.className.split(" "); //maybe the input has several classes, so we split them in a "classes" array
for(var c in classes) { //we loop on every class of the current input
switch(classes[c]) { //and we test if the current class of the current input is one of the classes we're interested in
case "validate-text": //if it is a text
test=reText; //the variable "test" will contain the RegExp we want to use
break;
case "validate-date": //same for a date
test=reDate;
break;
case "validate-number": //and same for a number
test=reNumber;
break;
default: //if the class is not something we want, nothing to do
break;
} //end switch
} //end classes loop
//here test is either null (no "validate-something" class found for the current input), or it contains the RegExp telling us the kind of input we must validate.
if(test!=null && !input.value.match(test)) { //if it is not null and if the input's value does not match the RegExp
message.push(input.title); //we add the field to the "message" array
}
} //end input loop
if(message.length>0) { //if the arary is not empty, we display a confirm box
return confirm("Please correctly fill the following field(s), or click OK to send an incomplete form:\n"+message.join("\n"));
}
//otherwise, the form is correctly filled, we return true to submit the form
return true;
}

Categories