New element not added to dynamic form - javascript

I downloaded this multistep form http://codepen.io/atakan/pen/gqbIz but whenever I try to use the dynamic form code, it fails to add the new element and instead submits the form.
The code that I use for the dynamic form is
var lastAdded;
var counter = 1;
var limit = 12;
function addFp(spanName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newspan = document.createElement('span');
newspan.innerHTML = "<br><select name='w_1_imp"+(counter+1)+"' class=''><option value='imp1'>Animal - Desi Plough</option><option value='imp2'>Animal - Mouldboard Plough</option><option value='imp3'>Animal - Disc Harrow</option><option value='imp4'>Bakhar Blade</option><option value='imp5'>MB Plough</option><option value='imp6'>Puddler</option><option value='imp7'>Disc Plough</option><option value='imp8'>Disc Harrow</option><option value='imp9'>Paddy Harrow</option><option value='imp10'>Rotavator</option><option value='imp11'>Ridger</option><option value='imp12'>Power Tiller</option><option value='imp13'>Animal - Three tyne cultivator</option><option value='imp14'>Cultivator</option></select> <input type='text' name='w_1_h"+(counter+1)+"' placeholder='Hours' class='' size='2'> <input type='text' name='w_1_t"+(counter+1)+"' placeholder='Times' class='' size='3'>"
document.getElementById(spanName).appendChild(newspan);
counter++;
lastAdded = newspan;
}
}
function deleteLastAdded () {
if (lastAdded) {
lastAdded.remove();
counter--;
}
}
The page from where I am calling and using the javascript:
<script src="./assets/js/field_preparation.js"></script>
<div class="form-top">
<div class="form-top-left">
<h3>Field preparation:</h3>
<p>Step 2 / 10</p>
</div>
<div class="form-top-right">
<i class="fa fa-user"></i>
</div>
</div>
<div class="form-bottom">
<div class="form-group">
<table>
<tr><td><b>Tractor Horse Power </b></td><td><b> :</b> </td><td><input type="text" name="tractor1" placeholder="HP" class="" size="8"></td></tr>
<tr><td><b>Bullocks </td><td> <b>:</b></td></b></td><td><input type="text" name="bullock1" placeholder="How many" class="" size="8"></td></tr>
<tr><td><b>No. of Man Hours </b></td><td> <b> : </b></td><td><input type="text" name="human1" placeholder="Men" class="" size="8"></td></tr>
</table>
<span id="dynamicFp">
<select name="w_1_imp1" class="" width="8">
<option value="imp1">Animal - Desi Plough</option>
<option value="imp2">Animal - Mouldboard Plough</option>
<option value="imp3">Animal - Disc Harrow</option>
<option value="imp4">Bakhar Blade</option>
<option value="imp5">Animal - Three tyne cultivator</option>
<option value="imp6">Puddler</option>
<option value="imp7">Disc Plough</option>
<option value="imp8">Disc Harrow</option>
<option value="imp9">Paddy Harrow</option>
<option value="imp10">Rotavator</option>
<option value="imp11">Ridger</option>
<option value="imp12">Power Tiller</option>
<option value="imp13">MB Plough</option>
<option value="imp14">Cultivator</option>
</select>
<input type="text" name="w_1_h1" placeholder="Hrs" class="" size="2">
<input type="text" name="w_1_t1" placeholder="Times" class="" size="3">
</span>
<br><center>
<input type="image" src="./assets/img/plus.png" border="0" width="30px" value="Add Implement" onClick="addFp('dynamicFp');">
<input type="image" src="./assets/img/cancel.png" border="0" width="30px value="Delete last added" onClick="deleteLastAdded();">
<center></center>
<div></div>
<button type="button" class="btn btn-previous">Previous</button>
<button type="button" class="btn btn-next">Next</button>
</div>
can you please help me?
Screenshot
the thing I want is an add remove button next to the implement dropdown field, and then use the same fields to process the results. Thanks
Also, in the above form, I need to have dynamic fields at each step. So, can anyone provide me the code. Thanks

The 'image' input type is actually a submit button...
Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/image
So that explains why it is submitting the form. Consider using a button, link (a) or other element type instead and it should work okay!

Related

How to responsively get Javascript to validate information from HTML5 form textboxes?

I am trying to build a functional Credit Card validation script for a demo assignment. I am attempting to get JavaScript to react to input as the focus() changes from text box to text box. Once I have the JavaScript reactive then I want to validate that data against specific parameters.
I've tried adding onchange methods directly into the HTML5, but something won't work correctly. I am open to all suggestions, I've spent too long at a stalemate.
HTML
<h2>Payment
<img style="visibility: hidden" class="mastercard"
src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard"
src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard"
src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard"
src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="16">
</div>
<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
<button type="submit" class="myButton"style = "float:right;">Place Order</button>
</form>
JavaScript
<script type="text/javascript">
var creditError="Error with Credit Card information";
var CWError="Error with CW";
document.getElementbyID("cc-cvv").onchange=function(){function CWcheck()};
document.getElementbyID("cc_number").onchange=function(){function creditCheck()};
document.getElementbyID("cc_name").onchange=function(){function upperFunction()};
function CWcheck()
{
if (document.forms["LeftCheck"]["cc-cvv"].value.length < 3 ||document.forms["LeftCheck"]["cc-cvv"].value.length>=5){
alert(CWError);
cdocument.forms["LeftCheck"]["cc-cvv"].value.value=" ";
}
else if(document.forms["LeftCheck"]["cc-cvv"].value.match(/^[A-Za-z]+$/)){
alert(CWError);
document.forms["LeftCheck"]["cc-cvv"].value=" ";
}
else if(document.forms["LeftCheck"]["cc-cvv"].value.match(/^[-+]?[0-9]+\.[0-9]+$/)) {
alert(CWError);
document.forms["LeftCheck"]["cc-cvv"].value=" ";
}
else
break;
}
function upperFunction() {
document.getElementsByClassName("cc_name").value.toUpperCase();
}
function creditCheck() {
{
if (document.forms["LeftCheck"]["cc_number"].value.length < 15 ||document.forms["LeftCheck"]["cc_number"].value.length>16){
alert(creditError);
document.forms["LeftCheck"]["cc_number"].value=" ";
}
else if(document.forms["LeftCheck"]["cc_number"].value.match(/^[A-Za-z]+$/)){
alert(creditError);
document.forms["LeftCheck"]["cc_number"].value=" ";
}
else if(document.forms["LeftCheck"]["cc_number"].value.match(/^[-+]?[0-9]+\.[0-9]+$/)) {
alert(creditError);
document.forms["LeftCheck"]["cc_number"].value=" ";
}
else
if(document.forms["LeftCheck"]["cc_number"].value.match(/^(?:3[47][0-9]{13})$/)){
document.getElementsByClassName('amexcard').style.visibility="visable";
document.forms["LeftCheck"]["cc_number"].value=" ";
}
else if(document.forms["LeftCheck"]["cc_number"].value.match(/^(?:4[0-9]{12}(?:[0-9]{3})?)$/)){
document.getElementsByClassName('visacard').style.visibility="visable";
document.forms["LeftCheck"]["cc_number"].value=" ";
}
else if(document.forms["LeftCheck"]["cc_number"].value.match(/^(?:5[1-5][0-9]{14})$/)){
document.getElementsByClassName('mastercard').style.visibility="visable";
document.forms["LeftCheck"]["cc_number"].value=" ";
}
else if(document.forms["LeftCheck"]["cc_number"].value;=.match(/^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/)){
document.getElementsByClassName('discovercard').style.visibility="visable";
document.forms["LeftCheck"]["cc_number"].value=" "
}
else {
alert(creditError)
this.clear()
}
}
I would ideal like the text box to validate that when a creditcard number is entered it; it will check nothing outside of numbers were entered, the cadence of the numbers match a card type or reset the field, and display the image that the card is next to the "Payment" header.
The Checksum Validation by Alex works very well, with that portion out of the way I can streamline the image setting. So far my code has been updated to the following
Updated HTML
<form method="POST" action="/checkout" class = "LeftCheck" name="LeftCheck" id="LeftCheck">
<h2>Payment
<img style="visibility: hidden" class="mastercard"
src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard"
src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard"
src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard"
src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="16">
</div>
<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
<button type="submit" class="myButton"style = "float:right;">Place Order</button>
</form>
And the updated Issue area of my JavaScript
document.getElementById('cc_number').addEventListener('change',pictureCheck);
function pictureCheck()
{
var ccNum = this.value;
if (ccNum.length = 15)
{
document.getElementsById('amexcard').style.display='';
}
else if(ccNum.value.match(/^(?:4[0-9]{12}(?:[0-9]{3})?)$/))
{
document.getElementsById('visacard').style.display='';
}
else if(ccNum.value.match(/^(?:5[1-5][0-9]{14})$/))
{
document.getElementsById('mastercard').style.display='';
}
else (ccNum.value;=.match(/^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/))
{
document.getElementsById('discovercard').style.display='';
}
}
Your javascript part is all wrong. Let me show how it should work.
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
alert('CC number is 15 or 16 digits');
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
alert('Incorrect checksum of CC');
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
alert('CC number doesn\'t match known any CC issuer');
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
UPDATE: CC issuer from card number is added.
You could do this with JQuery. When you switch between input fields, you could run your validation script.
$("#id1, #id2").focus(function() {
alert("Focus changed.");
//run validator
});
I noticed that you use document.forms["LeftCheck"]["cc-cvv"] to access the fields of the form. Since you did not include your form start tag, I want to make sure that the name field of you form is set to LeftCheck, rather than the ID, since I have had this problem before.
You also use document.getElementbyID() to access the elements that you are applying the onchange listener to. The method is actually document.getElementbyId(), with the last letter not capitalized. This may be the reason your events are not firing.
The way that you attach your events to the select element is also incorrect. You can simply do this:
document.getElementbyID("cc-cvv").onchange = CWcheck;
or alternatively
document.getElementbyID("cc-cvv").onchange = function() { CWcheck();};
One last thing is that you use regex to validate the input of the credit card field. However, you do this by checking if the input matches an invalid pattern and raises an error if it does. Although this could work, it would be much better to check if the input matches a valid pattern, and if it doesn't, raise in error. This makes your validation code more robust and makes sure that you don't have invalid edge cases that may pass your validation.
Use the inline onblur event
<input type="text" onblur="CWcheck()" />

PHP code not working in a Form which is used for javascript

I am working with a form which uses Javascript for a process. When i try to read the textbox value in form with PHP, It's not showing output.
My code is
HTMLCode is
<form class="form-inline" method="POST" action="staff.php" onSubmit=" return questiontable()" >
<div class="form-group">
<label for="qscount">Number of Questions: </label>
<input type="number" name="qscount" class="form-control" id="qscount" style="width:150px;" placeholder="No of questions"> <br>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" id="gobtn" onClick="return disable()" >Go</button> <br>
<p id="btnhide"> </p>
</div>
</form>
Javascript is
<script type="text/javascript">
function questiontable()
{
var qs = document.getElementById("qscount").value;
var count;
for(count=1; count<=qs; count++)
{
document.getElementById("demo").innerHTML += '<br><font style="font-size: 20px">'+ count+'. <input class="textboxtest" style="width:850px;" type="text" name=" q'+ count +' " placeholder="Question "><br>' ;
document.getElementById("demo").innerHTML +='<br><input style="margin-left: 25px;" type="radio" name="a'+count+'" value="c1"> <input class="testbox" type="text" name="o'+count+'1" placeholder="Option 1">';
return false;
}
</script>
PHP Code is
<?php
if (isset($_POST['qscount'])){
echo $_POST['qscount'];
}
?>
I want to use this qscount value in another php page. How to get this textbox value in PHP and use it in another page ?
Javascript function() should return true, since you are using return function() in onclick attribute of button type=submit
<script type="text/javascript">
function questiontable()
{
var qs = document.getElementById("qscount").value;
var count;
for(count=1; count<=qs; count++)
{
document.getElementById("demo").innerHTML += '<br><font style="font-size: 20px">'+ count+'. <input class="textboxtest" style="width:850px;" type="text" name=" q'+ count +' " placeholder="Question "><br>' ;
document.getElementById("demo").innerHTML +='<br><input style="margin-left: 25px;" type="radio" name="a'+count+'" value="c1"> <input class="testbox" type="text" name="o'+count+'1" placeholder="Option 1">';
}
return true;
}
</script>
This will continue the form posting onclick of the button
If you are trying to create the number of questions on click dynamically using javascript,
then use syntax to call questionTable
<button type="button" class="btn btn-primary" id="gobtn" onClick="javascript:return questiontable()" >Create Questions</button>
Remove
onSubmit=" return questiontable()"
from the form
Now when the question table is rendered, please show the button type="submit"
<button type=submit value="Go" name="cmdGo">Go</button>
to trigger form submission
Hope it helps!

cloning template Jquery

I have a rather long complicated form to be used to record field data. One section of the form requires the ability to add a "Field Blank" section with no data recorded AND the ability to add a duplicate section where everything (including the data from the field blank section) is duplicated. The only different thing that would change on the duplicate would be the SampleID
The field blank script
<script>
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
</script>
The duplicate script
<script>
$(document).ready(function(){
var template_index=0;
$("#add_FieldDup").click(function(){
template_index++;
$(this).parent().before($("#template").clone().attr("id","template" + template_index));
$("#template" + template_index).css("display","inline");
$("#template" + template_index + " :input").each(function(){
$(this).attr("name",$(this).attr("name") + template_index);
$(this).attr("id",$(this).attr("id") + template_index);
});
$("#remove_Dup" + template_index).click(function(){
$(this).closest("fieldset").remove();
});
});
});
</script>
My form
<h3>Water Samples</h3>
<fieldset id="template"> <!--for the duplicate-->
<div id="template"> <!--for the duplicate-->
Sample ID: <input type="text" id="SampleID" name="SampleID"></div>
<div class="_40" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label> Collection Method</label><br />
<input type="radio" id="radGrab" value="grab" name="Collection" />
<label for="radGrab">Grab</label>
<input type="radio" id="radEWI" value="EWI" name="Collection" />
<label for="radEWI">EWI</label>
</div>
<fieldset> <!--For the field blank-->
<div id="readroot" class="hidden"> <!--For the field blank-->
QA Sample ID:<input type="text" id="QASampleID" name="QASampleID">
<div class="_30" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label>Collection Method</label><br />
<input type="radio" id="radGrab1" value="Grab" name="Collection1" />
<label for="radGrab1">Grab</label>
<input type="radio" id="radEWI1" value="EWI" name="Collection1" />
<label for="radEWI1">EWI</label></div>
</div>
<label class="analysis-label" for="analysis">Analyte:</label>
<select class="analysis" id="analysis" name="analysis" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "TN">TN</option>
<option value = "TP,NO2+3">TP,NO2+3</option>
</select>
<label class="preserve-label" for="preserve">Preserved</label>
<select class="select_preserve" id="preserve" name="preserve" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "HNO3">HNO₃</option>
<option value = "H2SO4">H₂SO₄</option>
</select>
<label class="cool-label" for="cool">Cooled</label>
<select class="select_cool" id="cool" name="cool" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "Ice">Ice</option>
<option value = "Frozen">Frozen</option>
<option value = "None">None</option>
</select>
</div> <!--Fieldblank-->
</fieldset> <!--Fieldblank -->
<hr /><span id="writeroot"></span>
</div> <!--duplicate template-->
</fieldset> <!--duplicate template-->
<button type="button" data-theme="b" data-icon="plus" id="moreFields" onclick="moreFields()">ADD FIELD BLANK</button>
<button type="button" data-theme="b" data-icon="plus" id="add_FieldDup">ADD FIELD DUP</button>
I got the duplicate to work (when the field blank wasn't hidden) but I cannot get the field blank to work. Any assistance would be greatly appreciated!
You should extract your javascript from your dom, put it in separate js and make function work in any of this blocks, create class="template" block and inside give any needed interaction buttons and inputs classes so there can exist multiple parent elements with same inside structure... then cloning does not get in a way of your interaction logic.
In js go like:
$(document).ready(function() {
$(".template .interaction_button_one").on('click', function(){
//... here you go traversing like
$(this).parents('.template').find('.some_important_div').show();
})
});
Notice .on(), this is delegation, and it will give same interaction bindings to all of your elements.

Execute function with value of current selected option

Even if i have selected an options it still alert a message "Please choose something."
I got this working with only one dropdown list, but i have problems when there are two or more.
(In working example variable sport is document.getElementById("sports") and only one dropdown list)
What's the issue?
<script type="text/javascript">
function check() {
sport = document.getElementsByClassName("sports");
sport_selected = sport.selectedIndex;
weight = document.getElementById("weight").value;
time = document.getElementById("time").value;
if (sport_selected > 0) {
if (isNaN(weight, time)) {
alert("Error. This is not a number.");
}
else {
met = sport.options[sport_selected].value;
calculations = (time * ((met * 3.5 * weight)/200));
result = Math.round(calculations);
document.lastform.output.value = result + " kcal";
}
}
else {
alert("Please choose something.")
}
});
</script>
<div id="tabs">
<ul>
<li>Running</li>
<li>Walking</li>
</ul>
<div id="tabs-1">
<form name="form1">
<select class="sports">
<option value="">-Choose-</option>
<option value="6">Jog/walk combination</option>
<option value="7">Jogging, general</option>
<option value="8">Running, 5 mph (12 min/miile)</option>
<option value="9">Running, 5.2 mph (11.5 min/mile)</option>
<option value="10">Running, 6 mph (10 min/mile)</option>
</select>
</form>
</div>
<div id="tabs-2">
<form name="form2">
<select class="sports">
<option value="">-Choose-</option>
<option value="2">Walking, general</option>
<option value="2">Walking, 1 mph</option>
</select>
</form>
</div>
</div>
<form name="lastform">
<label for="weight">Weight [kg]:</label><br />
<input type="text" size="3" id="weight"><br />
<label for="time">Duration [min]:</label><br />
<input type="text" size="3" id="time">
<input type="button" value="Calc" onClick="check()"><br /><br />
<label for="kcal">You have burned:</label><br />
<input type="text" id="output">
</form>
getElementsByClassName is returning a collection but not just one item, you need to write code to iterate the collection if you have more controls. please check: https://developer.mozilla.org/en/DOM/document.getElementsByClassName
What about using jQuery, since you've used the TAG ?
HTML
<div id="tabs">
<ul>
<li>Running</li>
<li>Walking</li>
</ul>
<div id="tabs-1">
<form name="form1">
<select class="sports">
<option value="">-Choose-</option>
<option value="6">Jog/walk combination</option>
<option value="7">Jogging, general</option>
<option value="8">Running, 5 mph (12 min/miile)</option>
<option value="9">Running, 5.2 mph (11.5 min/mile)</option>
<option value="10">Running, 6 mph (10 min/mile)</option>
</select>
</form>
</div>
<div id="tabs-2">
<form name="form2">
<select class="sports">
<option value="">-Choose-</option>
<option value="2">Walking, general</option>
<option value="2">Walking, 1 mph</option>
</select>
</form>
</div>
</div>
<form name="lastform">
<label for="weight">Weight [kg]:</label><br />
<input type="text" size="3" id="weight"><br />
<label for="time">Duration [min]:</label><br />
<input type="text" size="3" id="time">
<input type="button" value="Calc" id="check"><br /><br />
<label for="kcal">You have burned:</label><br />
<input id="result" type="text" id="output">
</form>
javascript
$("#check").click(function() {
var sport_selected = $(".sports option:selected").val();
var weight = $("#weight").val();
time = $("#time").val();
if (parseInt(sport_selected) > 0) {
if (isNaN(weight, time)) {
alert("Error. This is not a number.");
}
else {
var met = sport_selected
calculations = (time * ((met * 3.5 * weight) / 200));
result = Math.round(calculations);
$("#result").val(result + " kcal");
}
}
else {
alert("Please choose something.")
}
});​
and this is the fiddle.

Need to swap field visibility on a form

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>

Categories

Resources