dropdown menu that requires selection - javascript

I am trying to figure this one out, but I need some help. a drop down menu with add to cart button that doesn't submit without selecting any options, what I would love to have is a pop up that prompts to select one from each drop down options (required). this is what i'm trying to do http://ccaples.com/index.php/basic-scripts/examples-i/dropdown-menus-that-require-selection , the question is how to implement this to my code thank you very much.
<SCRIPT TYPE="text/javascript">
function MM_goToURL() { //v3.0
var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function Dollar (val) { // force to valid dollar amount
var str,pos,rnd=0;
if (val < .995) rnd = 1; // for old Netscape browsers
str = escape (val*1.0 + 0.005001 + rnd); // float, round, escape
pos = str.indexOf (".");
if (pos > 0) str = str.substring (rnd, pos + 3);
return str;
}
function ReadForm (obj1) { // process un-named selects
var i,j,amt,des,obj,pos,tok,val;
var ary = new Array ();
amt = obj1.baseamt.value*1.0; // base amount
des = obj1.basedes.value; // base description
for (i=0; i<obj1.length; i++) { // run entire form
obj = obj1.elements[i]; // a form element
if (obj.type == "select-one" && // just get selects
obj.name == "") { // must be un-named
pos = obj.selectedIndex; // which option selected
val = obj.options[pos].value; // selected value
ary = val.split (" "); // break apart
for (j=0; j<ary.length; j++) { // look at all items
// first we do single character tokens...
if (ary[j].length < 2) continue;
tok = ary[j].substring (0,1); // first character
val = ary[j].substring (1); // get data
if (tok == "#") amt = val * 1.0;
if (tok == "+") amt = amt + val*1.0;
if (tok == "%") amt = amt + (amt * val/100.0);
if (tok == "#") { // record item number
if (obj1.item_number) obj1.item_number.value = val;
ary[j] = ""; // zap this array element
}
// Now we do 3-character tokens...
if (ary[j].length < 4) continue;
tok = ary[j].substring (0,3); // first 3 chars
val = ary[j].substring (3); // get data
if (tok == "s1=") { // value for shipping
if (obj1.shipping) obj1.shipping.value = val;
ary[j] = ""; // clear it out
}
if (tok == "s2=") { // value for shipping2
if (obj1.shipping2) obj1.shipping2.value = val;
ary[j] = ""; // clear it out
}
}
val = ary.join (" "); // rebuild val with what's left
if (des.length == 0) des = val; // 1st storage?
else des = des + ", " + val; // nope, accumulate value
}
}
obj1.item_name.value = des;
obj1.amount.value = Dollar (amt);
if (obj1.tot) obj1.tot.value = "$" + Dollar (amt);
}
</SCRIPT>
<FORM id=viewcart name=viewcart action=https://www.paypal.com/cgi-bin/webscr
method=post>
</FORM>
<FORM onSubmit="this.target = 'paypal';
ReadForm (this.form);"
action=https://www.paypal.com/cgi-bin/webscr method=post>
<P>
<INPUT type=hidden value=_cart name=cmd>
<INPUT type=hidden value=1 name=add>
<INPUT type=hidden value=my#email.com name=business>
<INPUT type=hidden name=item_name>
<INPUT type=hidden name=item_number>
<INPUT type=hidden name=amount>
<INPUT type=hidden value=USD name=currency_code>
<INPUT type=hidden value=USD name=lc>
<INPUT type=hidden value=00 name=shipping>
<INPUT type=hidden value=00.00 name=baseamt>
<INPUT type=hidden VALUE="itemname" name=basedes>
<INPUT TYPE="hidden" NAME="on0" VALUE="Details">
<INPUT TYPE="hidden" NAME="os0" VALUE="moredetails" MAXLENGTH="800">
<BR>
<BR>
</P>
<TABLE WIDTH="400px" BORDER="0" CELLPADDING="0" CELLSPACING="0" align="right">
<TR>
<TD ALIGN="left">
<p class="heading"> </p>
<p class="main"> dropdown1</p>
<p class="heading"> </p>
</TD>
<TD>
<SELECT STYLE="WIDTH: 240px" onChange="ReadForm (this.form);">
<OPTION selected>Please select </OPTION>
<OPTION VALUE="option1 +125.00">option1</OPTION>
<OPTION VALUE="option2 +90.00">option2</OPTION>
<OPTION VALUE="option3 +40.00">option3</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<TD ALIGN="left">
<p class="heading"> </p>
<p class="main"> dropdown2</p>
<p class="heading"> </p>
</TD>
<TD>
<SELECT STYLE="WIDTH: 240px" onChange="ReadForm (this.form);">
<OPTION selected>Please select </OPTION>
<OPTION VALUE="option1 +55.00">option1</OPTION>
<OPTION VALUE="option2 +99.00">option2</OPTION>
<OPTION VALUE="option3 +44.00">option3</OPTION>
</SELECT>
</TD>
</TR>
<tr>
<TR>
<TD ALIGN="left">
<p class="main"> </p>
<p class="main"> Price</p>
<p class="main"> </p>
</TD>
<TD ALIGN="left">
<INPUT class=nbor size=8 value=00.00 name=tot>
</TD>
</TR>
<TD align="left">
<label for="submit"></label>
<TD align="left">
<input type="image" src="/addtocart2.png" name="submit" id="submit" value="submit" >
</div>
</div></td>
</tr>
</table>
</table>
</form>
</TABLE>
</FORM>
</div>

You just have to add a form validation function and give the elements some IDs so your validation function knows what to validate.
First, add this function under your <script> tag.
function validate_first() {
var msg1 = "Please select from first dropdown\n";
var msg2 = "Please select from second dropdown";
var first = document.getElementById('select1').value;
var second = document.getElementById('select2').value;
if(first=="" || second=="") {
alert(((first == "") ? msg1 : "") + ((second == "") ? msg2 : ""));
return false;
}
return true;
}
Then change onsubmit value from the form definition as follows:
<FORM onSubmit="this.target = 'paypal';
return validate_first();" action=https://www.paypal.com/cgi-bin/webscr method=post>
Finally, give the dropdowns some IDs, and add real values to the "Please Select" options.
For first dropdown:
<SELECT id="select1" STYLE="WIDTH: 240px" onChange="ReadForm (this.form);">
<OPTION value="" selected>Please select </OPTION>
<OPTION VALUE="option1 +125.00">option1</OPTION>
<OPTION VALUE="option2 +90.00">option2</OPTION>
<OPTION VALUE="option3 +40.00">option3</OPTION>
</SELECT>
Second one:
<SELECT id="select2" STYLE="WIDTH: 240px" onChange="ReadForm (this.form);">
<OPTION value="" selected>Please select </OPTION>
<OPTION VALUE="option1 +55.00">option1</OPTION>
<OPTION VALUE="option2 +99.00">option2</OPTION>
<OPTION VALUE="option3 +44.00">option3</OPTION>
</SELECT>
That's it.

Here is an example with a few different ideas that may be helpful:
jsFiddle Demo
HTML:
<div id="msg">Please select from each of the following:</div>
Model:
<select id="car">
<option value="">Select One</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Color:
<select id="color">
<option value="">Select One</option>
<option value="white">White</option>
<option value="black">Black</option>
</select>
Transmission:
<select id="tran">
<option value="">Select One</option>
<option value="manual">Manual</option>
<option value="auto">Automatic</option>
</select>
<br />
<input type="button" id="mybutt" value="Submit" />
jQuery/javascript:
var chkFld, arrAll = {'Vehicle Model':'car','Vehicle Color':'color','Transmission':'tran'};
$('select').change(function(){
$('#msg').slideUp();
});
$('#mybutt').click(function() {
var errMsg='', badFlds='', firstBad='';
for(var key in arrAll){
chkFld = '#'+arrAll[key];
$(chkFld).removeClass('error');
if ($(chkFld).val() ==''){
$(chkFld).addClass('error');
//alert('Please complete field ' + arrAll[key] );
errMsg += '* ' + key + '\n';
if (firstBad=='') firstBad=chkFld;
}
}
if (errMsg != '') {
$('#msg').slideDown();
alert('Please complete: '+"\n"+errMsg);
$(firstBad).focus();
}
}); //END mybutt.click
CSS:
#msg{background:wheat;padding:10px;text-align:center;color:darkcyan;margin-bottom:10px;}
.error{border:1px solid red;background:yellow;}
#mybutt{margin-top:10px;}

Related

Multiple Select boxes with JS function, doesn't work with array

I have the following code which creates two multiple selects that use js to move values between each other. The code as it is below functions but I wish to use the POST data values for the items in the select. I wish to change to so that I can get the array of values of post in PHP but when I change it to an array[] it doesn't function moving the values between the two select boxes.
<html>
<body>
<script>
function SelectMoveRows(SS1,SS2)
{
var SelID='';
var SelText='';
// Move rows from SS1 to SS2 from bottom to top
for (i=SS1.options.length - 1; i>=0; i--)
{
if (SS1.options[i].selected == true)
{
SelID=SS1.options[i].value;
SelText=SS1.options[i].text;
var newRow = new Option(SelText,SelID);
SS2.options[SS2.length]=newRow;
SS1.options[i]=null;
}
}
SelectSort(SS2);
}
function SelectSort(SelList)
{
var ID='';
var Text='';
for (x=0; x < SelList.length - 1; x++)
{
for (y=x + 1; y < SelList.length; y++)
{
if (SelList[x].text > SelList[y].text)
{
// Swap rows
ID=SelList[x].value;
Text=SelList[x].text;
SelList[x].value=SelList[y].value;
SelList[x].text=SelList[y].text;
SelList[y].value=ID;
SelList[y].text=Text;
}
}
}
}
</script>
<form name="example" method=post action=test.php >
<table border="0" cellpadding="3" cellspacing="0">
<tr>
<td>
<select multiple name="left" size="9">
<option value="1">Row 1</option>
<option value="2">Row 2</option>
<option value="3">Row 3</option>
<option value="4">Row 4</option>
<option value="5">Row 5</option>
</select>
</td>
<td align="center" valign="middle">
<input type="Button" value="Add >>" style="width:100px" onClick="SelectMoveRows(document.example.left,document.example.right)"><br>
<br>
<input type="Button" value="<< Remove" style="width:100px" onClick="SelectMoveRows(document.example.right,document.example.left)">
</td>
<td>
<select multiple name="right" size="9">
</select>
</td>
</tr>
</table>
<br><input type='submit' value='Submit'>
</form>
</body>
</html>
If you change it to name="left[]" then you have to change document.example.left to document.example['left[]'] to match it.
function SelectMoveRows(SS1, SS2) {
var SelID = '';
var SelText = '';
// Move rows from SS1 to SS2 from bottom to top
for (i = SS1.options.length - 1; i >= 0; i--) {
if (SS1.options[i].selected == true) {
SelID = SS1.options[i].value;
SelText = SS1.options[i].text;
var newRow = new Option(SelText, SelID);
SS2.options[SS2.length] = newRow;
SS1.options[i] = null;
}
}
SelectSort(SS2);
}
function SelectSort(SelList) {
var ID = '';
var Text = '';
for (x = 0; x < SelList.length - 1; x++) {
for (y = x + 1; y < SelList.length; y++) {
if (SelList[x].text > SelList[y].text) {
// Swap rows
ID = SelList[x].value;
Text = SelList[x].text;
SelList[x].value = SelList[y].value;
SelList[x].text = SelList[y].text;
SelList[y].value = ID;
SelList[y].text = Text;
}
}
}
}
<form name="example" method=post action=test.php>
<table border="0" cellpadding="3" cellspacing="0">
<tr>
<td>
<select multiple name="left[]" size="9">
<option value="1">Row 1</option>
<option value="2">Row 2</option>
<option value="3">Row 3</option>
<option value="4">Row 4</option>
<option value="5">Row 5</option>
</select>
</td>
<td align="center" valign="middle">
<input type="Button" value="Add >>" style="width:100px" onClick="SelectMoveRows(document.example['left[]'],document.example['right[]'])"><br>
<br>
<input type="Button" value="<< Remove" style="width:100px" onClick="SelectMoveRows(document.example['right[]'],document.example['left[]'])">
</td>
<td>
<select multiple name="right[]" size="9">
</select>
</td>
</tr>
</table>
<br><input type='submit' value='Submit'>
</form>
You could also give them IDs, and then use document.getElementById().

How to associate two inputs in JavaScript?

I have this code:
$(document).ready(function(){
$('.container select').each(function(){
$(this).on('change', function(){
var selectedVal = $(this).val();
//console.log(selectedVal);
});
});
$('input').on('change', function () {
var sum = 0;
$('input').each(function() {
sum += Number($(this).val());
});
$('.total span').html(sum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='full'>
<input type='number' value=''>
<select name='select1'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select2'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select3'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='total'>
Total nr: <span>5(2 A1, 3 A2)</span>
</div>
</div>
Is it possible that on change of the select and the input of type number to modify the total number like in the code above using JavaScript/jQuery?
Can anyone help me with this please.
On every change on the inputs or select fields I need to calculate total number of A1 and total number of A2. Hope this make sense. And display them beside the total number.
JSFiddle
We can't give you the full code but I tried to provide some logic for what you want.I think you want some thing like this:
//create a json to collect the sum of numbers
var number = {
a1: 0,
a2: 0,
a1_count:0,
a2_count:0
};
//check in select change
$(".select").change(function() {
//flush previous calculation before using again
number.a1=0,number.a2=0,number.a1_count=0,number.a2_count=0;
//check all the select value and get the corresponding input value
$(".select").each(function() {
var valueType = $(this).val();
if (valueType == "a1") {
number[valueType+"_count"]=number[valueType+"_count"]+1;
number[valueType] = number[valueType] + parseInt($(this).prev().val()||0);
} else if (valueType == "a2") {
number[valueType+"_count"]=number[valueType+"_count"]+1;
number[valueType] = number[valueType] + parseInt($(this).prev().val()||0);
}
});
$("#total").html('Total:'+(number.a1+number.a2)+',A1:'+number.a1+'('+number.a1_count+'),A2:'+number.a1+'('+number.a2_count+')');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='full'>
<input type='number' value=''>
<select name='select1' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select2' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select3' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='total' id="total">
</div>
</div>
This will work for any arbitrary list in the select.
function change() {
var res = {}, fulls = $('.container .full');
fulls.each(function(index){
var selected = $(this).find('select > option:selected').text();
if (! res[selected]) res[selected] = 0;
res[selected] += 1*$(this).find('input[type="number"]').val();
});
var detail = "", total = 0;
for(prop in res) {
if (res.hasOwnProperty(prop)) {
try {
var val = 1*res[prop];
detail += ", "+val+" "+prop;
total += val;
}catch(e){}
}
}
$('.total > span').text(""+total+" ("+detail.substr(2)+")");
}
$().add('.container .full input[type="number"]')
.add('.container .full select[name^="select"]')
.on('change', change);

Skip last Html row text box value and select on print

I am trying to create a query which inserts the data in to Mobile sqlite data base say for now i have three rows in a html table on button press a query is generated where it selects the value of the text box and the select selected value but the problem is on print it should skip the last rows value as in my case that is a auto increment table where a last row is left blank to fill in the data for the user.
Now
INSERT INTO demo (xxxx, xxxxx, xxxx,xxxx,xxxx) VALUES ("Mickey1","Mouse1","No Match"),("Mickey2","Mouse2","No Match"),("skip row","skip row","No Match");
Expected
INSERT INTO demo (xxxx, xxxxx, xxxx,xxxx,xxxx) VALUES ("Mickey1","Mouse1","No Match"),("Mickey2","Mouse2","No Match");
Demo Jsfiddle
JS
function Get() {
var html = '';
var arr = [];
$('tr').each(function() {
var inputs = $('input', this);
var selects = $('select :selected', this);
arr.push('("' + inputs[0].value + '","' + inputs[1].value + '","' + selects[0].text + '")');
});
html = 'INSERT INTO demo (xxxx, xxxxx, xxxx,xxxx,xxxx) VALUES ' + arr.join(',') + ';';
$('#data').html(html);
}
HTML
<form id="Form" onsubmit="return false;">
<table>
<tr>
<td>First name:
<input type="text" name="FirstName" value="Mickey1">
</td>
<td>Last name:
<input type="text" name="Lastname" value="Mouse1">
</td>
<td>Last name:
<select name="select2">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
</td>
</tr>
<tr>
<td>First name:
<input type="text" name="FirstName" value="Mickey2">
</td>
<td>Last name:
<input type="text" name="Lastname" value="Mouse2">
</td>
</td>
<td>Last name:
<select name="select2">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
</td>
</tr>
<tr>
<td>skip row
<input type="text" name="FirstName" value="skip row">
</td>
<td>skip row
<input type="text" name="Lastname" value="skip row">
</td>
</td>
<td>skip row
<select name="select2">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
</td>
</tr>
</table>
</form>
<input type="submit" name="Submit" onclick="Get();" />
<div id="data"></div>
If you add the index parameter to the each function you can edit your code to only display specific lines.
$('tr').each(function(index, me) {
if(index < $('tr').length - 1) {
var inputs = $('input', me);
var selects = $('select :selected', me);
arr.push('("' + inputs[0].value + '","' + inputs[1].value + '","' + selects[0].text + '")');
}
});
Also in each functions I believe this is not recommended. Adding the second argument to the function should act like this for the individual row (as I've have used me).
Here is a forked version of your Fiddle - https://jsfiddle.net/szkp0Lwq/1/
Edit
As per your comment below -
If you first want to validate your inputs you can do something like -
var valid = true;
$('tr').each(function(index, me) {
if(index < $('tr').length - 1 && valid) {
var inputs = $('input', me);
inputs.each(function(index, me) {
if($(me).val().length == 0)
valid = false;
});
var selects = $('select', me);
selects.each(function(index, me) {
if($(me)[0].selectedIndex == 0)
valid = false;
});
if(valid)
arr.push('("' + inputs[0].value + '","' + inputs[1].value + '","' + $(selects[0]).val() + '")');
}
});
if(valid)
..... submit query
else
alert("Form isn't valid!");
Fiddle - https://jsfiddle.net/o4b1rLns/2/
You could skip the row when you build the array, or only add the ones that doesnt have the "skip row" value, as below:
$('tr').each(function() {
var inputs = $('input', this);
var selects = $('select :selected', this);
if (inputs[0].value != "skip row") {
arr.push('("' + inputs[0].value + '","' + inputs[1].value + '","' + selects[0].text + '")');
}
});

how to get multiple inputs spontaneously in JavaScript

I am new to JavaScript and I am trying to make an html page with JavaScript inside it.
The idea is that, when someone selects the value of option from the select, it should generate automatically the fields of firstName, lastName etc depending on the number which is selected. If one is selected then it should have one field of firstName, lastName and if two is selected then it should generate two fields dynamically.
<select id="noOfAuthor" multiple="multiple">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
<option value="five">5</option>
</select>
If someone selects one then below there should be one code of
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
If we selects “2” then there should be two code asking
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
Title Name <input type="text" name="txtTitle2">
Author Name <input type="text" name="txtAuthor2" >
Copy right<input type="text" name="txtCopyrightYear2">
And so on and so forth.
I tried to write a code for doing this, but it is not working.
<html>
<head>
<title>Book Collection</title>
<script language="JavaScript">
function WBook(bookName, writer, yearPublished)
{
this.Title = bookName;
this.Author = writer;
this.CopyrightYear = yearPublished;
}
function showBook(oneBook)
{
var no = showChoices();
var i ;
for(i =0; i<no; i++)
{
document.frmBooks.txtTitle[i].value = oneBook.Title[i];
document.frmBooks.txtAuthor[i].value = oneBook.Author[i];
document.frmBooks.txtCopyrightYear[i].value = oneBook.CopyrightYear[i];
}
}
function displayCollection()
{
var aBook = new WBook("Visual C++ From the Ground Up", "John Paul Mueller", 1998);
showBook(aBook);
}
function showChoices(){
var noOfAuthor = document.getElementById("noOfAuthor");
var result = " You selected";
result += " \n";
for(i=0; i<noOfAuthor.length;i++){
currentOption = noOfAuthor[i];
if(currentOption.selected == true){
result += currentOption.value + "\n";
}
}
result += " \n";
alert(result);
return(result);
}
</Script>
</head>
<body>
<h1>Book Collection</h1>
<form name="frmBooks">
<input type="hidden" name="id" value="" required="true" /><br> <br>
<select id="noOfAuthor" >
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
<option value="five">5</option>
</select>
<button type="button" onclick="showChoices()">Submit</button>
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
Title Name <input type="text" name="txtTitle2">
Author Name <input type="text" name="txtAuthor2" >
Copy right<input type="text" name="txtCopyrightYear2">
<p><input type="button" value="Show Collection" name="btnShow" onClick="displayCollection()">
</form>
</body>
</html>
You can solve it like this (jsFiddle demo):
<html>
<head>
<title>Book Collection</title>
<script language="JavaScript">
function WBook(bookName, writer, yearPublished)
{
this.Title = bookName;
this.Author = writer;
this.CopyrightYear = yearPublished;
}
function showBook(oneBook)
{
var no = showChoices();
var i ;
for(i =0; i<no; i++)
{
document.frmBooks.txtTitle[i].value = oneBook.Title[i];
document.frmBooks.txtAuthor[i].value = oneBook.Author[i];
document.frmBooks.txtCopyrightYear[i].value = oneBook.CopyrightYear[i];
}
}
function displayCollection()
{
var aBook = new WBook("Visual C++ From the Ground Up", "John Paul Mueller", 1998);
showBook(aBook);
}
function showChoices(){
var noOfAuthor = document.getElementById("noOfAuthor");
var result = " You selected";
result += " \n";
result += noOfAuthor.value
for(i=1; i <= noOfAuthor.length;i++){
if(i <= noOfAuthor.value){
document.getElementById("inputs" + i).style.display = 'block';
} else {
document.getElementById("inputs" + i).style.display = 'none';
}
}
result += " \n";
alert(result);
return(result);
}
</Script>
</head>
<body>
<h1>Book Collection</h1>
<form name="frmBooks">
<input type="hidden" name="id" value="" required="true" /><br> <br>
<select id="noOfAuthor" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button type="button" onclick="showChoices()">Submit</button>
<div id="inputs1">
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
</div>
<div id="inputs2" style="display:none">
Title Name <input type="text" name="txtTitle2">
Author Name <input type="text" name="txtAuthor2" >
Copy right<input type="text" name="txtCopyrightYear2">
</div>
<div id="inputs3" style="display:none">
Title Name <input type="text" name="txtTitle3">
Author Name <input type="text" name="txtAuthor3" >
Copy right<input type="text" name="txtCopyrightYear3">
</div>
<div id="inputs4" style="display:none">
Title Name <input type="text" name="txtTitle4">
Author Name <input type="text" name="txtAuthor4" >
Copy right<input type="text" name="txtCopyrightYear4">
</div>
<div id="inputs5" style="display:none">
Title Name <input type="text" name="txtTitle5">
Author Name <input type="text" name="txtAuthor5" >
Copy right<input type="text" name="txtCopyrightYear5">
</div>
<p><input type="button" value="Show Collection" name="btnShow" onClick="displayCollection()">
</form>
</body>
</html>
very simple with jquery:
<select id="noOfAuthor" multiple="multiple">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div id="inputs"></div>
$( document ).ready(function() {
$("select#noOfAuthor > option").click(function() {
$( "#noOfAuthor" ).attr("disabled", true);
var howMuch = parseInt($( "#noOfAuthor" ).val());
for(i = 0; i < howMuch; i++) {
$( "#inputs" ).append('Title Name: <input type="text" name="txtTitle' + i + '"><br>Author Name: <input type="text" name="txtAuthor' + i + '"><br>Copy right: <input type="text" name="txtCopyrightYear' + i + '"><br><hr />');
}
});
});
So you get inputs as the selected number.
the Three first willl be:
name="txtTitle0"
name="txtAuthor0"
name="txtCopyrightYear0"
demo: http://jsfiddle.net/mxgbc/3/
I would generate the inputs and labels dynamically. This is a pure javascript example, without using jQuery. I can provide a jQuery solution if you need it.
Example http://jsfiddle.net/A62qA/1 // basic select menu
Example http://jsfiddle.net/A62qA/2/ // mutiple choice select menu
HTML
<select id="noOfAuthor" onchange="inputFunction(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div id="myContainer"></div>
JavaScript
function createInputs(i) {
var myContainer = document.getElementById("myContainer");
var titleName = document.createElement("input");
titleName.setAttribute('name', 'txtTitle1' + i);
var label = document.createElement("Label");
label.innerHTML = "Title Name";
myContainer.appendChild(label);
myContainer.appendChild(titleName);
var authorName = document.createElement("input");
authorName.setAttribute('name', 'txtAuthor1' + i);
var label = document.createElement("Label");
label.innerHTML = "Author Name";
myContainer.appendChild(label);
myContainer.appendChild(authorName);
var copyRight = document.createElement("input");
copyRight.setAttribute('name', 'txtCopyrightYear1' + i);
var label = document.createElement("Label");
label.innerHTML = "CopyRight";
myContainer.appendChild(label);
myContainer.appendChild(copyRight);
}
function inputFunction(y) {
var y = y.value;
var myContainer = document.getElementById("myContainer");
for (var i = 0; i < y; i++) {
createInputs(i);
}
}

Form submit in javascript

Hi been wrestling this form and the last step (actually submitting) has me scratching my head. What I have so far is the form:
<form id="theForm" method='post' name="emailForm">
<table border="0" cellspacing="2">
<td>Email <span class="red">*</span></td><td><input type='text'class="validate[required,custom[email]]" size="30"></td></tr>
<td>First Name:</td><td><input type='text' name='email[first]' id='first_name' size=30></td></tr>
<tr height="30">
<td cellpadding="4">Last Name:</td><td><input type='text' name='email[last]' id='e_last_name' size=30>
<td>Birthday</td>
<td><select name='month' style='width:70px; margin-right: 10px'>
<option value=''>Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
....
</select><select name='day' style='width:55px; margin-right: 10px'>
<option value=''>Day</option>
<option value="1">1</option>
<option value="2">2</option>
...
<option value="31">31</option>
</select><select name='year' style='width:60px;' >
<option value=''>Year</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
...
</select>
<input type='image' src='{{skin url=""}}images/email/signUpButt.gif' value='Submit' onClick="return checkAge()" />
<input type="hidden" id= "under13" name="under13" value="No">
and a script that checks the age and sets a cookie/changes display
function checkAge()
{
var min_age = 13;
var year = parseInt(document.forms["emailForm"]["year"].value);
var month = parseInt(document.forms["emailForm"]["month"].value) - 1;
var day = parseInt(document.forms["emailForm"]["day"].value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ( (today.getTime() - theirDate.getTime()) < 0) {
var el = document.getElementById('emailBox');
if(el){
el.className += el.className ? ' youngOne' : 'youngOne';
}
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
createCookie('age','not13',0)
return false;
}
else {
createCookie('age','over13',0)
return true;
}}
that all seems to be working well.. just missing kind of a crucial step of actually submitting the form if it validates (if they pass the age question). So I am thinking that this will be wrapped in that script.. something in here :
else {
createCookie('age','over13',0)
return true;
}
Can someone please help me figure out how I could handle this submit?
You would call
var form = document.getElementById('theForm');
if(form != null)
form.submit();
And that would post the data to the server.

Categories