I am really new to jquery and javascript... I want to use the four variables in myairFunction to calculate something and those four variables store values retrieved from database.
How can make use of these values in my function ?
The function does not work. even if i test as follows, it printed nothing. where's wrong ?
$("#airradio1").click(function(){
$("#aircalc").click(function(){
$("#airanswer").html(lat1);
});
});
html :
<div id="calculator">
<h3>Air Travel</h3>
<div id="air">
<input type="radio" name="frm" id="airradio1" checked="check" onclick="setairform1()">Enter Individual flights(more accurate) <br>
<input type="radio" name="frm" id="airradio2" onclick="setairform2()">Enter numbers of flight(faster)<br>
<form id="airform1">
<div>
From
<div class="textinput">
<input type="text" id="dept" name="departure" placeholder="City name or aiport code" >
</div>
</div>
<div>
To
<div>
<input type="text" id="dest" placeholder="City name or airport code" >
</div>
</div>
<div>
Via
<div>
<input type="text" id="via" placeholder="City name or airport code" >
</div>
</div>
<div>
<div>
<input type="radio" name="trip" value="roundtrip">Round-trip <br>
<input type="radio" name="trip" value="oneway">One-way
</div>
</div>
<div>
Number of flights/passengers
<input type="text">
</div>
<div>
Class
<select style="width: 82px">
<option selected="selected">Economy</option>
<option>Business</option>
<option>First</option>
</select>
</div>
<div><button type="button" id="aircalc" >calculate</button></div>
<div id="result">
<div id="totalresult"> Total Emission:
<p id="airanswer">0 </p> lbs CO<sub>2</sub> </div>
</div>
here is the php :
$strSQL = "SELECT display, lat, longi FROM airport WHERE display LIKE '$term%'";
$rs = mysql_query($strSQL);
$json=array();
while($row = mysql_fetch_array($rs)){
$json[]=array('value'=>$row['display'],
'label'=>$row['display'],
'lat'=>$row['lat'],
'longi'=>$row['longi']
);
}
echo json_encode($json);
javascript :
$(document).ready(function(){
var lat1;
var long1;
var lat2;
var long2;
var a;
$('#dept').autocomplete({
source:'source.php',
minLength:1,
select:function(evt,ui){
lat1=ui.item.lat;
long1=ui.item.longi;
}
});
$('#dest').autocomplete({
source:'source.php',
minLength:1,
select:function(evt,ui){
lat2=ui.item.lat;
long2=ui.item.longi;
}
});
$("#airradio1").click(function(){
$("#aircalc").click(function(){
myairFunction1(lat1,lat2,long1,long2);
});
});
$('#via').autocomplete({
source:'source.php',
minLength:1
});
});
function myairFunction1(lat1,lat2,long1,long2){
co2 = lat1+lat2+long1+long2;
document.getElementById("airanswer").innerHTML = co2;
}
without seeing the information requested in the comments its nearly impossible to say what's going wrong. but the nested click function looks suspect. if you can target the element directly then why the nested listener?
$("#airradio1").click(function(){
$("#aircalc").click(function(){
myairFunction1(lat1,lat2,long1,long2);
});
});
instead just add the event listener directly to the #aircalc element:
$("#aircalc").click(function(){
myairFunction1(lat1,lat2,long1,long2);
});
Related
So I have a form with two identical group of inputs that represent education info. There could be more than two as I want to include a button to create a new group so the user can put all his education background like in LinkedIn.
<form id="formCV" action="">
<div id="educationContainer">
<!-- First Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
<!-- Second Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
</div>
</form>
Now, if I use the FormData API to get the form data like this:
for(let entry of formData.entries()){
console.log(entry);
}
I get the following output:
(2) ["institutionName", "Harvard"]
(2) ["courseName", "Web Development"]
(2) ["startDate", "2000-11"]
(2) ["endDate", "2008-11"]
(2) ["institutionName", "Oxford"]
(2) ["courseName", "Business Management"]
(2) ["startDate", "2009-10"]
(2) ["endDate", "2010-05"]
What I want to achieve is to get the output in an organized way, like this:
education:[
{
institutionName:"Harvard",
courseName:"Web Development",
startDate:"2000-11",
endDate:"2008-11"
},
{
...
}
]
So I'm interested in knowing the best approach to achieve this. Thanks in advance for any help!
It does not make sense to have two equal forms, with one being sufficient.
In addition to the form you should have a list that shows each item added.
It's what I recommend.
Not sure whether this is the best approach, but you can achieve the desired structure like this:
const formCV = document.querySelector('#formCV');
const formData = new FormData(formCV);
function groupEducationData(inputGroupSize = 4) {
const result = [];
let educationObj = null;
let counter = 0;
for (const entry of formData.entries()) {
// Since the counter is divisible by the number of inputs in a group
// only if one form group finishes. And when one form group finishes,
// we need to add the object into the result array
if (counter % inputGroupSize === 0) {
// if this is the first iteration, the educationObj is null and
// we don't want to add it to the result array yet
// we only add the educationObj to the result array if it is
// an object containing the education info
if (educationObj) result.push(educationObj);
// initialize the educationObj at the start
// and after one form finishes
educationObj = {};
}
// add entry[0] as key to the object (e.g. 'institutionName')
// with the value of entry[1] (e.g. 'Harvard')
educationObj[entry[0]] = entry[1];
counter++;
}
return result.concat(educationObj);
}
console.log(groupEducationData());
<form id="formCV" action="">
<div id="educationContainer">
<!-- First Group -->
<div class="education">
<div>
<input type="text" name="institutionName" value="Harvard">
</div>
<div>
<input type="text" name="courseName" value="Web Development">
</div>
<div>
<input type="month" name="startDate" value="2000-11">
</div>
<div>
<input type="month" name="endDate" value="2008-11">
</div>
</div>
<!-- Second Group -->
<div class="education">
<div>
<input type="text" name="institutionName" value="Oxford">
</div>
<div>
<input type="text" name="courseName" value="Business Management">
</div>
<div>
<input type="month" name="startDate" value="2009-10">
</div>
<div>
<input type="month" name="endDate" value="2010-05">
</div>
</div>
</div>
</form>
You can try FormData.getAll() and iterate over each group entry.
const institutionNames = formData.getAll('institutionName');
const courseNames = formData.getAll('courseName');
...
const educations = [];
for (let i = 0; i < institutionNames.length; i++) {
educations.push({
institutionName: institutionNames[i],
courseName: courseNames[i],
...
});
}
This is also a way to populate your desired format data.
$(document).ready(function(){
$(":button").click(function(){
var educations=$("#formCV .education");
var data=[];
educations.each(function(i,education){
var set={}
$(education).find(":input").each(function(i,value){
set[$(value).attr("name")] = $(value).val();
});
data.push(set);
})
console.log("data",data)
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form id="formCV" action="">
<div id="educationContainer">
<!-- First Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
<!-- Second Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
</div>
<input type="button" value="click me"/>
</form>
</body>
</html>
I have this code :
<div class="st-form-line">
<span class="st-labeltext">Countries</span>
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_0" name="members_create_campaign_form[countrySelectionType]" required="required" value="0" checked="checked" /> All</label>
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_1" name="members_create_campaign_form[countrySelectionType]" required="required" value="1"/> Selected</label>
<div id="clist_div" class="simplebox cgrid540-right" style="display:none;">
<div style="padding:5px"></div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Excluded Countries</b></p>
<select size="10" name="excluded2" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form['excluded2'],this.form['countries[]'])" multiple >
<?php foreach($arrayCountries as $country) {?>
<option value="<?= $country ?>" ><?= $country ?></option>
<?php } ?>
</select>
</div>
<div class="simplebox cgrid40-left">
<input class="button-blue" type="button" name="right" value=">>" onclick="moveSelectedOptions(this.form['excluded2'],this.form['countries[]'])"><br/><br/>
<input class="button-blue" type="button" name="left" value="<<" onclick="moveSelectedOptions(this.form['countries[]'],this.form['excluded2'])">
</div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Selected Countries</b></p>
<select size="10" id="members_create_campaign_form_countries" name="countries[]" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form['countries[]'],this.form['excluded2'])" multiple >
</select>
</div>
</div>
<div class="clear"></div>
</div>
This code look like this:
after i choose some countries from left side is adding me to right side, ok, that's good, but my problem is if is not selected as in this photo
is not adding in my database, and in this screnshoot it added only Canada and Germany that is selected and normally i want to add all countries that is added in right side.
This is js code:
<script type="text/javascript">
$(document).ready(function () {
if ($('#members_create_campaign_form_countrySelectionType_1').is(':checked')) {
$('#clist_div').show('slow');
}
$('#members_create_campaign_form_countrySelectionType_0').click(function () {
$('#clist_div').hide('slow');
});
$('#members_create_campaign_form_countrySelectionType_1').click(function () {
$('#clist_div').show('slow');
});
function selectDiff(s1Id, s2Id) {
var selected = $('#' + s2Id + ' option').map(function(){
return this.value;
}).get()
var excluded = $('#' + s1Id + ' option').each(function() {
if (selected.indexOf(this.value) != -1) {
selected.splice(selected.indexOf(this.value), 1);
$(this).remove();
}
}).get()
};
selectDiff('clist_div', 'members_create_campaign_form_countries');
});
1st : you need to select the all option in selected countries on submit
2nd : simple add selected attribute in all option in selected countries
Note : consequently if your adding to selected countries and removing from selected countries means . option loose the selected attribute so you need to add the selected attribute on submit
$(document).on('submit','#submit_button',function(){
$('#members_create_campaign_form_countries option').prop('selected',true);
});
You can take the selected countries as array and keep pushing selected countries in to that.
For example:
var selected_countries=[];
//on select country
selected_countries.push('country selected');
use selected_countries array add to DB.
I used the top answer to this question to build a form that feeds into a sheet along with file upload. Now I've hit another wall.
I have categories, and sub-categories. I'd like the sub-categories to only show up IF their parent category has been selected. I just can't figure out A) where I need to put the code (on our website it's right in with the HTML), I've tried putting it in the HTML file and the Code.gs file, or B) if the code I'm using is even right.
Here's the form - the "Co-Op Category" is the parent categories, I have hidden divs for each category that would hold the 'child categories'
HTML:
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name: <input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br>
Other: <input type="text" name="split" /><br />
Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit"
onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
Code.gs:
var submissionSSKey = '1zzRQwgXb0EN-gkCtpMHvMTGyhqrx1idXFXmvhj4MLsk';
var folderId = "0B2bXWWj3Z_tzTnNOSFRuVFk2bnc";
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Form.html');
template.action = ScriptApp.getService().getUrl();
return template.evaluate();
}
function processForm(theForm) {
var fileBlob = theForm.myFile;
var folder = DriveApp.getFolderById(folderId);
var doc = folder.createFile(fileBlob);
// Fill in response template
var template = HtmlService.createTemplateFromFile('Thanks.html');
var name = template.name = theForm.name;
var amount = template.amount = theForm.amount;
var split = template.split = theForm.split;
var reason = template.reason = theForm.split;
var brand = template.brand = theForm.brand;
var category = template.category = theForm.category;
var message = template.message = theForm.message;
var email = template.email = theForm.email;
var fileUrl = template.fileUrl = doc.getUrl();
// Record submission in spreadsheet
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 9).setValues([[name,amount,split,reason,category,brand,message,email,fileUrl]]);
// Return HTML text for display in page.
return template.evaluate().getContent();
}
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
This bit specifically is where I'm having trouble:
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
The unexpected token is due to the function(){ line, which is invalid syntax for the jQuery document ready function. You should have:
$(function(){
$('input[type="radio"]').click(function(){
...
});
});
With that fixed, your next error will be:
Uncaught ReferenceError: $ is not defined
That's because you haven't included jQuery, which is what the $ symbol is referring to in statements like $(this). You'll want to read this for more tips about using jQuery in Google Apps Script. The short story, though: You need to add the following, adjusted for whatever version of jQuery you intend to use:
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Updated Form.html, which shows the appropriate <div> as you intended. It also includes the recommended doctype, html, head and body tags:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//Toggle Secondary Categories
$(function() {
$('input[type="radio"]').click(function() {
if ($(this).attr("id") == "dealer") {
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if ($(this).attr("id") == "online") {
$(".box").not(".online").hide();
$(".online").show();
}
if ($(this).attr("id") == "advertising") {
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if ($(this).attr("id") == "pricing") {
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if ($(this).attr("id") == "correspondence") {
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if ($(this).attr("id") == "meetings") {
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if ($(this).attr("id") == "other") {
$(".box").not(".other").hide();
$(".other").show();
}
});
});
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name:
<input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br> Other: <input type="text" name="split" /><br /> Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit" onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
</body>
</html>
So I am validating a form - The validation works fine but if the user was to get something wrong it would .after a <p></p> error message. But if the user were to click the button more than once it will keep printing out that .after error message!
I have tried everything - This includes putting a boolean expression in the if statement and once the .after error message prints it will make that expression falseso the if statement won't run again. This did not work for me.
I also can't get the values to print out once the validation is all done!?
To try and fix this I have wrapped tried to wrap the validation in an if statement that tests to see if the validation is true and then at the bottom of the if statement after the validation I make that boolean value turn to false and then I have an else statement which prints out the values for each input...This won't work for me!
jQuery:
// JavaScript Document
$(document).ready(function() {
//Submit the form for validation
$('#submit').click(function ()
{
//Get the values from input fields:
$name = $('#txtName').val();
$age = $('#numAge').val();
//Sex:
$sex = $('sex').val();
//Email:
$email = $('#txtEmail').val();
$confirmEmail = $('#txtConfirmEmail').val();
//Checkbox
$("input[name='interest']:checked").each(function() {
$gender += "" + $(this).val() + ", ";
});
//Fish varieties:
$varieties = $('#txtVariety').val();
//Put checkbox values into an Array
var values = $('input:[name="interest[]"]:checked').map(function () {
return this.value;
}).get();
//printDetails is the id to print out to.
for(var i=0; i<values.length;i++){
alert(values[i]);
}
//Start Validation
if($name.length < 5){
$('#txtName').focus();
$('#txtName').val("");
$('#txtName').after("<p id='after1' style='color:red;'><strong>Enter a name greater than 5 letters!</strong></p>");
return false;
}
else{
$('p').remove('#after1');
$name = $('#txtName').val();
}
if($age.length > 105 || $age.length < 1){
$('#numAge').focus();
$('#numAge').val("");
$('#numAge').after("<p id='after2' style='color:red;'><strong>Enter an Age less than 106 and greater than 0!</strong></p>");
return false;
}
else{
$('p').remove('#after2');
}
function isValidEmailAddress($email) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
// alert( pattern.test(emailAddress) );
return pattern.test($email);
};
if(!isValidEmailAddress($email)){
$('#txtEmail').focus();
$('#txtEmail').after("<p id='after3' style='color:red;'><strong>Enter a valid email - <span style='color:#0078ab;'>"+ $email +"</span> - Is not valid</strong></p>");
$('#txtEmail').val("");
return false;
}
else{
$('p').remove('#after3');
//Now check if the email is successfully confirmed
if($email != $confirmEmail){
$('#txtConfirmEmail').focus();
$('#txtConfirmEmail').after("<p id='after4' style='color:red;'><strong>Your email - <span style='color:#0078ab;'>"+ $confirmEmail +"</span> - Does not match!</strong></p>");
$('#txtConfirmEmail').val("");
return false;
}
else{
$('p').remove('#after4');
}
}
//Check if there is atleast 1 checkbox checked
if($('input[type=checkbox:checked').length < 1) {
$('#checkboxError').html('<p id="after5" style="color:red;" id="after5">Please check atleast one checkbox</p>');
return false;
}
else{
//This should remove the above error message!
$('p').remove('#after5');
}
//These won't work?
document.getElementById("printDetails").innerHTML = $name + $age + $gender + $sex + $varieties + $email;
$("#printDetails").html("<div>" + $name + $age + $gender + $sex + $varieties + $email + " </div");
}); //END OF ONCLICK
}); //End of document.ready
Html
<div data-role="page" id="page2">
<div data-role="header">
<h1>Register jQuery</h1>
</div>
<div data-role="content">
<!-- Name, Age -->
<div data-role="fieldcontain">
<label for="txtName">Name:</label>
<input type="text" name="txtName" id="txtName" value="" />
</div>
<div data-role="fieldcontain">
<label for="numAge">Age:</label>
<input type="number" name="numAge" id="numAge" value="" />
</div>
<!-- Sex, Default value = Male-->
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Sex</legend>
<input type="radio" name="sex" id="sex_male" value="" />
<label for="sex_male">Male</label>
<input type="radio" name="sex" id="sex_female" value="" checked='checked' />
<label for="sex_female">Female</label>
</fieldset>
</div>
<!-- Emails -->
<div data-role="fieldcontain">
<label for="txtEmail">e-mail:</label>
<input type="email" name="txtEmail" id="txtEmail" value="" />
</div>
<div data-role="fieldcontain">
<label for="txtConfirmEmail">Confirm e-mail:</label>
<input type="email" name="txtConfirmEmail" id="txtConfirmEmail" value="" />
</div>
<!-- Interest In checkboxes -->
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>I am interested in the following</legend>
<input type="checkbox" name="interest[]" value='Comet' id="interest_0" class="custom" value="" />
<label for="interest_0">Comet</label>
<input type="checkbox" name="interest[]" value='Common Goldfish' id="interest_1" class="custom" value="" />
<label for="interest_1">Common Goldfish</label>
<input type="checkbox" name="interest[]" id="interest_2" class="custom" value="Black Moor" />
<label for="interest_2">Black Moor</label>
<input type="checkbox" name="interest[]" value='Celestial Eye' id="interest_3" class="custom" value="" />
<label for="interest_3">Celestial Eye</label>
<input type="checkbox" name="interest[]" value='Fantail' id="interest_4" class="custom" value="" />
<label for="interest_4">Fantail</label>
<input type="checkbox" name="interest[]" value='Lionchu' id="interest_5" class="custom" value="" />
<label for="interest_5">Lionchu</label>
<input type="checkbox" name="interest[]" value='Other' id="interest_6" class="custom" value="" />
<label for="interest_6">Other</label>
</fieldset>
</div>
<div data-role="fieldcontain" class='display'>
<label for="txtVariety">Fish Varieties:</label>
<textarea cols="40" rows="8" name="txtVariety" id="txtVariety"></textarea>
</div>
<p id='checkboxError'></p>
<!-- Text Area - Fish Varieties -->
<!-- Drop down select menu - How did u hear about us -->
<div data-role="fieldcontain">
<label for="selectmenu" class="select">How did you hear about us?:</label>
<select name="selectmenu" id="selectmenu">
<option value="Internet">Internet</option>
<option value="Email">Email</option>
<option value="Friend">Friend</option>
<option value="Billboard">Billboard</option>
<option value="Other">Other</option>
</select>
</div>
<!-- Register & Start again buttons -->
<input type="submit" id='submit' value="Register"/>
<input type="submit" id='resetForm' value="Start Again" />
<!-- Print out the details -->
<div id='printDetails'></div>
I Have a feeling this code should work - Hopefully someone sees the problem i',
Ok so after going through your fiddle and I think I got it working with bare minimum code changes.
The main thing was setting up the boolean isValid at the beginning of the submit button event to true and setting to false when it fails a validation test. Then only displaying your output when the form is valid.
Demo
Also, some jQuery selectors were incorrect and I think there is some confusion between gender and sex. They are the same thing, just different words.
There are still is lots of room for improvement but this looks like a homework assignment so I can tell you maybe still learning.
I have found out how to fix one of the issues - The issue I fixed is the duplication of the .after error messages. To fix this I just added $('p').remove('#after5'); inside each if statement before the if statement actually prints the .after error message out.
if($('input[type=checkbox:checked').length < 1) {
$('p').remove('#after5');
$('#checkboxError').html('<p id="after5" style="color:red;" id="after5">Please check atleast one checkbox</p>');
return false;
}
else{
//This should remove the above error message!
$('p').remove('#after5');
}
I am still having problems printing out the data when all the validation is correct!
I'm trying to swap visibility of 2 elements based on a drop-down selection in the form.
If user selects any of the first 6 items, the "Message" area remains.
If user selections last item "Reproduction Rights", then "Message" disappears and is swapped with "Rights message" div.
I've got it working with the repro rights showing/hiding, but not the message box. I'm new to java, so pardon my ignorance. Here's the full page code or view at Paul-Rand.com:
Got it working with this code, but is there a cleaner way to do it?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Paul-Rand.com :: Contact Us</title>
{embed=site/meta}
<link rel="stylesheet" type="text/css" href="{stylesheet=styles/twocolumn}" />
<link rel="stylesheet" type="text/css" href="{stylesheet=styles/global}" />
<script type="text/javascript" src="{path=scripts/livevalidation_standalone}"></script>
<script type="text/javascript">
// <![CDATA[
function display(obj,id1,id2) {
txt = obj.options[obj.selectedIndex].value;
document.getElementById(id1).style.display = 'none';
document.getElementById(id2).style.display = 'none';
if ( txt.match(id1) ) {
document.getElementById(id1).style.display = 'block';
}
if ( txt.match(id2) ) {
document.getElementById(id2).style.display = 'block';
}
}
// ]]>
</script>
</head>
<body>
{embed="site/mainNav"}
<div id="container">
<div id="centercontent">
<h1>Contact Us</h1>
<div class="form-left">
<p>To send us a message, please fill out the form below. We'll get back to you shortly!</p>
{exp:freeform:form
required="name|email|message"
collection="Contact Form"
return="site/success"
notify="dlewandowski38#yahoo.com"
template="randContact"
file_upload="Email attachments"
send_attachment="yes" }
<label>Name / Company Name <em>(required)</em>
<br style="clear:both">
<span><input type="text" name="name" id="Name" class="formMediumText"/></span>
</label>
<script type="text/javascript">var Name = new LiveValidation('Name');Name.add(Validate.Presence);</script>
<label>Email <em>(required)</em>
<br style="clear:both">
<span><input type="text" name="email" id="Email" class="formMediumText"/></span>
<script type="text/javascript">var Email = new LiveValidation('Email');Email.add(Validate.Email );</script>
</label>
<label>Regarding
<br style="clear:both">
<span>
<select name="regarding" id="Regarding" class="formMediumText" onchange="display(this,'subject','Reproduction Rights');">
<option value="subject">General Inquiry</option>
<option value="subject">Suggestion for the site</option>
<option value="subject">Problem with the site</option>
<option value="subject">Work to Share</option>
<option value="subject">Story to Share</option>
<option value="subject">Pictures to Share</option>
<option value="Reproduction Rights">Reproduction Rights</option>
</select>
</span>
</label>
<div id="Reproduction Rights" style="display: none; float:left;background-color: #ff9900; padding: 20px;">
<h4 style="text-transform: uppercase; padding: 0; margin:0;">Reproduction rights are granted through the Paul Rand estate only.</h4>
<p style="padding: 0; margin: 0;">Contact the Yale Archives with a detailed description of your planned usage and they will process your request.</p>
</div>
<div id="subject" style="display: none">
<label>Message
<br style="clear:both">
<span>
<textarea cols="24" rows="12" name="message" id="Message" class="formMediumText"></textarea>
</span>
</label>
</div>
<br style="clear:both"/>
<hr/>
<h2 style="margin-bottom:-18px">Help the site grow</h2>
<h5 style="margin-bottom:-6px">Have a piece of Paul Rand work that's not seen on the site? Share it! </h5>
<p>Send your files (any image type, 800px wide or larger), your name and website (if available). I'll add it to the appropriate gallery and give you credit for your addition.</p>
<p>Your contributions are GREATLY APPRECIATED!</p>
<br/>
<label for="file" style="float:left;">Share a File (up to 5 per message):</label>
<span><input type="file" name="file1" id="file1" class="formPicBrowse"/></span>
<span><input type="file" name="file2" id="file2" class="formPicBrowse"/></span>
<span><input type="file" name="file3" id="file3" class="formPicBrowse"/></span>
<span><input type="file" name="file4" id="file4" class="formPicBrowse"/></span>
<span><input type="file" name="file5" id="file5" class="formPicBrowse"/></span>
<br style="clear:both"/>
<br/>
{if captcha}
<label>For security, please enter the word you see below:
<br style="clear:both">
<p style="width:160px;">{captcha}</p>
<span><input type="text" name="captcha" onfocus="if(this.value == 'Security Code') { this.value = ''; }" value="Security Code" id="Captcha" class="formMediumText" style="width:130px" /></span>
<script type="text/javascript">var Captcha = new LiveValidation('Captcha');Captcha.add(Validate.Presence);</script>
</label>
{/if}
<br style="clear:both"/>
<br/>
<p><input type="submit" name="submit" value="Send" class="buttons" style="font-size:18px; padding-top:8px;"/></p>
{/exp:freeform:form}
</div>
<script type="text/javascript">
var Name = new LiveValidation( 'Name', {onlyOnSubmit: true } );
Name.add( Validate.Presence );
var Email = new LiveValidation( 'Email', {onlyOnSubmit: true } );
Email.add( Validate.Presence );
var Message = new LiveValidation( 'Message', {onlyOnSubmit: true } );
Message.add( Validate.Presence );
var Captcha = new LiveValidation( 'Captcha', {onlyOnSubmit: true } );
Captcha.add( Validate.Presence );
</script>
</div>
</div>
{embed=site/bottomSection}
{embed=site/footer}
{embed=site/googleTracking}
</body>
</html>
For start it's good manners to clean your code to contain only the necessary bits before you post it here. It's difficult to wade through all of it in search of the relevant bits.
This isn't a JavaScript problem as such, just a plain logic issue. So what you want to do is a switch. If user selected option a set div 1 visible and div 2 invisible. If user selected option b do the opposite. Below is the modified display function
function display(obj) {
txt = obj.options[obj.selectedIndex].value;
if (txt.match("Reproduction Rights")) {
document.getElementById("Reproduction Rights").style.display = 'block';
document.getElementById("MessageDiv").style.display = 'none';
}
else {
document.getElementById("Reproduction Rights").style.display = 'none';
document.getElementById("MessageDiv").style.display = 'block';
}
}
and the HTMLto go with it. Two points to notice about this. You don't need the call to the hide() function in the onchange event handler, the display function is a switch, it'll do all the work. I also added a wrapping div with an id of MessageDiv to allow hiding both the message box and the text accompanying the message box. If the text isn't supposed to be hidden then by all means leave the div out.
<label>Regarding
<br style="clear:both">
<span><select name="regarding" id="Regarding" class="formMediumText" onchange="display(this, 'Reproduction Rights');">
<option value="General Inquiry">General Inquiry</option>
<option value="Suggestion for the site">Suggestion for the site</option>
<option value="Problem with the site">Problem with the site</option>
<option value="Work to Share">Work to Share</option>
<option value="Story to Share">Story to Share</option>
<option value="Pictures to Share">Pictures to Share</option>
<option value="Reproduction Rights">Reproduction Rights</option>
</select></span>
</label>
<div id="Reproduction Rights" style="display: none; float:left;background-color: #ff9900; padding: 20px;">
<h4 style="text-transform: uppercase; padding: 0; margin:0;">Reproduction rights are granted through the Paul Rand estate only.</h4>
<p style="padding: 0; margin: 0;">Contact the Yale Archives with a detailed description of your planned usage and they will process your request.</p>
</div>
<div id="MessageDiv">
<label>
Message <em>(required)</em>
<br style="clear:both">
<span><textarea cols="24" rows="12" name="message" id="Message" class="formMediumText"></textarea><script type="text/javascript">var Message = new LiveValidation('Message');Name.add(Validate.Presence);</script>
</span>
</label>
</div>