How to add data to an array from text box/s? - javascript

I'm fairly stuck on this, I'm playing catchup on course work.
How do I go about adding values to an array using string from text boxes on the page?
var book = [
{
"name":"Book 1",
"publisher":"Publisher 1",
"isbn":"ISBN 1"
},
{
"name":"Book 2",
"publisher":"Publisher 2",
"isbn":"ISBN 2"
},
{
"name":"Book 3",
"publisher":"Publisher 3",
"isbn":"ISBN 3"
},
];
book.push({"name":"Moby Dick","publisher":"Ryan Spain","isbn":"00147097"});
I know I can push it into the array but I want to add values to name, publisher and isbn from values attained from text boxes in HTML.

EDIT: Adding information
Imagine you have three inputs with the following ids "name", "publisher", "isbn".
var name = document.getElementById('name');
var pub = document.getElementById('publisher');
var isbn = document.getElementById('isbn');
You could add a button when the user is ready to add a book to your list:
<button id="add">Add</button>
var button = document.getElementById('add');
Then you could add an onclick:
button.onclick = function(){
book.push({'name': name.value, 'publisher': pub.value, 'isbn':isbn.value});
}
Getting information:
Is how you would do it.
book[0].name = "Book test";
You could loop through all your books and update them one by one:
for(var i = 0; i < book.length; i++){
book[i].name = "Book " + i;
//etc
}

Related

JQUERY/js how make dropdown menu from api response

Based from my code below , how can i make the newField a drop down menu textfield like this cause now it is still a textfield . Then the value is the list of "title" from this rest api https://jsonplaceholder.typicode.com/todos. Thanks
var addRuleLink = $("<a>", {"href": "#", "class": "add-rule", "text": "Add Condition"});
var _this = this;
addRuleLink.click(function(e) {
e.preventDefault();
var f = _this.fields[0];
var newField = {name: f.value, operator: f.operators[0], value: null};
div.append(_this.buildRule(newField));
});
div.append(addRuleLink);

Call field from another table in select firebase

I have a table categories and a documents. I want to create a new document and associate this document with a category already created.
The category table has the title field.
In the document creation form I want to put the categories already created in a select.
I tried doing this in the code below, but I ended up getting the select a key from the category -L0_xe_FIK9QdfTGhBDG for example, but I wanted the category title.
var documentosRef = firebase.database().ref('documentos');
var categoriasRef = firebase.database().ref('categorias');
var keyDocumento = ""
function initFirebase(){
categoriasRef.on('value', function(data) {
$('#categoria').html('');
for(categoria in data.val()){
option = "<option>"+categoria+"</option>"
$('#categoria').html($('#categoria').html()+option);
}
})
}
Structure:
{ "categorias": {
"L0_xe_FIK9QdfTGhBDG": {
"titulo": "Categorias 1"
},
"-L0a0FPFkXkKb3VNFN0c":{
"titulo": "Categorias 2"
}
}
Let check it out: JavaScript for/in Statement
var categorias = data.val();
for(var key in categorias){
option = "<option>"+categorias[key].titulo +"</option>"
$('#categoria').html($('#categoria').html()+option);
}

Using php array in javascript to populate a 'select' ajax

I have a multidimensional array of stores and states, which makes a json as follows:
<?php
$list[$store][$state] = $city;
echo json_encode ($list);
{"store 1": {"state x": "city 1", "state y": "city 2"}, "store 2": {"state z": "city 3"}}
?>
I need to create a select that changes the second select according to what was chosen, using the data of the array in question.
Something like this http://www.daviferreira.com/blog/exemplos/cidades/index.php
How can I handle this data in php for javascript?
And how can I separate them to use them in each select?
I've already tried:
var list = JSON.parse ("<? php echo json_encode($list)?>");
But it did not work :(
EDIT The structure of the selects should look like this.
{"store 1": {"state x": "city 1", "state y": "city 2"}, "store 2": {"state z": "city 3"}}
First select
Store 1
Store 2
if store 1 selected
Second select
State x
State y
if store 2 selected
Second select
State z
Something like that
You can simply do this using jQuery:
$(document).ready(function(){
var list = <?= json_encode($list); ?>;
var storeSelect = $("<select></select>");
storeSelect.attr('id', 'storeSelect');
for(var item in list)
{
storeSelect.append('<option value="' + item + '">' + item + '</option>');
}
$('#theForm').append(storeSelect);
var storeStates = $("<select></select>");
storeStates.attr('id', 'storeState');
$('#theForm').append(storeStates);
$('#storeSelect').change(function ()
{
var storeName = $(this).val();
for(var item in list[storeName])
{
storeStates.html('<option value="' + item + '">' + item + '</option>');
}
});
$('#storeSelect').change();
});
It simply uses loops to create the select menu. And uses the onChange event to manipulate the values.
Here's how to do it using jQuery. If you're using plain JS, converting it is an exercise for the reader.
var list = <?php echo json_encode($list); ?>;
$.each(list, function(store) {
$("#store_menu").append($("<option>", {
value: store,
text: store
}));
});
$("#store_menu").change(function() {
var store = $(this).val();
$("#state_menu").empty();
$.each(list[store], function(state) {
$("#state_menu").append($("<option>", {
value: state,
text: state
}));
});
});

Looping javascript object to print data

I have a javascript object that I would like to traverse and print data based off 1 common category.
Javascript object:
var $states = {
"AL" : {
"longname": "Alabama",
"lawOne": "Alabama Law 1",
"lawTwo": "Alabama Law 2",
"lawThree": "Alabama Law 3",
"region" : "Southeast"
},
"AK" : {
"longname": "Alaska",
"lawOne": "Alaska Law 1",
"lawTwo": "Alaska Law 2",
"lawThree": "Alaska Law 3",
"region" : "Northwest"
},
"AZ" : {
"longname": "Arizona",
"lawOne": "Arizona Law 1",
"lawTwo": "Arizona Law 2",
"lawThree": "Arizona Law 3",
"region" : "Southwest"
},
etc...
}
I am able too loop the array and get as granular as getting the console to log all of the states that are in the same region:
for (var key in $states) {
if ($states.hasOwnProperty(key)) {
var $getStateRegion = $states[key].region
if ($getStateRegion === "Northeast") {
console.log ($states[key].longname);
}
}
}
Once I try to loop through those and print a table with that data is where I am running into an issue. I want to be able to have a withthe 's longname, lawOne, lawTwo, and lawThree values input in there. What gives? Once I try running a for loops through this is where I'm hitting a roadblock. Thanks in advance!
Try the working code below.
var $states = {
"AL" : {
"longname": "Alabama",
"lawOne": "Alabama Law 1",
"lawTwo": "Alabama Law 2",
"lawThree": "Alabama Law 3",
"region" : "Southeast"
},
"AK" : {
"longname": "Alaska",
"lawOne": "Alaska Law 1",
"lawTwo": "Alaska Law 2",
"lawThree": "Alaska Law 3",
"region" : "Northwest"
},
"AZ" : {
"longname": "Arizona",
"lawOne": "Arizona Law 1",
"lawTwo": "Arizona Law 2",
"lawThree": "Arizona Law 3",
"region" : "Southwest"
}
};
var result = {};
Object.keys($states).forEach(function(key) {
if ($states[key]["region"] === "Southwest") {
result[key] = $states[key];
}
});
console.log(result);
You are on the right track. Before I continue, I would like to point out that you are using a for..in loop, but newer versions of Javascript support the for..of loop also, so this is something you may want to consider. The difference is that the for..in loop gives you the keys of the object, and the for..of loop gives you the values, so it shortens the code by skipping the step where you write something to the effect of:
for( var index in array ){
var currentObject = array[ index ];
}
The secret to your solution is in how you handle the DOM, and there are many ways to do this. I will show you one, but it is not necessarily the fastest or the best. I recommend playing around with different DOM manipulations to find the one that works best for you.
First, we know how to get a record, so the javascript aspect of looping, you have that handled...
Next, we need to create the table.... I will assume that you want four columns based on your description, but you could easily adjust this to put the state name and one law on each line, which would probably be a better design allowing a variable number of laws.
The html would look something like this:
<table>
<tr><th>State</th><th>Law 1</th><th>Law 2</th><th>Law 3</th></tr>
<!-- Here is where we would create new html for each state -->
</table>
Your loop then would need to add to this html by creating several lines that appear as:
<tr><td>[State]</td><td>[Law1]</td><td>[Law2]</td><td>[Law3]</td><tr>
We will use string manipulation of the DOM, because it is a good place to start, because it is most similar to what you would write by hand.
We will break the table into three parts: the header, the body and the footer.
var header = "<table><tr><th>State</th><th>Law 1</th><th>Law 2</th><th>Law 3</th></tr>";
var body = ""; //this is where we add the data
var footer = "</table>";
Now, on the loop, we will create each line as needed and add it to the body:
for( var index in stateObj ){
...error checking occurs here...
var state = stateObj[ index ];
var stateColumn = "<td>" + state.longname + "</td>";
var law1Col = "<td>" + state.lawOne + "</td>";
var law2Col = "<td>" + state.lawTwo + "</td>";
var law3Col = "<td>" + state.lawThree + "</td>";
var row = "<tr>" + stateColumn + law1Col + law2Col + law3Col + "</tr>";
//now that we have a row, we add it to the body
body += row; //same as body = body + row;
}
After we have the body, we can make our table by combining the header, body and footer:
var tableHTML = header + body + footer;
And then we find a place to inject it into our document:
var outputDiv = document.getElementById( "stateTableData" );
outputDiv.innerHTML = tableHTML;
Here is a live example:
var states = {
PA: {
longname:"Pennsylvania",
lawOne:"It is illegal to sing in the shower in apartment buildings within the city limits of Philadelphia",
lawTwo:"All motorists are required to stop the vehicle for passing horsemen. The vehicle shall be covered with camoflage so as not to scare the horses.",
lawThree:"Any house having more than four women occupants shall be considered a brothel and shall be in violation of the law."
},
NJ: {
longname:"New Jersey",
lawOne:"There is no such thing as the Mafia",
lawTwo:"Any reference to the denizens of New Jersey shall be derogatory and degrading, think Jersey Shore",
lawThree:"There is no escape from New Jersey and we are not a suburb of NYC"
},
VA: {
longname:"Virginia",
lawOne: "Civil War re-enactments must have the North as the victor.",
lawTwo: "All roads shall end in Richmond, VA",
lawThree: "I have run out of silly ideas for this example."
}
};
function buildTableForState( stateNames ){
var stateList = stateNames.split(",");
//remove spaces
for( var i in stateList ){ stateList[i] = stateList[i].trim(); }
//initialize table parts
var header = "<table><tr><th>State</th><th>Law 1</th><th>Law 2</th><th>Law 3</th></tr>";
var footer = "</table>";
var body = "";
//build body
for( var index in states ){
if( stateList.indexOf( index ) !== -1 ){
var currentState = states[index];
body += buildRowForState( currentState );
}
}
//compose and inject table
var tableHTML = header + body + footer;
var documentOut = document.getElementById( "outputDiv" );
documentOut.innerHTML = tableHTML;
}
function submitTable(value){
buildTableForState( value );
}
function buildRowForState( currentState ){
var state = makeTableCol( currentState.longname );
var law1 = makeTableCol( currentState.lawOne );
var law2 = makeTableCol( currentState.lawTwo );
var law3 = makeTableCol( currentState.lawThree );
var row = makeTableRow( [state, law1, law2, law3] );
return row;
}
function makeTableCol( stringText ){
return "<td>" + stringText + "</td>";
}
function makeTableRow( arrayColumns ){
return "<tr>" + arrayColumns.join("") + "</tr>";
}
<h1>Table Loader</h1>
<form>
<p>Use the values "PA", "NJ", and "VA" to generate a table. You can use more than one value by separating them with a comma.</p>
<input type="text" id="stateNames" name="stateNames" /><br/>
<button onclick="submitTable(stateNames.value);">Build Table</button>
<p>Try:
</p>
<ul>
<li>PA</li>
<li>NJ,VA</li>
<li>VA,PA,NJ</li>
</ul>
</form>
<h1>Table Output appears here</h1>
<div id="outputDiv"></div>
NOTE: Regarding the live code, the HTML is bigger than the display box. In my browser I have to scroll down on the snippit HTML to view the generated table. Either that or expand the snippit window to a full tab to view it in a larger screen.
The above code is simplified, and most coders would tell you not to use HTMLElement.innerHTML, because it is slow, but it is a good place to start. Once you have this down, start practicing with document.create( tagName ), and then use more direct DOM manipulations.

pushing into ko.observableArray not updating the UI

I have a 2 view models
function group(){
name = "";
description = "";
members = ko.observableArray([]);
}
and
function groupTypes(){
gorupA = ko.observableArray([]);
groupB = ko.observableArray([]);
}
I have a regular JS array groupArray with group type objects as elements.
I've separate templates for groupA-template and groupB-template
I did:
var groupTypeInstance = new groupTypes;
groupTypeInstance.groupA.push(groupArray.slice(0,4));
ko.applyBindingsToNode(
document.getElementById('group-a'),
{
template: {
name: "groupA-template",
foreach: groupTypeInstance.groupA
}
}
);
This displayed the UI correctly.
But afterwards when I do groupTypeInstance.groupA.push(groupArray[5]), nothing happens. UI doesnt change. Console doesn't show any error. Array has the extra element when I print it in console. Why is the UI not getting updated?
Please ask for more details if needed.
Your code as it is do not work. You misspelled groupA and forgot the this. on the variables. Also, you cannot add individual array itens to another array by calling push() (it will work but not as you probably intended). Here is the code to do what you want, based on what you posted:
$(function(){
function group(){
this.name = "";
this.description = "";
this.members = ko.observableArray([]);
}
function groupTypes(){
this.groupA = ko.observableArray([]);
this.groupB = ko.observableArray([]);
}
var groupArray = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"] ;
var groupTypeInstance = new groupTypes();
groupTypeInstance.groupA.push.apply(groupTypeInstance.groupA, groupArray.slice(0,4));
ko.applyBindingsToNode(
document.getElementById('group-a'),
{
template: {
name: "groupA-template",
foreach: groupTypeInstance.groupA
}
}
);
setInterval(function(){
groupTypeInstance.groupA.push(groupArray[5]);
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/html" id="groupA-template">
<h3 data-bind="text: $data"></h3>
</script>
<div id="group-a">
</div>

Categories