<!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>
Related
my script
<script>
function hii(Name,Mobile){
let Count=0;
if(Name=="" || Name==null){
document.getElementById('nameerror').style.display='block';
document.getElementById('nameerror').innerHTML='Please Enter Student Name';
Count++;
}
if(Mobile=="" || Mobile==null){
document.getElementById('mobileerror').style.display='block';
document.getElementById('mobileerror').innerHTML='Please Enter Student Mobile';
Count++;
}
if(Count>0){
alert(Count);
return false;
}
}
</script>
Html
<form action="addstudent.php" method="POST" onsubmit="hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
<input type="text" name='name' id="name" placeholder="Enter Student Name"><br><br>
<label for="" id="nameerror" style="display: none;color:red;font-size:small;"></label>
<input type="number" name='mobile' id='mobile' placeholder="Enter Mobile Number"><br><br>
<label for="" id="mobileerror" style="display: none;color:red;font-size:small;"></label>
<input type="submit" value="add">
</form>
im getting count as 2 via alert after submitting form with no data which means there are no errors in my html and javascript code and i cant find any flashing errors in console
What you need is to pass an event to the submit function, and use event.preventDefault() to stop the submission.
function hii(event, Name, Mobile) {
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
action="addstudent.php"
method="POST"
onsubmit="hii(
event,
document.getElementById('name').value,
document.getElementById('mobile').value
)"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>
A better solution is to use addEventListener()
document.querySelector("#form1").addEventListener("submit", hii);
function hii(event) {
const Name = document.querySelector("#name").value;
const Mobile = document.querySelector("#mobile").value;
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
id="form1"
action="addstudent.php"
method="POST"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>
You have to return the value in the handler
<form action="addstudent.php" method="POST" onsubmit="return hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
But better yet is to keep it all together in your script
<form action="addstudent.php" method="POST">
<!-- remove the onsubmit here -->
<input type="submit" value="add">
<!-- we'll put the listener here -->
Then, your script
document.querySelector('input[type="submit"]').addEventListener('click', function(e) {
e.preventDefault();
let Count = 0;
let Name = document.getElementById('name').value;
let Mobile = document.getElementById('mobile').value
if (Name == "" || Name == null) {
document.getElementById('nameerror').style.display = 'block';
document.getElementById('nameerror').innerHTML = 'Please Enter Student Name';
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById('mobileerror').style.display = 'block';
document.getElementById('mobileerror').innerHTML = 'Please Enter Student Mobile';
Count++;
}
if (Count > 0) {
alert(Count);
return false;
}
document.querySelector('form').submit()
})
Im partly there but it would be helpful if any of you guys could send the entire code .
1) Create a form with the below given fields and validate the same using javascript or jquery.
Name : Text box- mandatory
Gender : Radio Button
Age : Text box - Accept Number only - (check for valid Age criteria)
Email : Text box - should be in format example#gmail.com
Website : Text box - should be in format http://www.example.com
Country : Select box with 10 countries
Mobile : Text box - should be a 10 digit number - Display this field only after the user selects a country
Social Media Accounts : Facebook, Google, Twitter (3 checkboxes) - Display Social media section only if selected Country is India
I agree the Terms and Conditions - Checkbox
All fields are mandatory and show error messages for all fields(if not valid)
Only allow to submit form after checking the 'I agree' checkbox.
<!DOCTYPE html>
<html>
<head>
<title>Get Values Of Form Elements Using jQuery</title>
<!-- Include CSS File Here -->
<link rel="stylesheet" href="form_value.css"/>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="form_value.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#social").hide() ;
// $("#hide").click(function(){
// $("social").hide();
// });
// var country = document.getElementByName("country")[0].value;
// if (country.value == "India") {
// $("#show").click(function(){
// $("social").show();
// });
// }
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.email_id.value)) {
alert("You have entered an invalid email address!")
return (false)
}
});
</script>
</head>
<body onload="disableSubmit()">
<div class="container">
<div class="main">
<h2>Get Values Of Form Elements Using jQuery</h2>
<form action="">
<!-- Text -->
<br>
<br>
<label>Name :</label>
<input type="text" id="text" name="name" value=""required/><br>
<!-- Radio Button -->
<br><br><br>
<label>Gender:</label>
<input type="radio" name="male" value="Male">Male
<input type="radio" name="female" value="Female">Female
<br><br>
<!-- Textarea -->
<label>Email :</label>
<input type="text" id="Email" value="" id="Email"/>
<br>
<br><br>
Age: <input type="text" id="Age" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
<br><br>
<label> Website:</label>
<input type="text" id="text" value="" name = "Website" id="website" />
<script type="text/javascript">
function validate() {
if(Website.value.length==0)
{
document.getElementById("Website").innerHTML="Should be in the format http://www.example.com ";
}
}
</script>
<br><br>
<label>Country:</label>
<select class="country" id = "country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
<option value="uae">United Arab Emirates</option>
<option value="germany">Germany</option>
<option value="france">France</option>
<option value="netherlands">Netherlands</option>
<option value="yemen">Yemen</option>
<option value="pakistan">Pakistan</option>
<option value="russia">Russia</option>
</select>
<br><br>
<label>Mobile:</label>
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
<script type="text/javascript">
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>
<br><br>
<div id = "social" >
<p>Social Media Accounts.</p> <input type="checkbox" id="Facebook" value="Facebook"><label for="Facebook"> Facebook</label><br> <input type="checkbox" id="Google" value="Google"><label for="Google"> CSS</label><br> <input type="checkbox" id="Twitter" value="Twitter"><label for="Twitter"> Twitter</label><br>
</div>
<br>
<br>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)"> I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</script>
</form>
</div>
</body>
</html>
this is my js page content form_value.js
$(document).ready(function() {
// Function to get input value.
$('#text_value').click(function() {
var text_value = $("#text").val();
if(text_value=='') {
alert("Enter Some Text In Input Field");
}else{
alert(text_value);
}
});
// Funtion to get checked radio's value.
$('#gender_value').click(function() {
$('#result').empty();
var value = $("form input[type='gender']:checked").val();
if($("form input[type='gender']").is(':checked')) {
$('#result').append("Checked Radio Button Value is :<span> "+ value +" </span>");
}else{
alert(" Please Select any Option ");
}
});
// Get value Onchange radio function.
$('input:gender').change(function(){
var value = $("form input[type='gender']:checked").val();
alert("Value of Changed Radio is : " +value);
});
// Funtion to reset or clear selection.
$('#radio_reset').click(function() {
$('#result').empty();
$("input:radio").attr("checked", false);
});
$('#Email').click(function() {
function validate(Email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za- z]{2,4})$/;
//var address = document.getElementById[email].value;
if (reg.test(email) == false)
{
alert('Should be in the format example#gmail.com');
return (false);
}
}
});
});
$("#Age").click(function() {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
function handleChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 100) input.value = 100;
}
});
</script>
<!DOCTYPE html> <html> <head> <script> function validateForm() {
var name = document.forms["myForm"]["fname"].value;
var gender = document.forms["myForm"]["gender"].value;
var age = document.forms["myForm"]["age"].value;
var a = parseInt(age);
var email = document.forms["myForm"]["email"].value;
var url = document.forms["myForm"]["website"].value;
var country = document.forms["myForm"]["country"].value;
var mobileCountry = document.forms["myForm"]["mobileCountry"].value;
var mcLength = mobileCountry.length;
if (name == "") {
alert("Name Field is mandatory");
return false;
}
if (gender != "male" && gender != "female") {
alert("Atleast one Gender has to be chosen");
return false;
}
if(isNaN(a)){
alert("Age is compulsory and must be a number");
return false;
}
if(email == ""){
alert("Email address is required");
}
else if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
} else{
alert("Email address entered is invalid");
return false;
}
if(/^(ftp|http|https):\/\/[^ "]+$/.test(url)){
} else{
alert("Website url entered is invalid");
return false;
}
if(country != "choose"){
document.getElementById("mc").style.display = "block";
} else{
document.getElementById("mc").style.display = "none";
}
if(mcLength != 10){
alert("Number must be ten digits");
return false;
}
} function displaySocial(){ var social =
document.getElementById("social");
var mc = document.getElementById("mobileCountry");
var country = document.getElementById("country");
var selectedValue = country.options[country.selectedIndex].value;
if (selectedValue != "choose") {
if(selectedValue == "india"){
if(social.style.display = "none"){
social.style.display = "block";
} else{
social.style.display = "none";
} } else{
social.style.display = "none"; }
if(mc.style.display = "none"){
mc.style.display = "block";
} else{
mc.style.display = "none"; } } else{
mc.style.display = "none"; }
} </script> </head> <body> <form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"><br> Gender: <input type="radio" name="gender" value="male"> Male <input type="radio" value="female" name="gender"> Female <br> age: <input type="text" name="age"><br> email: <input type="text" name="email"><br> website: <input type="text" name="website"><br> country: <select type="text" name="country" id="country" onclick="displaySocial()"><option value="choose">--choose--</option><option value="usa">USA</option><option value="uk">UK</option><option value="ng">Nigeria</option><option value="india">India</option></select><br> <span id="mobileCountry" style="display: none;">mobile country: <input type="text" name="mobileCountry"><br></span> <span id="social" style="display: none;">Social Media: <input type="radio" name="gender"> Facebook <input type="radio" name="gender"> Google <input type="radio" name="gender"> Twitter</span> <br> <p> <input type="submit" value="Submit"> </form> <p id="error"></p> </body> </html>
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>
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 have created one form with dynamically created fields. and i have a one check box with unique ID . when user clicks that check box then only those two fields are visible ("name and age"). after clicking only "age" field need to be validate .
here is my code :
$(document).ready(function() {
$('#person').click(function() {
function formValidator(){
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
});
});
$(document).ready(function() {
$('#person').click(function() {
$('#name').attr('required','required');
$('#age').attr('required','required');
});
});
style is :
.selectContainer{
display:none;
}
input[type=checkbox]:checked ~ .selectContainer {
display:block;
}
Html code is:
<form action="" method="post" onSubmit="return formValidator()">
<label for="name">Any Accompanying Person ?:</label>
<input type="checkbox" name="person" id="person" >Yes
<div class="selectContainer">
<br>
<label>Person Details</label>
<p>
<div style="padding-left:70px;">
<input type="button" value="Add Person" onClick="addRow('dataTable')" />
<input type="button" value="Remove Person" onClick="deleteRow('dataTable')" />
</div>
</p>
<table style="padding-left:50px;" id="dataTable" class="form" border="1" >
<tbody>
<tr>
<p>
<td><input type="checkbox" name="chk[]" checked="checked" /></td>
<td>
<label>Name</label>
<input type="text" size="20" name="name[]" id="name" >
</td>
<td>
<label>Age</label>
<input type="text" size="20" name="age[]" id="age" >
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>
</div>
</div>
<h3>Choose Your Payment Option</h3>
<h1>
<div style="padding-left:150px;">
<input type="radio" name="type" value="visa">VISA/MASTER CARD:<br />
<input type="radio" name="type" value="cheque"> CHEQUE/DEMAND DRAFT<br />
<input type="radio" name="type" value="neft">NEFT<br /><br/>
</div>
<label></label>
<input type="submit" name="submit" value="submit"><br />
</form>
problem: the form field "age" is validating successfully by clicking check box ("Any Accompanying Person ?:"). problem is when user try to submit the form without clicking that check box then all so its asking for validate . how get salutation for this ? please help
The validator is within a click handler, which should live outside of that (On the base on the document.ready()).
Also if you just want to validate when that checkbox is clicked you could check it within the javascript and select it via the name of the checkbox (If it has a unique ID each time).
function formValidator(){
var age = document.getElementsByName('age[]');
if($("input[name = 'chk[]']").prop('checked')){
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}
Bring all javascript functions outside of click events. Try this formValidator function
function formValidator(){
if($("#person").is(":checked")) {
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}