Should be simple but I can't work it out.
I've got a page with a table, within that table is an autocomplete and a button, I want to locate the autocomplete when I click the button and make it disabled or enabled. The disable/enabled part isn't the problem, I can't get it to traverse the heirarchy to find the autocomplete in the first place. Here's the chunk of html I've got: -
<td colspan="3">
<fieldset class="buttons">
<div>
<input class='required' style='width:400px' type='text' id='autoLook[0]' name='autoLook[0].id' value='' title='' />
<div class='searchcontainer yui-skin-sam' id='abb890644f19d382ef69951344848d878'></div>
<script type='text/javascript'> var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/FARTFramework/form/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
;
autoComplete = new YAHOO.widget.AutoComplete('autoLook[0]','abb890644f19d382ef69951344848d878', autoCompleteDataSource);
autoComplete.queryDelay = 0;
autoComplete.prehighlightClassName = 'yui-ac-prehighlight';
autoComplete.useShadow = false;
autoComplete.minQueryLength = 3;
autoComplete.typeAhead = false;
autoComplete.forceSelection = true;
autoComplete.maxResultsDisplayed = 20;
autoComplete.shadow = false;
var itemSelectHandler = function(sType, args) {
var autoCompleteInstance = args[0];
var selectedItem = args[1];
var data = args[2];
var id = data[1];
updateHiddenInput(id, 0, 'forms') };
autoComplete.itemSelectEvent.subscribe(itemSelectHandler);
</script>
</div>
<input type="button" id="EnableDisable" value="Edit" onclick="enabledisable($(this))" />
<input type="hidden" class="required" id="forms[0]" name="forms[0].id" value="" />
<input type="hidden" class="required" id="oldvalue[0]" name="oldvalue[0].id" value="" />
<input type="button" value="Remove Form" onclick="globalRemoveRow($(this),'forms')" />
<input type="button" value="Insert New Form Above" onclick="addRowWithin('/FARTFramework/testScenario/ajaxNewFormFragment',$(this))" />
<input type="button" value="Go to Form Definition" onclick="gotoNew('/FARTFramework/form/edit/',$(this))" />
</fieldset>
<div id="hideDIV">
<table name="formSubTable[0]" id="formSubTable[0]">
</table>
</div>
</td>
The button I'm clicking is called "EnableDisable" and in the javascript I can do this: -
function enabledisable(theButton){
$thebutton = $(theButton)
$theInput = $thebutton.closest('td')
var myValue = $theInput.html();
alert(myValue)
}
Which returns this: -
<fieldset class="buttons">
<div class="yui-ac">
<input required="required" autocomplete="off" class="required yui-ac-input" style="width:400px" id="autoLook[0]" name="autoLook[0].id" value="" title="" type="text">
<div class="searchcontainer yui-skin-sam yui-ac-container" id="af745a9597adf2dd98aeab126bc31bcb9"><div style="display: none;" class="yui-ac-content"><div style="display: none;" class="yui-ac-hd"></div><div class="yui-ac-bd"><ul><li style="display: none;"></li><li style="display: none;"></li><li style="display: none;"></li><li style="display: none;"></li><li style="display: none;"></li><li style="display: none;"></li><li style="display: none;"></li><li style="display: none;"></li><li style="display: none;"></li><li style="display: none;"></li></ul></div><div style="display: none;" class="yui-ac-ft"></div></div></div>
<script type="text/javascript"> var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/FARTFramework/form/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
I can see the input I want is the third line down, the first input there is in that html. But when I try to expand the jquery to $thebutton.closest('td').children('input').eq(0) I get undefined returned.
I've tried all manner of first, next etc but no luck. I know that the input will have the text autolook[xx] in it but there will be loads with that id and I can't tell what the number will be to just look for a specific id or name so need to traverse the html to find it...
Try using .find()
$thebutton.closest('td').find('input[type='text'])
Or
$thebutton.closest('td').find('input')
Or
$thebutton.closest('td').find('input:first')
try tho change this:
function enabledisable(theButton){
$thebutton = $(theButton)
$theInput = $thebutton.closest('td')
var myValue = $theInput.html();
alert(myValue)
}
to this:
$('#EnableDisable').click(function(){
var myValue = $(this).closest('td').find('input').val();
alert(myValue)
});
and your html changed:
<input type="button" id="EnableDisable" value="Edit" />
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;
}
So I'm still new to JS and jQuery, but I'm trying to learn how to get all the elements and the values inside a div when I click a button inside it.
I was able to get it working for a form when I used FormData to do it. I can't figure out how to do it with a div instead of a form. (I would just use a form, but can't for this unfortunately.)
Here is what I got so far, but I know I'm doing something wrong.
$('button.browsePageImages').on('click', (function(e) {
e.preventDefault();
console.log("Attempting Image Browsing: ");
var myArea = $(this).closest("div");
console.log(myArea);
var myAreaData = new FormData(myArea[0]);
console.log(myAreaData);
var myFormID = $(this).closest("div").attr("id");
console.log(myFormID);
var dataHref = $(this).attr('data-href');
console.log(dataHref);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" id="browseImagesDiv">
<h4>Image (Optional) <span></h4>
<input type="text" class="form-control" name="description" value="This is the image description." />
<input type="text" class="form-control" id="areaSection-15" name="image_url" value="" placeholder="Image URL Here"/>
<button type="button" class="btn btn-white btn-xs browsePageImages" data-href="15">Save Image Info</button></span>
</div>
You can use serializeArray for each input.
var myArea = $(this).closest("div").find(':input');
var myAreaData = myArea.serializeArray();
$('button.browsePageImages').on('click', (function(e) {
e.preventDefault();
console.log("Attempting Image Browsing: ");
var myArea = $(this).closest("div").find(':input');
//console.log(myArea);
var myAreaData = myArea.serializeArray();
console.log(myAreaData);
var myFormID = $(this).closest("div").attr("id");
console.log(myFormID);
var dataHref = $(this).attr('data-href');
console.log(dataHref);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" id="browseImagesDiv">
<h4>Image (Optional) <span></h4>
<input type="text" class="form-control" name="description" value="This is the image description." />
<input type="text" class="form-control" id="areaSection-15" name="image_url" value="" placeholder="Image URL Here"/>
<button type="button" class="btn btn-white btn-xs browsePageImages" data-href="15">Save Image Info</button></span>
</div>
I'm making an html question form. Based on the answers, it performs JavaScript algorithms. Then JavaScript takes the numbers it calculated and uses document.getElementById to put the answers in a hidden html form. PHP puts the form into variables, and updates the MYSQL row that was selected. I didn't show the actual calculations because it is over 300 lines of code. The values in the database are blank every time I click submit. Thanks to anyone who can help me out!!!
<html>
<form method="post" id="formformid">
//These are where the JavaScript values are entered.
<input class="hidden" name="processfnumaa" id="processfnum" type="number" value="0">
<input class="hidden" name="technologyfnumaa" id="technologyfnum" type="number" value="0">
<input class="hidden" name="staffingfnumaa" id="staffingfnum" type="number" value="0">
<input class="hidden" name="Question4aa" id="Question4aa" type="text">
<input class="hidden" name="Question5aa" id="Question5aa" type="text">
<input class="hidden" name="Question6aa" id="Question6aa" type="text">
<input class="hidden" name="Question7aa" id="Question7aa" type="text">
<input class="hidden" name="Question8aa" id="Question8aa" type="text">
<input class="hidden" name="Question9aa" id="Question9aa" type="text">
<input class="hidden" name="Question10aa" id="Question10aa" type="text">
<input class="hidden" name="Question11aa" id="Question11aa" type="text">
<input class="hidden" name="Question12aa" id="Question12aa" type="text">
<input class="hidden" name="Question13aa" id="Question13aa" type="text">
<input class="hidden" name="Question14aa" id="Question14aa" type="text">
<input class="hidden" name="Question15aa" id="Question15aa" type="text">
<input class="hidden" name="Question16aa" id="Question16aa" type="text">
<input class="hidden" name="Question17aa" id="Question17aa" type="text">
<input class="hidden" name="Question18aa" id="Question18aa" type="text">
<input class="hidden" name="Question19aa" id="Question19aa" type="text">
<input class="hidden" name="Question20aa" id="Question20aa" type="text">
<input class="hidden" name="Question21aa" id="Question21aa" type="text">
<input class="hidden" name="Question22aa" id="Question22aa" type="text">
<input class="hidden" name="Question23aa" id="Question23aa" type="text">
<input class="hidden" name="Question24aa" id="Question24aa" type="text">
<input class="hidden" name="Question25aa" id="Question25aa" type="text">
<input type="button" id="savebutton" onclick="submitthatform()" value="Save Changes" style="display: none;" />
</form>
//This function is called when the user is done editing the answers in a different form.
<script type="text/javascript">
function submitthatform() {}
document.getElementById("Question4aa").value = a;
document.getElementById("Question5aa").value = b;
document.getElementById("Question6aa").value = c;
document.getElementById("Question7aa").value = d;
document.getElementById("Question8aa").value = e;
document.getElementById("Question9aa").value = f;
document.getElementById("Question10aa").value = g;
document.getElementById("Question11aa").value = h;
document.getElementById("Question12aa").value = i;
document.getElementById("Question13aa").value = j;
document.getElementById("Question14aa").value = k;
document.getElementById("Question15aa").value = l;
document.getElementById("Question16aa").value = m;
document.getElementById("Question17aa").value = n;
document.getElementById("Question18aa").value = o;
document.getElementById("Question19aa").value = p;
document.getElementById("Question20aa").value = q;
document.getElementById("Question21aa").value = r;
document.getElementById("Question22aa").value = s;
document.getElementById("Question23aa").value = t;
document.getElementById("Question24aa").value = u;
document.getElementById("Question25aa").value = v;
var awsasdg = document.getElementById("Question4aa").value;
alert(awsasdg);
document.getElementById("processfnum").value = processfinalnumber;
document.getElementById("technologyfnum").value = technologyfinalnumber;
document.getElementById("staffingfnum").value = staffingfinalnumber;
document.getElementById("formformid").submit();
}
</script>
</html>
<?php
//Here, I'm trying to update a row in my database. This is just the part of the file that ends up blank in the database.
$Question4aa = mysql_real_escape_string($_POST['Question4aa']);
$Question5aa = mysql_real_escape_string($_POST['Question5aa']);
$Question6aa = mysql_real_escape_string($_POST['Question6aa']);
$Question7aa = mysql_real_escape_string($_POST['Question7aa']);
$Question8aa = mysql_real_escape_string($_POST['Question8aa']);
$Question9aa = mysql_real_escape_string($_POST['Question9aa']);
$Question10aa = mysql_real_escape_string($_POST['Question10aa']);
$Question11aa = mysql_real_escape_string($_POST['Question11aa']);
$Question12aa = mysql_real_escape_string($_POST['Question12aa']);
$Question13aa = mysql_real_escape_string($_POST['Question13aa']);
$Question14aa = mysql_real_escape_string($_POST['Question14aa']);
$Question15aa = mysql_real_escape_string($_POST['Question15aa']);
$Question16aa = mysql_real_escape_string($_POST['Question16aa']);
$Question17aa = mysql_real_escape_string($_POST['Question17aa']);
$Question18aa = mysql_real_escape_string($_POST['Question18aa']);
$Question19aa = mysql_real_escape_string($_POST['Question19aa']);
$Question20aa = mysql_real_escape_string($_POST['Question20aa']);
$Question21aa = mysql_real_escape_string($_POST['Question21aa']);
$Question22aa = mysql_real_escape_string($_POST['Question22aa']);
$Question23aa = mysql_real_escape_string($_POST['Question23aa']);
$Question24aa = mysql_real_escape_string($_POST['Question24aa']);
$Question25aa = mysql_real_escape_string($_POST['Question25aa']);
$processfnumaa = mysql_real_escape_string($_POST['processfnumaa']);
$technologyfnumaa = mysql_real_escape_string($_POST['technologyfnumaa']);
$staffingfnumaa = mysql_real_escape_string($_POST['staffingfnumaa']);
if($_SERVER['REQUEST_METHOD'] === 'POST'){
mysql_query("UPDATE HuronForm1 SET Question4aa='$question4aa',Question5aa='$question5aa',Question6aa='$question6aa',Question7aa='$question7aa',Question8aa='$question8aa',Question9aa='$question9aa',Question10aa='$question10aa',Question11aa='$question11aa',Question12aa='$question12aa',Question13aa='$question13aa',Question14aa='$question14aa',Question15aa='$question15aa',Question16aa='$question16aa',Question17aa='$question17aa',Question18aa='$question18aa',Question19aa='$question19aa',Question20aa='$question20aa',Question21aa='$question21aa',Question22aa='$question22aa',Question23aa='$question23aa',Question24aa='$question24aa', processfnum='$processfnumaa', technologyfnum='$technologyfnumaa',staffingfnum='$staffingfnumaa',Question25aa='$question25aa' WHERE Id='$idchosen'");
}
?>
Maybe you would use the same case for variables?
If you have var $Question4aa, it should be the same in mysql string, not $question4aa
I've tried many different methods, and even tried searching on SO. No answer was what I was looking for.
What I want is to have two input buttons that do some things in pure javascript.
Button one: Have it say "Add" when the page loads. When clicked, the value changes to "Cancel." Also, when it's clicked, have it display a form with three fields. When it's clicked again, have the form disappear. One named 'name', the second named 'location', the third named 'type'. I want the user to be able to submit these three things and have them be stored in the code.
Button two: Take the user input from the form and each time the user clicks, it displays all three information values, but have the button act as random generator. Let's say the code has 5 separate entries, I want them to be randomly selected and displayed when the button is clicked.
Like I said, I tried to make this work, but couldn't quite get over the top of where I wanted to go with it. If you want to see my original code, just ask, but I doubt it will be of any assistance.
Thanks in advance.
EDIT: Added the code.
function GetValue() {
var myarray = [];
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML = random;
}
var testObject = {
'name': BWW,
'location': "Sesame Street",
'type': Bar
};
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
function change() {
var elem = document.getElementById("btnAdd1");
if (elem.value == "Add Spot") {
elem.value = "Cancel";
} else elem.value = "Add Spot";
}
window.onload = function() {
var button = document.getElementById('btnAdd1');
button.onclick = function show() {
var div = document.getElementById('order');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
};
<section>
<input type="button" id="btnChoose" value="Random Spot" onclick="GetValue();" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" onclick="change();" />
<div class="form"></div>
<form id="order" style="display:none;">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
The randomizer works, and so does the appear/hide form. Only thing is storing the input and switching the input value.
Here's one way to do this. Each form submission is stored as an object in an array. The random button randomly selects an item from the array and displays it below.
HTML:
<section>
<input type="button" id="btnChoose" value="Random Spot" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" />
<div class="form">
<form id="order" style="display:none;">
<input id="orderName" type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input id="orderType" type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input id="orderLocation" type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
<div id="randomName"></div>
<div id="randomLocation"></div>
<div id="randomType"></div>
JS:
var formData = [];
var formSubmission = function(name, location, type) {
this.name = name;
this.location = location;
this.type = type;
}
var spotName = document.getElementById("orderName"),
spotLocation = document.getElementById("orderLocation"),
spotType = document.getElementById("orderType");
var addClick = function() {
if (this.value === 'Add Spot') {
this.value = "Cancel";
document.getElementById('order').style.display = 'block';
}
else {
this.value = 'Add Spot';
document.getElementById('order').style.display = 'none';
}
}
document.getElementById("btnAdd1").onclick = addClick;
document.getElementById('order').onsubmit = function(e) {
e.preventDefault();
var submission = new formSubmission(spotName.value, spotLocation.value, spotType.value);
formData.push(submission);
submission = '';
document.getElementById('btnAdd1').value = 'Add Spot';
document.getElementById('order').style.display = 'none';
this.reset();
}
var randomValue;
document.getElementById('btnChoose').onclick = function() {
randomValue = formData[Math.floor(Math.random()*formData.length)];
document.getElementById('randomName').innerHTML = randomValue.name;
document.getElementById('randomLocation').innerHTML = randomValue.location;
document.getElementById('randomType').innerHTML = randomValue.type;
}
I was working on something since you first posted, and here is my take on it:
HTML:
<section>
<p id="message">
<div id="name"></div>
<div id="location"></div>
<div id="type"></div>
</p>
<input type="button" id="btnAdd" value="Add" onclick="doAdd(this);" />
<input type="button" id="btnShow" value="Show" onclick="doShow(this);" />
<div class="form">
<script id="myRowTemplate" type="text/template">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" onchange="onChanged(this, {{i}})" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
</script>
<form id="order" style="display:none;">
<div id="formItems">
</div>
<input type="button" value="Add Spot" onclick="addSpot()" />
</form>
</div>
</section>
JS:
function GetValue() {
if (enteredItems.length) {
var entry = enteredItems[Math.floor(Math.random() * enteredItems.length)];
document.getElementById("name").innerHTML = entry.name;
document.getElementById("location").innerHTML = entry.location;
document.getElementById("type").innerHTML = entry.type;
}
}
function doAdd(elem) {
switch (elem.value) {
case "Add":
document.getElementById('order').style.display = "";
elem.value = "Cancel";
break;
case "Cancel":
document.getElementById('order').style.display = "none";
elem.value = "Add";
break;
}
}
function doShow(elem) {
GetValue();
}
function addSpot(index) { // (note: here, index is only for loading for the first time)
if (index == undefined) index = enteredItems.length;
var newRowDiv = document.createElement("div");
newRowDiv.innerHTML = document.getElementById("myRowTemplate").innerHTML.replace(/{{i}}/g, index); // (this updates the template with the entry in the array it belongs)
if (enteredItems[index] == undefined)
enteredItems[index] = { name: "", location: "", type: "" }; // (create new entry)
else {debugger;
newRowDiv.children[0].value = enteredItems[index].name;
newRowDiv.children[1].value = enteredItems[index].location;
newRowDiv.children[2].value = enteredItems[index].type;
}
document.getElementById("formItems").appendChild(newRowDiv);
}
function onChanged(elem, index) {
enteredItems[index][elem.name] = elem.value;
localStorage.setItem('enteredItems', JSON.stringify(enteredItems)); // (save each time
}
// update the UI with any saved items
var enteredItems = [];
window.addEventListener("load", function() {
var retrievedObject = localStorage.getItem('enteredItems');
if (retrievedObject)
enteredItems = retrievedObject = JSON.parse(retrievedObject);
for (var i = 0; i < enteredItems.length; ++i)
addSpot(i);
});
https://jsfiddle.net/k1vp8dqn/
It took me a bit longer because I noticed you were trying to save the items, so I whipped up something that you can play with to suit your needs.