I've been looking for 3 hours now for this error, and I can't for the life of me find it. It looks like the onsubmit isn't being called for whatever reason. I'm trying to make sure the user enters a non-negative number in each field
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate(){
var wid1 = document.getElementByName("widget1").value;
var wid2 = document.getElementByName("widget2").value;
var wid3 = document.getElementByName("widget3").value;
if(isNaN(wid1)||isNaN(wid2)||isNaN(wid3)){
alert("all values entered must be numbers");
return false;
}
else if(wid1 < 0 || wid2 < 0 || wid3 < 0){
alert("all values must be greater than zero");
return false;
}
if(wid1+wid2+wid3 > 25){
if(!confirm("you have more than 25 items. Will you accept the additional shipping?")){
return false;
}
}
return true;
}
</script>
</head>
<body>
<form name="order" action="calculations.php" method="get" onsubmit="return validate()">
<p>37AX-L:</p>
<input type="text" name="widget1" value="0" required/>
<br>
<p>42XR-J</p>
<input type="text" name="widget2" value="0" required/>
<br>
<p>93XX-A</p>
<input type="text" name="widget3" value="0" required/>
<br>
<input type="radio" name="State" value="MO" checked>Missouri</input>
<br>
<input type="radio" name="State" value="IL">Illinois</input>
<br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
First, the name of the function is getElementsByName -- Elements is plural.
Second, since this returns a NodeList, you need to index the result to access a specific element, so you can access its value.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate(){
var wid1 = document.getElementsByName("widget1")[0].value;
var wid2 = document.getElementsByName("widget2")[0].value;
var wid3 = document.getElementsByName("widget3")[0].value;
if(isNaN(wid1)||isNaN(wid2)||isNaN(wid3)){
alert("all values entered must be numbers");
return false;
}
else if(wid1 < 0 || wid2 < 0 || wid3 < 0){
alert("all values must be greater than zero");
return false;
}
if(wid1+wid2+wid3 > 25){
if(!confirm("you have more than 25 items. Will you accept the additional shipping?")){
return false;
}
}
return true;
}
</script>
</head>
<body>
<form name="order" action="calculations.php" method="get" onsubmit="return validate()">
<p>37AX-L:</p>
<input type="text" name="widget1" value="0" required/>
<br>
<p>42XR-J</p>
<input type="text" name="widget2" value="0" required/>
<br>
<p>93XX-A</p>
<input type="text" name="widget3" value="0" required/>
<br>
<input type="radio" name="State" value="MO" checked>Missouri</input>
<br>
<input type="radio" name="State" value="IL">Illinois</input>
<br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
You can do it like this
$('#submitIT').submit(function(e){
console.log("callingIT");
var wid1 = document.getElementById("widget1").value;
var wid2 = document.getElementById("widget2").value;
var wid3 = document.getElementById("widget3").value;
if(isNaN(wid1)||isNaN(wid2)||isNaN(wid3)){
console.log("all values entered must be numbers");
e.preventDefault();
}
else if(wid1 < 0 || wid2 < 0 || wid3 < 0){
console.log("all values must be greater than zero");
e.preventDefault();
}
if(wid1+wid2+wid3 > 25){
if(!confirm("you have more than 25 items. Will you accept the additional shipping?")){
e.preventDefault();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="submitIT" name="order" action="calculations.php" method="get">
<p>37AX-L:</p>
<input type="text" id="widget1" value="0" required/>
<br>
<p>42XR-J</p>
<input type="text" id="widget2" value="0" required/>
<br>
<p>93XX-A</p>
<input type="text" id="widget3" value="0" required/>
<br>
<input type="radio" id="State" value="MO" checked>Missouri</input>
<br>
<input type="radio" id="State" value="IL">Illinois</input>
<br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Related
<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
for (var i=0; i <document.frmCustOrders.class.length;i++)
{
if (document.frmCustOrders.class[i].checked ==true)
{
classChecked = true;
vClass = document.frmCustOrders.class[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == -1) //validate customer
{
alert("Please select a customer.")
return false;
}
else if () //validate qty
{
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customer+ "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
}
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>
I'm having issues getting an output box that retrieves the selections on the form.
Also, in one of my if statements I'm assigned to check if the value is between 1 and 999 but I'm drawing a total blank on this. I'm new to coding (Javascript) and this is my first class. Any help with getting this to work would be greatly appreciated.
There are some issues with your code
Redundant else if ()
fsClassChecked variable not declared.
Redundant class when iterate elements document.frmCustOrders.class
Use wrong variable customer should be customerIndex
Wrong condition (customerIndex == -1) change to (customerIndex == "")
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
var fsClassChecked = false;
for (var i=0; i <document.frmCustOrders.length;i++)
{
if (document.frmCustOrders[i].checked ==true)
{
fsClassChecked = true;
vClass = document.frmCustOrders[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == "") //validate customer
{
alert("Please select a customer.")
return false;
}
else if(qty == "" || qty < 1 || qty > 999){
alert("Please enter qty 1-999.")
return false;
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customerIndex + "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
return false;
}
<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="#">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>
I am currently doing a unit task and am having trouble working out why my javascript wont connect. i have tried a few things but cant seem to work it out. Im sure its easy but i just cant work it out. an explanation would be great too.
There are two files one html and one javascript.
Thanks in advance
HTML
<script src="validate.js"></script>
</head>
<body>
<header>
<h1>Rohirrim Ranch Tours</h1>
<h2>Booking Form</h2>
</header>
<form id="regform" method="post"
action="https://mercury.swin.edu.au/it000000/formtest.php"
novalidate="novalidate">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="firstname">Enter your first name</label>
<input type="text" name="firstname" id="firstname" size="20"
/>
</p>
<p><label for="lastname">Enter your last name</label>
<input type="text" name="lastname" id="lastname" size="20" />
</p>
<fieldset id="species">
<legend>Species:</legend>
<label for="human">Human</label>
<input type="radio" name="species" id="human"
value="Human"/><br />
<label for="dwarf">Dwarf</label>
<input type="radio" name="species" id="dwarf"
value="Dwarf" /><br />
<label for="elf">Elf</label>
<input type="radio" name="species" id="elf"
value="Elf" /><br />
<label for="hobbit">Hobbit</label>
<input type="radio" name="species" id="hobbit"
value="Hobbit" /><br />
</fieldset>
<p><label for="age">Enter your age</label>
<input type="text" id="age" name="age" size="5">
</p>
<p><label for="beard">Enter your beard length in inches</label><br />
0 <input type="range" id="beard" name="beard" min="0"
max="60"> 60
</p>
</fieldset>
<fieldset id="trip">
<legend>Your trip:</legend>
<fieldset>
<legend>Booking:</legend>
<label for="1day">1 Day Tour - $200 </label>
<input type="checkbox" name="1day" id="1day"
value="1day" /><br />
<label for="4day">4 Day Tour - $1500</label>
<input type="checkbox" name="4day" id="4day"
value="4day" /><br />
<label for="10day">10 Day Tour - $3000</label>
<input type="checkbox" name="10day" id="10day"
value="10day" /><br />
</fieldset>
<p>
<label for="food">Menu preferences</label>
<select name="food" id="food">
<option value="none">Please select</option>
<option value="lembas">Lembas</option>
<option value="mushrooms">Mushrooms</option>
<option value="ent">Ent Draft</option>
<option value="cram">Cram</option>
</select>
</p>
<p>
<label for="partySize">Number of Travellers</label>
<input type="text" id="partySize" name="partySize"
maxlength="3" size="3" />
</p>
</fieldset>
<div id="bottom"> </div>
<p><input type="submit" value="Book Now!" />
<input type="reset" value="Reset" />
</p>
</form>
JAVASCRIPT
"use strict";
function validate() {
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var errMsg = "";
var result = true;
if (!firstname.match(/^[a-zA-Z]+$/)) {
errMsg = errMsg + "Your first name must only contain alpha
characters\n";
result = false; }
if (!lastname.match(/^[a-zA-Z+$]/)){
errMsg = errMsg + "Your last name must only contain alpha
characters\n";
result = false;
}
var age = document.getElementById("age").value;
if (isNaN(age)){
errMsg = errMsg + "your age must be a number\n"
result = false;
}
else if (age < 18) {
errMsg = errMsg +" your age must be 18 or older\n";
result = false;
}
else if (age >= 10000) {
errMsg = errMsg + "your age must be between 18 and 10000\n";
result = false;
}
var partySize = document.getElementById("partySize").value;
if (isNaN(partySize)) {
errMsg = errMsg + "your age must be a number\n"
result = false;
}
else if (partySize < 1) {
errMsg = errMsg +" party size must be greater than 0\n";
result = false;
}
else if (age >= 100) {
errMsg = errMsg + "your party size must be less or equal to 100\n";
result = false;
}
if (erMsg !== ""){
alert(errMsg);
}
return result;
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
I see your error erMsg instead of errMsg
if (erMsg !== ""){
alert(errMsg);
}
and also add event.preventDefault(); at the beginning of the validate function
Your js reference is fine :)
Try setting the Javascript url as './validate.js'
I currently have been working on this code and I can't seem to figure it out. I am planning to make it so that if the radio button is pressed that shipping is not free, that an input field pops up to specifying what the addition cost will be using DOM. I am also trying to figure out how to add text to describe the input field, and to validate the input field.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
c++;
alert("Added Text Box");
}
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id = "tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked /> Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;"/> No
<p class="boldParagraph" id = "emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br><br>
<button>Submit</button>
</form>
</body>
</html>
Create a label element and populate text using innerHTML. and then append to DOM.
Example Snippet:
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : ";
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
c++;
alert("Added Text Box");
}
}
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button>Submit</button>
</form>
OR
You can keep the text box hidden and show it when user clicks no. Also, apply validations only when no is selected for shipment radio button.
I suggest use jQuery, see the snippet below:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
var radioButtons = $("[name=tip3]");
radioButtons.on("change", function() {
if ($("[name=tip3]:checked").val() == "3") {
$("#shipmentDetail").hide();
} else {
$("#shipmentDetail").show();
}
})
$("#submit").on("click", function() {
var flag = true;
if ($("[name=tip3]:checked").val() == "4") {
if ($("#shipmentDetail").val() == "") {
flag = false;
alert("enter some value");
}
}
//other validations here
if (flag) {
$("#form").submit()
}
})
#shipmentDetail {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="#" method="post">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" />No
<label id="shipmentDetail" for="price">Shipment Cost:
<input id="price" type="text" value="" />
</label>
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button id="submit">Submit</button>
</form>
replace
alert("Added Text Box");
with:
var additional_fees = prompt("Type in");
x.setAttribute("value", additional_fees)
I´m working in a payment gateway where the user Name the Price for my digital books. An input box (to text the price) and a "Pay now" button are displayed. BUT:
If the price is less than 0.50 the payment button disapear and the download button appear
If the user introduce a "," instead a "." a box is displayed (please, enter a valid number)
Here is the form with the input box:
<form id="hikashop_paypal_form" name="hikashop_paypal_form" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="business" value="X" />
<input type="hidden" name="item_name_1" value="X" />
<input id="amount_1" name="amount_1" class="amount_1"/></form>
Pay Now button (it should be hiden if 1 is true)
<div id="PayNow" class="PayNow">
<input id="PayNow_button" type="submit" class="btn btn-primary" value="Pay now" name="" />
</div>
Download Now Button (it should be shown if 1 is true)
<div id="downloadNow" class="downloadNow">
Download now
</div>
Info box (It should be shown if 2 is true)
<div id="info" class="info">
Enter a valid number
</div>
And the question is: How can I do it?
I supose the solution passes by using javascript, but I don´t know how exactly... Thanks for you time...
I don´t know how, but it works for me:
Try it here: IBIZA! Book Download
<form id="pplaunch" action="https://www.paypal.com/cgi-bin/webscr" method="POST">
<input type="hidden" name="cmd" value="_xclick">
<input id="issueid" name="issueid" type="hidden" value="ARCHIVE NAME">
<input type="hidden" id="currency" name="currency" value="EUR">
<input type="hidden" name="business" value="YOUR PAYPAL ID" />
<input type="hidden" value="0" name="test_ipn"></input>
<input type="hidden" name="item_name" value="PRODUC NAME">
<input type="hidden" value="1" name="no_shipping"></input>
<input type="hidden" value="0" name="no_note"></input>
<input type="hidden" value="utf-8" name="charset"></input>
<input type="hidden" value="Super" name="first_name"></input>
<input type="hidden" value="http://www.YOURWEBSITE.com/return" name="return"></input>
<input type="hidden" value="http://www.OURWEBSITE.com/cancel" name="cancel_return"></input>
<div class="nameprice" style="float:left;margin-right:15px;>
<span style="font-size:small;">Name your price: </span><input id="amount" name="amount" size="6" maxlength="5" type="text"> <span style="font-size:small;color:#ccc;">From 0.00€</span>
</div>
<div id="pricerror"></div>
<div class="buttonspace">
<button id="buybutton" class="buybutton" type="button">Checkout</button>
<div id="descargaGratisMensaje"></div>
<div style="display: block;" class="pay">
</div>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
function newPopup(url, width, height){
popupWindow = window.open(url,'_blank','height='+height+',width='+width+',left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes');
return false;
}
function displaybutton(displayclass){
if(displayclass == 'pay'){
$('.pay').css('display','block');
$('#pplaunch').attr('action', 'https://www.paypal.com/cgi-binwebscr');
$('#buybutton').html('Pagar');
}else{
$('.pay').css('display','none');
$('#pplaunch').attr('action', 'http://www.example.com/archive/'+$('#issueid').val());
$('#buybutton').html('Descargar');
$('#descargaGratisMensaje').html('Un Me Gusta podría ser un buen intercambio');
}
}
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n) && (n.search(/0x/i)<0);
}
function price(n){
// return null if n is not a price, or n rounded to 2 dec. places
if(!isNumber(n)){
// maybe the user entered a comma as a decimal separator
n = n.replace(/,/g,'.');
if(!isNumber(n)){
return null;
}
}
// now we know it is a number, round it up to 2 dec. places
return Math.round(parseFloat(n)*100)/100;
}
function pricecheck(){
var data = $.trim($('#amount').val());
var myprice = price(data);
if(myprice == null){
if(data == ''){
$('#pricerror').html('');
}else{
$('#pricerror').html('Please enter a price.');
}
displaybutton('pay');
return false;
}
if(myprice == 0){
$('#pricerror').html('');
displaybutton('nopay');
}else if(myprice < 0.5){
$('#pricerror').html('The minimum price is '+currencysymbol+'0.50.
Please enter either zero, or at least '+currencysymbol+'0.50.');
displaybutton('pay');
}else{
$('#pricerror').html('');
displaybutton('pay');
}
jQuery('.content').hide();
}
var currencysymbol = '$';
$.getScript('//www.geoplugin.ne/javascript.gp?ref=panelsyndicate.com', function() {
if(geoplugin_continentCode() != 'EU'){return;}
$('#currency').val('EUR');
currencysymbol = '€';
$('.currencysymbol').html(currencysymbol);
});
$(document).ready(function(){
var dialog = $('#modal').dialog({
title: 'IBIZA!'
, autoOpen: false
, closeText: ''
, modal: true
, resizable: false
, width: 500
});
$('#buybutton').click(function() {
$('#pplaunch').submit();
});
$('#pplaunch').submit(function() {
var myprice = price($.trim($('#amount').val()));
if((myprice != 0) && ((myprice == null) || (myprice < 0.5))){
$('#pricerror').html('Please enter your price.');
$('#amount').focus();
return false;
}
});
$('.modaltrigger').click(function() {
var issueid = $(this).attr('href').substr(1);
$('#issueid').val(issueid); // Comic ID
$('#include_a_message_to').html(issues[issueid].include_a_message_to); // Destinee of the message
dialog.dialog('option', 'title', issues[issueid].title); // Title of the comic
$('#issuelangs').html(issues[issueid].langs); // Languages in which the comic is available
dialog.dialog('option', 'position', { my: "center", at: "center", of: window });
dialog.dialog('open');
// prevent the default action, e.g., following a link
pricecheck();
return false;
});
$('#amount').bind('input propertychange', function() {
pricecheck();
});
$('.custommsg').hide();
$('.msgtrigger').click(function() {
var cmsg = $('.custommsg');
if(cmsg.is(':visible')){
cmsg.hide();
$('.sendmsg').show();
}else{
$('.sendmsg').hide();
cmsg.show();
$('.msgtxt').focus();
}
return false;
});
$('.msgtxt').keyup(function(){
if($(this).val().length > maxlength){
$(this).val($(this).val().substr(0, maxlength));
}
var remaining = maxlength - $(this).val().length;
$('#msgtxtnumcharsleft').text(remaining);
});
var maxlength = 200;
var remaining = maxlength - $('.msgtxt').val().length;
$('#msgtxtnumcharsleft').text(remaining);
});
</script>
I am trying to validate the form when any special characters or number press in the text box it should trigger an error as alert.
<html>
<head>
<script>
function demoMatchClick() {
var reg = new RegExp("[a-z]|[A-Z]");
if (document.form.name.value.match(reg)) {
alert("Successful match");
} else {
alert("Not a match");
}
}
</script>
</head>
<body >
<form onSubmit="alert('submit')" name="form">
<input type="text" name="name" value="name" onkeyup="demoMatchClick();"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Replace your code with This:
function demoMatchClick(inputtxt) {
var letters = /^[A-Za-z]+$/;
var val = inputtxt.value.replace(/\s/g, '');
if (val.match(letters)) {
alert("Successful match");
} else {
alert("Not a match");
}
}
<html>
<body >
<form onSubmit="alert('submit')" name="form">
<input type="text" name="name" value="name" onkeyup="demoMatchClick(this);"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
<input type="text" name="name" value="name" pattern="[a-zA-Z]+" title="Letters only!"/>
Done. Demo