How to check for links in textbox JavaScript [duplicate] - javascript

This question already has answers here:
How to look for a word in textbox in JavaScript
(3 answers)
Closed 8 years ago.
If there is a link in a textbox then JavaScript will redirect the user to the link when they press a button. For example if the textbox has www.google.com in it the JavaScript would see the "www." and it would play a function which redirects the user to the link entered. Here is my code:
JavaScript:
function showAlert() {
var txtCtrl = document.getElementById("textbox1");
var txtVal = txtCtrl.value;
var txtValUpper = txtVal.toUpperCase();
var txtValLower = txtVal.toLowerCase();
if (txtVal == '') {
alert('Please fill in the text box. For a list of commands type "Help" into the text box.');
} else if (txtValUpper == 'start' || txtValLower == 'start') {
alert('Hello. What would you like me to do?');
} else if (txtValUpper.indexOf("weather") != -1 || txtValLower.indexOf("weather") != -1) {
window.location = "https://www.google.com/#q=weather";
} else if (txtValUpper.indexOf("time") != -1 || txtValLower.indexOf("time") != -1) {
alert('The current time according to your computer is' + formatTime(new Date()));
} else if (txtValUpper.indexOf("help") != -1 || txtValLower.indexOf("help") != -1) {
window.location = "help/index.html";
} else if (txtValUpper.indexOf("donate") != -1 || txtValLower.indexOf("donate") != -1) {
window.location = "donate/index.html";
} else {
alert('Sorry, I do not reconise that command. For a list of commands, type "Help" into the text box.');
}
}
//Show time in 24hour format
function showTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
return [h, m].join(':')
}
//Show time in 12hour format
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "PM" : "AM"].join(" ");
}
return formatted;
}
})();
And HTML:
<!doctype html>
<html>
<head>
<title>Random Project</title>
</head>
<body>
<div class="container">
<img class="logo" src="logo.png" width="450" height="110" alt="Random Project">
<input type="text" name="textbox1" value="" spellcheck="false" dir="ltr" placeholder="Type here" id="textbox1"><br>
<button id="button1" name="button1" aria-label="Help me" onClick="showAlert();">
<span id="button1_text">Help me</span>
</button>
<div class="separator"></div>
<span class="information">© Copyright DemDevs 2013. All rights reserved. Made by Omar Latreche<br>Donate now</span>
<div class="tip">
<span class="tip">Tip: </span><span class="tip_text">The commands are NOT case sensitive</span>
</div>
<div class="example">
<span class="example">Example: </span><span class="tip_text">Show me the weather or What is the current time</span>
</div>
</div>
<div class=""></div>
</body>
</html>
Any help will be greatly appreciated.
Thanks, Omar!

Use pattern matching for this:
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var t = 'www.google.com'; // you would change this to dynamically check text input
if(t.match(regex))
{
// Execute your code
}

Related

Script isn't working in html

This is a very basic piece of code. I am attempting to collect a number from the user and change parts of the page based on that. Here is my code
<body>
<h1> <span class ="magicNum" id ="magic"> ? </span></h1>
<h2><span id ="output">Result</span></h2>
<h2> Score: <span id = "score"> 0 </span></h2>
<div class="wrapper" >
<input type="text" id="input1" placeholder="Enter your guess:"/>
<button onclick="submit()"> Submit </button></div> <br>
<div class="wrapper" > <button id ="playAgain" onclick="restart()"> Play Again? </button></div>
<script type="text/javascript">
var magicNumber;
var points = 0;
function submit(){
var text=document.getElementById('input1').value;
var question=document.getElementById('magic');
var output=document.getElementById('output');
var counter=document.getElementById('score');
magicNumber=Math.floor((Math.random() * 10) + 1);
question.innerHTML = magicNumber;
if ((magicNumber == text) or ((text + 1) == magicNumber) or ((text - 1) == magicNumber)) {
points++;
counter.innerHTML = points;
output.innerHTML = You Got Lucky!;
} else {
output.innerHTML = Bad luck. Try again;
}
}
function restart() {
var text=document.getElementById('input1').value;
var question=document.getElementById('magic');
var output=document.getElementById('output');
text.innerHTML= result;
question.innerHTML=?;
output.innerHTML=;
}
</script>
</body>
My previous errors in similar scenarios were due to misspellings but I can't seem to find any of those cases. Is it because I am comparing numbers in the wrong way or not initializaing my variables properly or not retreiving items properly or soemthing else entirely? I can't figure out how to debug.
Edit: The script isn't working at all. I enter a number into my field and press the submit button which should trigger submit() but there is no result or change.
There are many errors in your code;
string not in quote ("this is a string")
The or in js is ||
In your restart function result is used but it is not defined. So instead of text.innerHTML= result you can do text.innerHTML= ""(it is all depend on what you want to do, but at least now it is syntactically correct) ;
<h1> <span class ="magicNum" id ="magic"> ? </span></h1>
<h2><span id ="output">Result</span></h2>
<h2> Score: <span id = "score"> 0 </span></h2>
<div class="wrapper" >
<input type="text" id="input1" placeholder="Enter your guess:"/>
<button onclick="submit()"> Submit </button></div> <br>
<div class="wrapper" > <button id ="playAgain" onclick="restart()"> Play Again? </button></div>
<script type="text/javascript">
var magicNumber;
var points = 0;
function submit(){
var text=document.getElementById('input1').value;
var question=document.getElementById('magic');
var output=document.getElementById('output');
var counter=document.getElementById('score');
magicNumber=Math.floor((Math.random() * 10) + 1);
question.innerHTML = magicNumber;
if ((magicNumber == text) || ((text + 1) == magicNumber) || ((text - 1) == magicNumber)) {
points++;
counter.innerHTML = points;
output.innerHTML = "You Got Lucky!";
} else {
output.innerHTML = "Bad luck. Try again";
}
}
function restart() {
var text=document.getElementById('input1').value;
var question=document.getElementById('magic');
var output=document.getElementById('output');
text.innerHTML= "";
question.innerHTML="?";
//output.innerHTML=;
}
</script>
In Javascript there is no "or" , you can use "||" as OR logical operator , https://www.w3schools.com/js/js_operators.asp
Updated your code there was a lot of mistakes, undefined variables, string were not between quotes and and so on:
<body>
<h1> <span class ="magicNum" id ="magic"> ? </span></h1>
<h2><span id ="output">Result</span></h2>
<h2> Score: <span id = "score"> 0 </span></h2>
<div class="wrapper" >
<input type="text" id="input1" placeholder="Enter your guess:"/>
<button onclick="submit()"> Submit </button></div> <br>
<div class="wrapper" > <button id ="playAgain" onclick="restart()"> Play Again? </button></div>
<script type="text/javascript">
var magicNumber;
var points = 0;
function submit(){
var text=document.getElementById('input1').value;
var question=document.getElementById('magic');
var output=document.getElementById('output');
var counter=document.getElementById('score');
magicNumber=Math.floor((Math.random() * 10) + 1);
question.innerHTML = magicNumber;
if ((magicNumber == text) || ((text + 1) == magicNumber) || ((text - 1) == magicNumber)) {
points++;
counter.innerHTML = points;
output.innerHTML = "You Got Lucky!";
} else {
output.innerHTML = "Bad luck. Try again";
}
}
function restart() {
var text=document.getElementById('input1').value;
var question=document.getElementById('magic');
var output=document.getElementById('output');
var result=document.getElementById('magic'); // was it the expected behavior ?
text.innerHTML= result;
question.innerHTML="?";
output.innerHTML= "";
}
</script>
</body>
https://jsfiddle.net/yg3hdfjw/1/

Verify ID Number using javascript

I am trying to verify the south african ID NUMBER. I am not fluent with javascript.
I have the following code:
The HTML and Javascript
<html>
<head>
<script src="jquery-1.12.0.min.js"></script>
<title>the man</title>
<script>
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
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();
var fullDate = id_date + "-" + id_month + 1 + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
</script>
</head>
The Body:
<body>
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
</body>
</html>
Unfortunately I am not getting any error output. Please Assist
If this is the entire code, you are missing the closing head tag after script, I ran it and it worked as far as displaying different error messages with that cleaned up.
Edit- also added compiled code below which has document.ready shorthand.
<!DOCTYPE html>
<head>
<title>the man</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
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();
var fullDate = id_date + "-" + id_month + 1 + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
});
</script>
</head>
<body>
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
</body>
</html>
There were two proposed solutions and both of them would work.
First to remove script from the head section. (I guess you both placed </head> in different places, and that's why for one of you the submit attached correctly but not for the other)
<HTML>
<head>
<title>the man</title>
</head>
<body>
<script src="jquery-1.12.0.min.js"></script>
<script> //your code</script>
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
</body>
</html>
And the other to wrap all your code in
$(document).ready(wrapper);
function wrapper(){
function Validate() {
//your code
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
}
Why does the first solution work? First we render <head> so when your code is run
$('#idCheck').submit(Validate);
cannot be attached because the dom element does not exist yet. If we place the code in the execution is delayed.
Why does the second solution work? We wait until all page is rendered; only then do we execute our function that contains the same event attachment ($('#idCheck').submit(Validate);).

auto tabbing on the first textbox isnt working

the following is code is used to create a credit card. My only promblem is that auto tabbing doesnt work for my textbox with the id of card.i have a external file for the auto tabbing and i have attached the code under the html code.Thanks in advance.
<head>
<title>Credit Card</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script src="jquery.autotab.js"></script>
<script src="Jstepper.js"></script>
</head>
</body oncopy="return false" oncut="return false" onpaste="return false">
<style>
#Month{
width: 20px;
}
#Year{
width: 40px;
}
#Cvc{
width: 30px;
}
</style>
<p>Payment:
Credit card<input type="radio" id='radio_1' name='payment' value="credit">
<div class="text1">
<form name="cardForm" method="post">
<p>Card number:<input type="text" name="FirstField" id='card' value=""
onKeyup="autotab(this,document.cardForm.SecondField)" maxlength=16 >
Expiration: Month:-<input type="text" name="SecondField" id='Month' value=""
onKeyup="autotab(this,document.cardForm.ThirdField)" maxlength=2 >
Year:-<input type="text" id='Year' name="ThirdField" value="" onKeyup="autotab(this, document.cardForm.FourthField)"maxlength=4></p>
3 digit CVC:-<input type="text" name="FourthField" id='Cvc' value="" maxlength=3></p>
</form>
</div>
</body>
<!--Jump when expiration number is typed-->
<!--month and year-->
<!--exp date has to greater than or equal to current date -->
<!--on every keypress check if the length is 16-->
<!--macthes-->
<!-- Import numeric from src folder-->
<script src="numeric.js"></script>
<script>
//autotab doesnt work for the first feild
//can still copy and paste text
$(document).ready(function () {
$(".text1").hide();
$("#radio_1").click(function () {
<!--passes card id to keypress function-->
$('#card').keypress();
//disable copy and paste
$('#card').bind();
$('#Month').keypress();
$('#Month').bind();
$('#Month').jStepper({minValue:0, maxValue:12});
$('#Year').keypress();
$('#Year').bind();
$('#Cvc').keypress();
$('#Cvc').bind();
$(".text1").show();
});
});
</script>
<html>
/*
Auto tabbing script- By JavaScriptKit.com
http://www.javascriptkit.com
This credit MUST stay intact for use
*/
function autotab(original,destination){
if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
destination.focus()
}
my isnumeric file
$(this).keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
//check for the type of credit card and prints to console
$(this).keypress(function (e) {
var input = document.getElementById('card');
input.onkeyup = function() {
if(input.value.length == 16){
var str = input.value;
var VisaRegx = /^4[0-9]{6,}$/i;
var Visafound = str.match(VisaRegx);
if(Visafound != null){
console.log("Visa Found");
}
var MasterRegx = /^5[1-5][0-9]{5,}$/i;
var Masterfound = str.match(MasterRegx);
if(Masterfound != null){
console.log("Master Card Found");
}
var AmericanExpressRegx = /^3[47][0-9]{5,}$/i;
var AmericanExpressfound = str.match(AmericanExpressRegx);
if(AmericanExpressfound != null){
console.log("American Express Card Found");
}
//^(?:2131|1800|35[0-9]{3})[0-9]{3,}$
var DinersClubRegx = /^3(?:0[0-5]|[68][0-9])[0-9]{4,}$/i;
var DinersClubfound = str.match(DinersClubRegx);
if(DinersClubfound != null){
console.log("Diners Club Card Found");
}
var DiscoverRegx = /^6(?:011|5[0-9]{2})[0-9]{3,}$/i;
var Discoverfound = str.match(DiscoverRegx);
if(Discoverfound != null){
console.log("Discover Card Found");
}
var JcbRegx = /^(?:2131|1800|35[0-9]{3})[0-9]{3,}$/i;
var Jcbfound = str.match(JcbRegx);
if(Jcbfound != null){
console.log("Jcb Card Found");
}
}
}
});
//checks for credit card expiration
$(this).keypress(function (e) {
var Monthinput = document.getElementById('Month').value;
var Yearinput = document.getElementById('Year').value;
var today = new Date();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(Yearinput.length == 4){
if(yyyy > Yearinput){
console.log("The card is expired cause of the year");
}
}
if(Yearinput.length == 4 && Monthinput.length == 2){
if(yyyy == Yearinput && mm > Monthinput){
console.log("The card is expired cause of the current month");
}
}
});
//Disable copy and paste
$(this).bind("cut copy paste",function(e) {
e.preventDefault();
});

Can't get JQuery to append some html and a value

I'm trying to create a script to keep a history track of three for a random number generator. (this is all for practice to take more advance approach) but I for some reason cannot get jQuery to Append a new html table/row after the code starts executing from a different JS file. however everything seems to go according to plan besides the part when I am trying to add the row into the table. I have a jsfiddle here:
http://jsfiddle.net/e3ey2a3s/2/
Here is my code however:
convert.js (the generator)
var min, max, setDol = false,
pArry = [];
function chooseRandom() {
min = prompt('whats the max value?', 'max');
max = prompt('whats the min value?', 'min');
return convertType(min, max);
}
function convertType(min, max) {
if (typeof min === 'string' || typeof max === 'string') {
document.getElementById('convert').innerHTML = "converting strings to numbers..."
parseInt(min);
parseInt(max);
}
return getRandom(min, max);
}
function getRandom(min, max) {
if (isNaN(min) || isNaN(max)) {
borked();
} else {
return amtFixed(Math.random() * (max - min) + min);
}
}
function amtFixed(amt) {
if (amt >= 0 && amt <= 10) {
document.getElementById('text').innerHTML = "Our number is " + amt + " which is between 0 and 10";
} else if (amt >= 11 && amt <= 20) {
document.getElementById("text").innerHTML = "Our number is " + amt + " which is between 11 and 20";
} else {
document.getElementById("text").innerHTML = "Our number is " + amt + " which is greater than 20. huh.";
}
var fixed = Number(amt).toFixed(2);
return convertFix(fixed);
};
function convertFix(fixed) {
if (typeof fixed === 'string') {
fixed = (fixed / 1);
document.getElementById("fixed").innerHTML = typeof fixed + " " + fixed + " converted down to two decimals.";
setDol = confirm("Convert our amount to a dollar amount?");
} else {
console.log('Failed to convert...');
}
return success(fixed);
};
function borked() {
var broke = false;
alert("You must not of entered a proper number... That sucks :/");
var broke = confirm("Do you want to retry?");
if (broke) {
return chooseRandom();
} else {
return document.getElementById("text").innerHTML = "I r broked :(";
}
}
function success(num) {
var amtHist = [];
if (setDol) {
$("#price").append('$' + num + ' Set fixed to a dollar amount!');
pArry.push(num);
return buildHistory(pArry);
} else {
$("#price").empty().append("Our fixed value is: " + num);
pArry.push(num);
return buildHistory(pArry);
}
}
After this script finishes up success() send the finished array over to my data.js function buildHistory() which looks like this:
buildHistory = function(arr) {
var t, i, _this = this,
numEls = 0,
a = arr;
var objLen = holdObj.History.length;
table = $('table.history');
//Let's do our loops to check and set history data
//We need to get our history data so we can make sure not to re print old data.
for (t = 0; t <= objLen; t++) {
for (i = 0; i < a.length; i++) {
x = objLen[t];
if ($.inArray(x, a) === -1) {
//Alright now we build onto the history table
$('table.history').append('<tr><td>' + a[i] + '</td></tr>');
var cell = table.find('td');
cell.addClass('hist' + numEls);
numEls++;
holdObj.History.push(a[i]);
} else {
break;
}
}
}
// Let's remove the oldest value once the table exceeds 3 or 4.
if (objLen > 3 && numEls > 3) {
var tmp = table.find('hist_3');
table.remove(tmp);
holdObj.History.pop();
}
}
This is all still in the makes so nothing is really finalized here, I am probably just overlooking a simple solution.
Here is my HTML:
<html>
<head>
<script type="text/javascript" src="../source/libs/jQuery-1.8.3.min.js"></script>
<title>Index</title>
</head>
<body>
<p>This is just some filler content lol.</p>
<p>Let's run some scripts! Click the buttons!</p>
<div class="math">
<p id="convert"></p>
<p id="text"></p>
<p id="fixed"></p>
<p id="price"></p>
<table id="history">
<tr>
<th>History</th>
</tr>
<tr>
<td id="hist"> Value #1</td>
</tr>
</table>
</div>
<button class="scrBtn">Click to start Script</button>
<div id="date"></div>
<button class="dateBtn">Get Date</button>
<div class="person">
<div class="pTitle">
<div class="pBody">
<div class="fName">Name: </div>
<div class="age">Age: </div>
<div class="height">Height: </div>
<div class="eyecolor">Eye Color: </div>
<div class="sex">Sex: </div>
This is where our person should go.
</div>
</div>
</div>
<a href="view/Form/personForm.html">
<button class="pBtn">Get Info</button>
</a>
<div class="bRowLeft">test
</div>
<div class="tRowLeft">test
</div>
</body>
<script type="text/javascript" src="../source/model/data.js"></script>
<script type="text/javascript" src="../source/model/convert.js"></script>
<script type="text/javascript" src="../source/model/button.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</html>
Sorry for such a long post but I am trying to explore as much as I can.
(The code is activated via jQuery with button.js)
$(document).ready(function() {
$('.scrBtn').click(function() {
chooseRandom();
});
});
Thanks again, let me know if anymore information is needed.
$('table.history') - you dont have a <table class="history"> element.
Try this:
table = $("#history");
and same where you append.

date validation in javascript using .js files

I am having a ini.jsp page for creating a form for adding two text fields to input date and then using javascript in the ini.jsp page itself to validate those dates. I now have some library files(calendar.js, calendar-en.js, calendar-setup.js, calendar_1.png, calendar_system.css).
Now my question is how to I link these files to javascript (I am using ECLIPSE IDE) so that it displays calendar beside the textboxes for date in the format dd/mm/yyyy. . .
I have gone through lots of stuff, tried doing those but really couldn't get the expected output.
Below is the code that i have implemented so far
<html lang="en">
<head>
<style type="text/css" src="../datePickers/calendar-system.css">
</style>
</head>
<body>
<script language="Javascript" src="../Scripts/calendar.js"></script>
<h1>Report Generation</h1>
<div style="margin: 0 auto; width: 100%; text-align: left">
<form name="date" action="<c:url value="cli.htm"/>"
method="post" onSubmit="return ValidateForm()">
<fieldset>
<legend>Please enter Start Date and End Date</legend>
<div style="text-align: center; margin: 150px auto 100px auto;">
<label for="dateFrom">Start Date:</label>
<font color="#CC0000"><b>(dd/mm /yyyy)</b></font>
<input type="text" name="dateFrom" maxlength="25" size="25"
id="dateFrom" />
<img src = "../Images/calendar_1.png" onclick="javascript:Calendar.setup(inputField,ifFormat,button) style="cursor: pointer" />
</div>
<div style="text-align: center; margin: 150px auto 100px auto;">
<label for="dateTo">End Date:</label>
<font color="#CC0000"><b>(dd/mm/yyyy)</b></font>
<input type="text" name="dateTo" maxlength="25" size="25"
id="dateTo" />
</div>
<div>
<input type="submit" value="Generate Report" align="center" />
</div>
</form>
</div>
<script language="Javascript" >
var dtCh= "/";
var minYear=1900;
var maxYear=2500;
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Checking that the current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9")))
return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function daysInFebruary (year){
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}
function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strDay=dtStr.substring(0,pos1)
var strMonth=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr = strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : dd/mm/yyyy");
return false;
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month");
return false;
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day");
return false;
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
return false;
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))== false){
alert("Please enter a valid date");
return false;
}
return true;
}
function ValidateForm(){
var dt1=document.date.dateFrom
var dt2=document.date.dateTo
if (!isDate(dt1.value)){
dt1.value='';
dt1.focus();
return false;
}
if(!isDate(dt2.value)){
dt2.value='';
dt2.focus();
return false;
}
return true
}
}
</script>
</body>
</html>
I want changes in code to be done as:
The code should initialises the calendar object and links an image to a text field (using their IDs) to respond to a click.
Calendar.setup(
{
inputField : "dateFrom", // ID of the input field
ifFormat : "%d/%m/%Y", // the date format
button : "imgCal" // ID of the calendar image
}
);
should I really need to create a calendar object if so, can I know where. Also, where should I place the Calendar.setup code in my jsp page?
Can someone please help me sort out this issue...
Quick suggestion: Have you tried looking into this page.
Easy to implement and you can see the demo as well.
http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/
**
Now, Looking into your code; can you please flick the calender.setup(foo1, foo2...) function implementation? (Is this your customized library?)
Thanks,
i am trying to validate date with **YYYY\MM\DD of format using HTML and Javascript
Hope its Help you...
try to yourself...
< script type = "text/javascript" >
function valdate() {
var regdate = /^(19[0-9][0-9]|20[0-9][0-9])\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])$/;
if (form1.txtdate.value.match(regdate)) {
return true;
} else {
alert("! please Enter the Date in this Format 'YYYY/MM/DD'");
form1.txtdate.value = "";
form1.txtdate.focus();
return false;
}
} < /script>
<from="form1" method="post" action="">
<input name="txtdate" type="text" onblur="valdate()" maxlength="10" required />
</form>
if helpful so make voting....

Categories

Resources