Newbie here. Using html and Javascript. It was working until I added a side menu. I had it set up with the submit button inside the side menu under the download function. I only included code for the first few questions and answers. The image local storage work sometimes. I'm running it on notepad++ and with chrome.
function save() {
//question1
var question1 = document.getElementById("question1")
var correctanswer1 = document.getElementById("correctanswer1");
var incorrect11 = document.getElementById("incorrect11");
var incorrect12 = document.getElementById("incorrect12");
var incorrect13 = document.getElementById("incorrect13");
try {
//question1
localStorage.setItem("question1", question1.value);
sessionStorage.setItem("question1", question1.value);
localStorage.setItem("correctanswer1", correctanswer1.value);
sessionStorage.setItem("correctanswer1", correctanswer1.value);
localStorage.setItem("incorrect11", incorrect11.value);
sessionStorage.setItem("incorrect11", incorrect11.value);
localStorage.setItem("incorrect12", incorrect12.value);
sessionStorage.setItem("incorrect12", incorrect12.value);
localStorage.setItem("incorrect13", incorrect13.value);
sessionStorage.setItem("incorrect13", incorrect13.value);
//question 1
question1value = "";
correctanswer1value = "";
incorrect11.value = "";
incorrect12.value = "";
incorrect13.value = "";
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
console.log("Error: Local Storage limit exceeds.");
} else {
console.log("Error: Saving to local storage.");
}
}
}
<div id="sidebar">
<ul>
Top of Page
<p>Download </p>
<p>
Submit </ul>
</p>
</div>
<div class="center">
Enter Question 1:
<input type="text" id="question1" name="Question 1" size="40">
<br>
<br> Next, add a correct answer
<font color="#51096F"> FIRST </font> and then the incorrect answers for your question.
<br>
<p>
<input type="text" id="correctanswer1" name="correctanswer1" size="50" style="border:2px solid #660570">
</p>
<p>
<input type="text" id="incorrect11" name="incorrect11" size="50">
</p>
<p>
<input type="text" id="incorrect12" name="incorrect12" size="50">
</p>
<p>
<input type="text" id="incorrect13" name="incorrect13" size="50">
</p>
<br>
<img id="uploadPreview1" style="width: 100px; height: 100px;" />
<input id="uploadImage1" type="file" name="myPhoto1" onchange="PreviewImage1();" />
<script type="text/javascript">
function PreviewImage1() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage1").files[0]);
oFReader.onload = function(oFREvent) {
document.getElementById("uploadPreview1").src = oFREvent.target.result;
sessionStorage.setItem("image", oFREvent.target.result);
localStorage.setItem("image", oFREvent.target.result);
};
};
</script>
</div>
Related
I have been searching for an answer everywhere but just can not find what I need.
I have a webpage that has an HTML table on the left column and an HTML form on the right column. When I click on a row in the table on the left I want it to display the values in the form on the right.
I have this working perfectly for the text fields on the form, but not for the two checkboxes. My javascript will return either true or false or checked and unchecked to the document.getElementById within the script itself by using alert(); but I have no idea what it needs to allow the checkboxes to display these values. I thought the document.getElementById would return the values but it seems it does not.
I have tried all kinds of conveluted ways to get this to work but can not seem to get the correct code needed.
I am new to all this so there is most likely something really simple I am missing.
This is the HTML form code:
<div class="column right">
<table>
<tr></tr>
<tr>
<div class="lockinv">
<form autocomplete="off" name="lockform" class="keyassign" action="includes/lockinventory.inc.php"
method="post">
<label id="inventory" for="locknum">Lock Number</label>
<input id="invlocknum" type="text" name="locknum" value="" required>
<label id="inventory" for="locktype">Lock Type</label>
<input id="invlocktype" type="text" name="locktype" value="" required>
<label id="inventory" for="keycode">Key Code</label>
<input id="invkeycode" type="text" name="keycode" value="" required>
<label id="inventory" for="lockengraved">Lock Engraved</label>
<input id="invlockengraved" type="hidden" name="lockengraved" value="0">
<input id="invlockengraved" type="checkbox" name="lockengraved" value="1">
<label id="inventory" for="lockmastered">Lock Mastered</label>
<input id="invlockmastered" type="hidden" name="lockmastered" value="0">
<input id="invlockmastered" type="checkbox" name="lockmastered" value="1">
<label id="inventory" for="locknote">Lock Note</label>
<textarea id="inventorynote" name="locknote" rows="5" cols="60"></textarea>
<div class="wheel">
<?php
if (isset($_GET["error"])) {
if($_GET["error"] == "lockexists") {
echo "<p>Lock Already In Inventory!</p>";
}
else if ($_GET["error"] == "lockexistsfailed") {
echo "<p>Lock Already In Inventory!</p>";
}
}
?>
</div>
<input id="bt6" type="submit" name="submit" value="Save">
<button id="bt6" type="reset" name="button">Cancel</button>
</form>
</div>
</tr>
</table>
</div>
This is my JavaScript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript"></script>
<script>
$(function () {
$('#lockTable td').click(function () {
var currentRow = $(this).closest("tr");
var locknum = currentRow.find("td:eq(0)").text();
var locktype = currentRow.find("td:eq(1)").text();
var keycode = currentRow.find("td:eq(2)").text();
var engraved = currentRow.find("td:eq(3)").find(":checkbox");
var mastered = currentRow.find("td:eq(4)").find(":checkbox");
var locknote = currentRow.find("td:eq(5)").text();
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
$grved = "checked";
} else {
$grved = "unchecked";
}
var lockmastered = mastered.prop("checked");
if (lockmastered === true) {
$msted = "checked";
} else {
$msted = "unchecked";
}
document.getElementById('invlocknum').value = locknum;
document.getElementById('invlocktype').value = locktype;
document.getElementById('invkeycode').value = keycode;
document.getElementById("invlockengraved").value = $grved;
document.getElementById('invlockmastered').value = $msted;
document.getElementById('inventorynote').value = locknote;
alert(document.getElementById("invlockengraved").value);
alert(document.getElementById("invlockmastered").value);
});
});
</script>
<p id="invlocknum"></p>
<p id="invlocktype"></p>
<p id="invkeycode"></p>
<p id="invlockengraved"></p>
<p id="invlockmastered"></p>
<p id="invlocknote"></p>
<p id="info"></p>
<p id="result"></p>
I found the answer to my issue. I had to modify my if statement in the Javascript to the following. Works the way I want it to. Thanks to all that helped.
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
document.getElementById("invlockengraved").checked = lockengraved;
}else if (lockengraved === false) {
document.getElementById("invlockengraved").checked = lockengraved;
}
I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.
Starting page HTML:
<form id="memCat" methed="get" class="member_catalogue">
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
<div class="cat_block">
<label class="cat_label" for="cat_name">Product Name:</label>
<input class="cat_input" type="text" id="catID" value="bepot002" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_description">Product Description:</label>
<input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_price">Per unit price:$</label>
<input class="cat_input" type="number" id="catVal" value="10" readonly>
</div>
</form>
New page HTML:
<form id="memOrder" method="post">
<div>
<label for="pname">Product Name:</label>
<input type="text" id="orderID" readonly>
</div>
<div>
<label for="pdescription">Product Description:</label>
<input type="text" id="orderDesc" readonly>
</div>
<div>
<label for="quantity">Quantity ordered:</label>
<input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
</div>
<div>
<label for="ind_price">Per unit price: $</label>
<input type="number" class="quantCount" id="orderVal" readonly>
</div>
<div>
<label for="tot_price">Total Price: $</label>
<input type="number" class="quantCount" id="orderTotal" readonly>
</div>
<div>
<button type="reset">Clear Order</button>
<button type="submit" id="orderCalc">Calculate Total</button>
<button type="submit" id="orderPlace">Place Order</button>
</div>
</form>
Script i have to date:
function openMemberOrder() {
document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
script and other meta tags in head are correct as other code is working correctly.
So after much trial and error i have had success with this:
On the submission page:
1. I created a button on the page that will capture the input form data
2. i created the localstorage function in JS
3. I then placed the script tag at the bottom of the page before the closing body tag
HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>
Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;
function openMemberOrder() {
var memberOrderWindow;
localStorage.setItem("catID", document.getElementById("catID").value);
localStorage.setItem("catDesc", document.getElementById("catDesc").value);
localStorage.setItem("catVal", document.getElementById("catVal").value);
memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;
Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
I then created the new page with the following javascript in the header loading both an image grid as well as input element values:
var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');
for (var rowN=1; rowN<5; rowN++) {
for (var colN = 1; colN < 6; colN++){
urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
}
}
window.onload = function urlLoad(){
document.getElementById('gridContainer').innerHTML = urlArray;
document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
};
I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.
function total() {
var Quantity = document.getElementById('orderQuant').value;
var Value = document.getElementById('orderVal').value;
var Total = Quantity * Value;
document.getElementById('orderTotal').value = Total;
}
function clearForm() {
var i = 0;
var j = 0;
document.getElementById('orderQuant').value = i;
document.getElementById('orderTotal').value = j;
}
I'm trying to create a form with HTML and javascript to be able to retrieve 3 different inputs from the user, combine them into 1 form in json format, and save the file into a local file location. Below is what I currently have. (I am unclear how I am able to save a json string to a local file location. Thank you for your time in advance. (I am a javascript and html novice)
<header class="banner">
<h1 style="color:blue">HTML User Input to local file location</h1><main>
<form id="myform" type="post">
<fieldset>
<legend style="color:blue">Sign Up</legend>
<p style="color:red">Write your con-fig codes below</p>
<div class="elements">
<label for="Input1">Input1 :</label>
<input required="required" type="text" onfocus="this.value=''" value="Input1"
name="Input1" size="25" />
</div>
<div class="elements">
<label for="Input2">Input2 :</label>
<input required="required" type="text" onfocus="this.value=''" value="Input2"
name="Input2" size="25" />
</div>
<div class="elements">
<label for="Input3">Input3 :</label>
<input required="required" type="text" onfocus="this.value=''" value="Input3"
name="Input3" size="25" />
</div
<div class="submit">
<input type="submit" id="btn" name="submit" class="btn" value="Send" />
</div>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function(e) {
var jsonData = {};
var formData = JSON.stringify($("#myForm").serializeArray());
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
e.preventDefault();
});
});
</script>
</main>
This has definitely been asked before in multiple places. Like Here and Here. Code copied from one of the links below
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
Credit to #Rafał Łużyński.
Please search for the solutions better before actually asking a question.
I'm working on a small, temporary site that will be used for collecting some names.
The idea is that people fill in the number of their class and their name and once they press a button, these two values are added to the page and can be viewed by everyone who visits the site.
I've already made a concept of this using javascript: www.googledrive.com/host/0B_eZKT0Ni3-tOXF5OVVQeWZRRjQ
The only problem is that the items aren't really stored on the site. As far as I know, you can only accomplish this using a database, but I have no experience with linking a database to a webpage.
Can someone help me with this or does someone know a source where I can find a solution for this? My searches turned up nothing.
I'm sorry if I'm sounding like a "help vampire". I only turned to you guys for a solution because I can't find it anywhere else.
HTML:
<body>
<div id="wrapper">
<div id="header">
<h2 id="title">Italiëreis 2015: opdiening tijdens quiz</h2>
</div>
<div id="content">
<!-- eerste ploeg -->
<div class="L">
<p id="kop">Ploeg 1</p>
<p class="klas"><input type="text" id="klas1" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam1" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText1()" value="Schrijf in" class="button" />
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst1"></ol>
</div>
</div>
<!-- tweede ploeg -->
<div class="L">
<p id="kop">Ploeg 2</p>
<p class="klas"><input type="text" id="klas2" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam2" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText2()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst2"></ol>
</div>
</div>
<!-- derde ploeg -->
<div class="L">
<p id="kop">Ploeg 3</p>
<p class="klas"><input type="text" id="klas3" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam3" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText3()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst3"></ol>
</div>
</div>
<!-- vierde ploeg -->
<div class="L">
<p id="kop">Ploeg 4</p>
<p class="klas"><input type="text" id="klas4" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam4" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText4()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst4"></ol>
</div>
</div>
</div>
<div id="footer">
<div id="credits">Code geschreven door Bert-Jan van Dronkelaar - 6E</div>
</div>
</div>
CSS is irrelevant.
Javascript:
//eerste ploeg
function changeText1() {
var klas1 = document.getElementById('klas1').value;
var naam1 = document.getElementById('naam1').value;
if (document.getElementById('klas1').value != "" && document.getElementById('naam1').value != "") {
var node = document.createElement("LI");
var textnode1 = document.createTextNode(klas1 + " " + naam1);
node.appendChild(textnode1);
document.getElementById("lijst1").appendChild(node);
}
}
//tweede ploeg
function changeText2() {
var klas2 = document.getElementById('klas2').value;
var naam2 = document.getElementById('naam2').value;
if (document.getElementById('klas2').value != "" && document.getElementById('naam2').value != "") {
var node = document.createElement("LI");
var textnode2 = document.createTextNode(klas2 + " " + naam2);
node.appendChild(textnode2);
document.getElementById("lijst2").appendChild(node);
}
}
//derde ploeg
function changeText3() {
var klas3 = document.getElementById('klas3').value;
var naam3 = document.getElementById('naam3').value;
if (document.getElementById('klas3').value != "" && document.getElementById('naam3').value != "") {
var node = document.createElement("LI");
var textnode3 = document.createTextNode(klas3 + " " + naam3);
node.appendChild(textnode3);
document.getElementById("lijst3").appendChild(node);
}
}
//vierde ploeg
function changeText4() {
var klas4 = document.getElementById('klas4').value;
var naam4 = document.getElementById('naam4').value;
if (document.getElementById('klas4').value != "" && document.getElementById('naam4').value != "") {
var node = document.createElement("LI");
var textnode4 = document.createTextNode(klas4 + " " + naam4);
node.appendChild(textnode4);
document.getElementById("lijst4").appendChild(node);
}
}
#SpencerWieczorek is not wrong, PHP and MySql will work for what you need. However, there is a bit of a learning curve there.
For a beginner, I'd recommend using Parse. It's free and it makes saving and retrieving data trivial. Below is simple app that lets the user input a class year and their name and saves them so others can see them on the same page.
The snippet here wont work due to SO restrictions...
...but here is a working jsfiddle
This is accomplished with plain ole javascript BTW
To get this going on your own you'll need to:
You'll need to go to https://www.parse.com/#signup and create an account with them
Go to https://www.parse.com/apps/new and create an app
add this in your html's head tag <script type="text/javascript" src="https://www.parsecdn.com/js/parse-1.3.0.min.js"></script>
Go to https://www.parse.com/apps/quickstart#parse_data/web/new, select your app from the dropdow (top-ish right) the Parse.initialize() function will be shown here with your app's Application ID and JavaScript key, copy this line for later
Replace the Parse.initialize() function in my example with the one you copied in step 4
Read up on the their javascript guide here to see what all you can do with parse
for a more indepth look, check out the Parse JavaScript SDK & Cloud Code Reference
You can also interact with parse with other scripting languages if you'd like.
Parse is free up to a certain amount of usage. I have one app that's used daily by 100+ users and doesn't come anywhere near having to pay anything.
Parse.initialize("Application ID", "JavaScript key");
function saveInput(){
//get our new values
var klassYear = document.getElementById('klassYear').value.trim();
var studentName = document.getElementById('studentName').value.trim();
// dont continue if either value is blank
if(klassYear=="" ||studentName=="" ){
alert ('Please fill in both fields.') ;
return;
}
// create the `Parse` object
var Klass = Parse.Object.extend("Klass");
var _klass = new Klass();
// set the object's values to our input values
_klass.set("klassYear", klassYear);
_klass.set("studentName", studentName);
// save the object
_klass.save(null, {
success: function(_klass) {
// if the save succeeded, add the new info to our page
retrieveSavedInputs()
},
error: function(_klass, error) {
// save failed, do error handeling here
console.log('Failed to create new object, with error code: ' + error.message);
}
});
}
function retrieveSavedInputs(){
// create a query to search for our `Klass` items
var Klass = Parse.Object.extend("Klass");
var query = new Parse.Query(Klass);
query.find({
success: function(results) {
// get our table's `tbody` and clear it
var myTbl = document.getElementById('mytbl');
myTbl.innerHTML='';
// `results` is an array of all the matches
// loop through each
for(var i =0; i < results.length; i++){
// get the values from the saved object
// note that `klassYear` and `studentName`
// are not available within the scope of the `success` function
var k = results[i].get("klassYear")
var s = results[i].get("studentName")
// create a table row with the info and add it at the top of `contents`
myTbl.innerHTML = '<tr><td>'+k+'</td><td>'+s+'</td></tr>' + myTbl.innerHTML;
}
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
// load all previously saved items
window.onload = retrieveSavedInputs();
//clcik handeler for the btn
document.getElementById("myBtn").addEventListener('click', saveInput , false);
table{
margin-top:50px;
}
Class Year: <input type="text" id="klassYear" value=""/> <br>
Name: <input type="text" id="studentName" value=""/> <br>
<input type="button" id="myBtn" value="Submit" class="button" />
<br> Add a ame and year above and see it added to the list below
<div id="myDiv"></div>
<table width="400" border="1">
<thead>
<tr>
<th scope="col">Class Year</th>
<th scope="col">Student Name</th>
</tr>
</thead>
<tbody id="mytbl">
</tbody>
</table> Class Year: <input type="text" id="klassYear" value=""/> <br>
Name: <input type="text" id="studentName" value=""/> <br>
<input type="button" id="myBtn" value="Submit" class="button" />
<br> Add a ame and year above and see it added to the list below
<div id="myDiv"></div>
<table width="400" border="1">
<thead>
<tr>
<th scope="col">Class Year</th>
<th scope="col">Student Name</th>
</tr>
</thead>
<tbody id="mytbl">
</tbody>
</table>
i have a form and would like to give users the ability to duplicate a group of fields as many times as necessary. With one group it iterates correctly but when I add a second group the "current" variable iterates collectively instead of being unique to each group... i tried changing all of the "current" to "newFieldset.current" but that returns NAN... any ideas?
<script type="text/javascript">
$(document).ready(function() {
var current = 0;
//Add New Fieldset with Button
var newFieldset = {
init: function(groupIndex) {
current++;
$newPerson= $("#Template"+groupIndex).clone(true);
$newPerson.children("p").children("label").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("for",$currentElem.attr("for")+current);
});
$newPerson.children("p").children("input").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("name",$currentElem.attr("name")+current);
$currentElem.attr("value",$currentElem.attr("value")+groupIndex+current);
$currentElem.attr("id",$currentElem.attr("id")+current);
});
$newPerson.appendTo("#mainField"+groupIndex);
$newPerson.removeClass("hideElement");
},
currentID: null,
obj: null
};
$(".addButton").each(function() {
$(this).click(function() {
var groupIndex = $(this).attr("title");
//newFieldset.obj = this;
//var fieldIndex = $(this).attr("class");
newFieldset.init(groupIndex);
});
});
console.log('r');
});
</script>
<style>
.hideElement {display:none;}
</style>
<form name="demoForm" id="demoForm" method="post" action="#">
<div id="groupCtr1">
<fieldset id="mainField1">
<div id="Template1" class="hideElement">
<p>
<label for="firstname">Name</label> <em>*</em>
<input id="firstname" name="firstname" size="25" /> <input id="lastname" name="lastname" size="25" />
</p>
<p>
<label for="email">Email</label> <em>*</em><input id="email" name="email" size="25" />
</p>
</div>
<div>
<p>
<label for="firstname1">Name</label>
<em>*</em> <input id="firstname1" name="firstname1" size="25" /> <input id="lastname1" name="lastname1" size="25" />
</p>
<p>
<label for="email1">Email</label>
<em>*</em><input id="email1" name="email1" size="25" />
</p>
</div>
</fieldset>
<p>
<input type="button" class="addButton" title="1" value="Add Another Person">
</p>
</div>
<div id="groupCtr2">
<fieldset id="mainField2">
<div id="Template2" class="hideElement">
<p>
<label for="coname">Company Name</label> <em>*</em>
<input id="coname" name="coname" size="25" />
</p>
<p>
<label for="codesc">Description</label> <em>*</em><input id="codesc" name="codesc" size="25" />
</p>
</div>
<div>
<p>
<label for="coname1">Company Name</label>
<em>*</em> <input id="coname1" name="coname1" size="25" />
</p>
<p>
<label for="codesc1">Description</label>
<em>*</em><input id="codesc1" name="codesc1" size="25" />
</p>
</div>
</fieldset>
<p>
<input type="button" class="addButton" title="2" value="Add Another Company">
</p>
</div>
<input type="submit" value="Save">
</form>
Attach the value to the element with the jQuery data method. Increment it on click, and then pass it to the newFieldset.init method as the second param. Voila!
$(document).ready(function() {
//Add New Fieldset with Button
var newFieldset = {
init: function(groupIndex,current) {
$newPerson= $("#Template"+groupIndex).clone(true);
$newPerson.children("p").children("label").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("for",$currentElem.attr("for")+current);
});
$newPerson.children("p").children("input").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("name",$currentElem.attr("name")+current);
$currentElem.attr("value",$currentElem.attr("value")+groupIndex+current);
$currentElem.attr("id",$currentElem.attr("id")+current);
});
$newPerson.appendTo("#mainField"+groupIndex);
$newPerson.removeClass("hideElement");
},
currentID: null,
obj: null
};
$(".addButton").click(function() {
var groupIndex = $(this).attr("title");
var current = $(this).data('current');
$(this).data('current',++current);
//newFieldset.obj = this;
//var fieldIndex = $(this).attr("class");
newFieldset.init(groupIndex,current);
}).data('current',0);
console.log('r');
});
Happy jquery-ing to you sir.
if you dont make the current variable global it will should work. try this:
var newFieldset = {
current: 0,
init: function() {
this.current++;
//rest of init code
},
//all your other fieldset code here
};
/* all other code */
EDIT: After re-reading the question, I would take a completely different approach to what you're trying to achieve. The above code will still exhibit the same behavior for you. If the question hasn't been successfully answered I'll do a bigger writeup when i get home.
I would do something like that:
...
var currents = {};
var newFieldset = {
init: function(groupIndex) {
var current = 0;
if (currents[groupIndex]) {
current = currents[groupIndex];
}
++current;
currents[groupIndex] = current;
...