I'm trying to figure out how to add my object from a form. Any ideas how I can add a new name and photo_url to the end of my object?
Thanks,
data = [
{name: "Mark-Paul Gosselaar", photo_url: ""},
{name: "Delta Burke", photo_url: "img/avatars/delta.png"},
{name: "Alf", photo_url: "img/avatars/alf.png"},
{name: "Jaleel White", photo_url: "img/avatars/jaleel.png"},
{name: "Ralph Macchio", photo_url: "img/avatars/ralph.png"},
{name: "Candace Cameron", photo_url: "img/avatars/candace.png"},
{name: "Patrick Duffy", photo_url: "img/avatars/pduff.png"},
{name: "Arnold Schwartzengger", photo_url: "img/avatars/arnold.png"}
];
//MY CODE
$(document).ready(function() {
var employee = data;
var directory = $("#directory");
//SORT THROUGH THE JSON DATA AND REVERSE IT
function reverseArr(input) {
for (var i = input.length - 1; i >= 0; i--) {
var photoPlacement = employee[i].photo_url;
//CHECKS TO SEE IF A PHOTO_URL OBJECT HAS SOMETHING IN IT, IF IT DOESN'T THEN INJECTS THE DEFAULT IMAGE
if (photoPlacement.length <= 0) {
photoPlacement = 'img/default.png'
} else {
photoPlacement = employee[i].photo_url;
}
var employeePost = "<div class='employee'><div id='photo'><img src=" + photoPlacement + "></div><div id='closeButton' class='close'><img src='img/close.png'></div><div class='empName'>" + employee[i].name + "</div></div>";
console.log(employee[i].name);
console.log(employee[i].photo_url);
directory.append(employeePost);
}
}
var b = reverseArr(employee);
//SHOW THE "X" (CLOSE) BUTTON
$('.employee').hover(
function() {
$(this).children("#closeButton").removeClass("close")
$(this).children("#closeButton").addClass("showClose")
//IF THE "X" (CLOSE) BUTTON IS CLICKED, DELETE PARENT DIV
$(this).children("#closeButton").click(function(event) {
event.preventDefault();
$(this).parent(".employee").remove();
})
},
function() {
$(this).children("#closeButton").removeClass("showClose")
$(this).children("#closeButton").addClass("close")
}
);
//IF FORM BUTTON IS CLICKED, SUBMIT NEW DATA TO JSON OBJECT
$(":button").click(function(event) {
event.preventDefault();
});
});
This is how my HTML is formatted and need to have whatever name you type in the first input box to be added to data.
<!DOCTYPE html>
<html>
<head>
<link href="css/application.css" rel="stylesheet">
</head>
<body>
<div id="main-content">
<!-- The page width is 817px -->
<!-- Example of using the form CSS to help you out. -->
<form>
<div>
<label>Full Name</label>
<input name="name" type="text" required />
</div>
<div>
<label>Photo URL</label>
<input name="photo_url" />
</div>
<button type="submit">Create</button>
</form>
<hr />
<!-- Employee list goes here. There is initial data for you in application.js -->
<div id="directory">
</div>
</div>
<script src="js/vendor/jquery.min.js" type="text/javascript"></script>
<script src="js/vendor/underscore.js" type="text/javascript"></script>
<script src="js/application.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
</body>
</html>
Bind the form and listen to submit event. Convert the form to json object and push to data.
$(function() {
//listen to form submit
$("form").on("submit", function(event) {
event.preventDefault();
//serialize form to object
var formData = $(this).serializeObject();
data.push(formData);
console.log(data);
$("#data").html(JSON.stringify(data));
});
});
Plnkr - http://plnkr.co/edit/dhLqCkXmpGHit78ZGAxZ?p=preview
Convert form data to JavaScript object with jQuery
Related
I am playing with jQuery and Javascript. Working on a TODOs app using li items and with this API: https://jsonplaceholder.typicode.com/todos. I receive 200 items from this API.
I am trying to post a new item created with a click from the button (btn-add) and everything works as expected, with the exception that the post request is leaving in blank one property which is "title". Here is my HTML and JS code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/CSS/styles.css" rel="stylesheet">
<title>TO DO List</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="/JS/index.js"></script>
</head>
<body>
<div id="inputDIV">
<input id="input" type="text" placeholder="Enter new item">
</div>
<div id="buttons">
<button id="btn-add">Add List Item</button>
<button id="btn-update">Update First Item</button>
<button id="btn-delete">Delete First Item</button>
</div>
<div id="ulDIV">
<ul id="list">
<!-- Here we will insert the list items via JS-->
</ul>
</div>
</body>
</html>
$(document).ready(function(){
let inputNew = $('#input');
let list = $('#list');
let currentInputValue = "";
$('#btn-add').click(createTODOItemAtBackend);
inputNew.on({
"input": function(e){
console.log(e.target.value);
currentInputValue = e.target.value;
},
"keyup": function(e){
if(e.keyCode === 13){
createTODOItemAtBackend();
}
}
})
getTODOListFromBackend();
function clearInputData(){
inputNew.val("");
currentInputValue = "";
}
function createTODODynamically(id, title){
let newListElement = document.createElement("li");
let textNode = document.createTextNode(title);
newListElement.appendChild(textNode);
newListElement.id = id;
return newListElement;
}
function getTODOListFromBackend(){
$.get("https://jsonplaceholder.typicode.com/todos", function(data, status){
let response = data;
for(let i=0; i < response.length; i++){
list.append(createTODODynamically(response[i].id, response[i].title));
}
});
}
let obj = {
"userId": 1,
"title": currentInputValue,
"completed": false
};
function createTODOItemAtBackend(){
$.post("https://jsonplaceholder.typicode.com/todos", obj, function(data, status){
let response = data;
list.append(createTODODynamically(response.id, currentInputValue));
console.log("Item Added to the list!");
clearInputData();
});
}
})
And this is what I see when I read the post information in the web browser:
{userId: "1", title: "", completed: "false", id: 201}
completed: "false"
id: 201
title: ""
userId: "1"
Can somebody help me, why is the property "title" being posted as empty? Thanks in advance
The answer is in what #epascarello hinted on the OP's comment. You set currentInputValue when the input value is changed but there's no code which updates this value to obj.
"input": function(e){
console.log(e.target.value);
currentInputValue = e.target.value;
//Add this line
obj.title = e.target.value;
},
Additional note: You really don't need currentInputValue if you refactor your code, using obj should do the job.
This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Closed 3 years ago.
I have a js and htlm code in jfiddle.
I have created the button onclick event on the object method and on the page load it firing the event.
Is this some problem with my code.
var user = {
data: [
{name: 'T. Woods', age: 37},
{name: 'P. Mickelson', age: 43}
],
clickHandler: function (event) {
console.log(this);
var randomNum = ((Math.random() * 2 | 0) + 1) - 1; // Random number between 0 and 1
$('input').val(this.data[randomNum].name + ' ' + this.data[randomNum].age);
}
};
console.log(user);
$('button').click(user.clickHandler(this));
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>Homepage Headline</h1>
<div id="div1">
<p>
<button>Get Random Person</button><br>
<input type="text">
</p>
</div>
<script type="text/javascript" src="oops.js"></script>
</body>
</html>
Your click event listener needs to be a function otherwise it will trigger .click() on the button instead of creating a listener
See the documentation for .click()
$("button").click(function () {
user.clickHandler(this)
});
Test it with your code here -
var user = {
data :[
{name: "T. Woods", age:37},
{name: "P. Mickelson", age:43}
],
clickHandler:function (event) {
console.log(this);
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1
//console.log(this.data[randomNum].name + " " + this.data[randomNum].age);
// This line is adding a random person from the data array to the text field
$ ("input").val (this.data[randomNum].name + " " + this.data[randomNum].age);
}
};
console.log(user);
$("button").click(function() {
user.clickHandler(this)
});
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>Homepage Headline</h1>
<div id="div1">
<p>
<button>Get Random Person</button><br>
<input type="text">
</p>
</div>
<script type="text/javascript" src="oops.js"></script>
</body>
</html>
The issue is because you invoke the user.clickhandler() function when the page loads and set its response as the click handler for the element.
You instead want to provide the reference to the function to the event handler. You will also need to bind() the scope of user to the reference, as that's what clickhandler() expects to run under. Try this:
$("button").click(user.clickHandler.bind(user));
Working example:
var user = {
data: [{
name: "T. Woods",
age: 37
}, {
name: "P. Mickelson",
age: 43
}],
clickHandler: function(event) {
console.log(this);
var randomNum = ((Math.random() * 2 | 0) + 1) - 1;
$("input").val(this.data[randomNum].name + " " + this.data[randomNum].age);
}
};
$("button").click(user.clickHandler.bind(user));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<h1>Homepage Headline</h1>
<div id="div1">
<p>
<button>Get Random Person</button><br>
<input type="text">
</p>
</div>
You need to attach the handler, not call it, and then bind the this object accordingly:
user.clickHandler.bind(user)
This is not a problem, you call
$("button").click(user.clickHandler(this));
at the loading, then it call the click event
Replace it by
$("button").bind("click", user.clickHandler(this));
I am trying to parse JSON data from the url (only feeds data from the JSON) and stored the values in localstorage now I am trying to retrieve the values that are stored in the localstorage from one file to another file the stored values is in the from of array objects.while retrieving I am getting only the final object in other file. Can anyone help me how to retrieve all the objects? I am attaching the code below new.html (here I am trying to store the data in localstorage) and new1.html (here I am retrieving the data). Thank you
new.html:
<html>
<head>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width ,height=device-height"/>
</head>
<body>
<div id="header">
<h1> Login </h1>
</div>
<div id="section">
<!--script type="text/javascript"
charset="utf-8" src="cordova-1.7.0.js"></script-->
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("#submit").click(insertId);
});
function insertId() {
// Getting the value of your text input
var did = document.getElementById("deviceId").value;
if (did == null || did == "") {
alert("Kindly enter a valid Device ID");
return false;
} else {
console.log("id: ", did);
}
window.alert("DID entered is : " + did);
window.open("new1.html");
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=10",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
localStorage.setItem('Created_at', feed.created_at);
var create = localStorage.getItem('Created_at');
console.log(create);
localStorage.setItem('Entry_id', feed.entry_id);
var entry = localStorage.getItem('Entry_id');
console.log(entry);
localStorage.setItem('Field1', feed.field1);
var fd1 = localStorage.getItem('Field1');
console.log(fd1);
localStorage.setItem('Field2', feed.field2);
var fd2 = localStorage.getItem('Field2');
console.log(fd2);
});
}
});
return false;
}
</script>
<form id="insertId">
<br><input type="text" placeholder="DeviceId" id="deviceId" /><br>
<br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</div>
</body>
new1.html:
<html>
<body onload="init();">
<div id="header">
<h1> USER DETAILS </h1>
</div>
<div id="section">
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var create = localStorage.getItem('Created_at');
console.log(create);
document.writeln("<br>Created_at = "+create);
var entry = localStorage.getItem('Entry_id');
document.writeln("<br>Entry_id = "+entry);
var fd1 = localStorage.getItem('Field1');
document.writeln("<br>Field1 = "+fd1);
var fd2 = localStorage.getItem('Field2');
document.writeln("<br>Field3 = "+fd2);
}
</script>
<body onload="init();">
</body>
</div>
</body>
so I am working on a stock market simulator using HTML and JS. I have a api here that gets current stock prices. Here is my HTML http://pastebin.com/ymcGKtin Sorry about pastebin not very good at formatting for SO. But in the function add stock I am trying to push the submitted form stockto the array stocks. However I have run into a problem trying to figure out how to get the submitted form stock and push it to the array. If I could get some pointers on how to do this it would be appricated. To be specific I would like help on getting the attribute stock pushed to the array Stocks. Ideas?
var Market = {};
var Stocks = [];
Market.getQuote = function(symbol, fCallback){
this.symbol = symbol;
this.fCallback = fCallback;
this.DATA_SRC = "http://dev.markitondemand.com/Api/v2/Quote/jsonp";
this.makeRequest();
}
Market.getQuote.handleSuccess = function(jsonResult){
this.fCallback(jsonResult);
}
Market.getQuote.handleError = function(jsonResult){
console.error(jsonResult);
}
Market.makeRequest = function () {
//Abort any open requests
if (this.xhr) { this.xhr.abort(); }
//Start a new request
this.xhr = $.ajax({
data: { symbol: this.symbol },
url: this.DATA_SRC,
dataType: "jsonp",
success: this.handleSuccess,
error: this.handleError,
context: this
});
};
function addStock(){
alert("derp");
// Stocks.push(ele.getAttribute)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Stock Market Game PRE ALPHA BETA</title>
</head>
<body>
<form onsubmit = "addStock()">
<input type="text" name="stock" value =""><br><br>
<input type="submit" value="Get Price">
</form>
</body>
</html>
With JQuery you could use find on the form-object (this in the onsubmit-handler):
...
function addStock(form){
var value = $(form).find('input[name="stock"]').val();
alert(value);
Stocks.push(value);
//prevents a submit of the form
return false;
}
</SCRIPT>
<form onsubmit = "return addStock(this);">
<input type="text" name="stock" value =""><br><br>
<input type="submit" value="Get Price">
</form>
...
Changed the addStock() function to use the form element collection method.
function addStock(){
var xForm = document.forms[0];
var xField = xForm.elements[0];
alert("Stock: "+xField.value);
Stocks.push(xField.value);
console.log(Stocks);
}
var Market = {};
var Stocks = [];
Market.getQuote = function(symbol, fCallback) {
this.symbol = symbol;
this.fCallback = fCallback;
this.DATA_SRC = "http://dev.markitondemand.com/Api/v2/Quote/jsonp";
this.makeRequest();
}
Market.getQuote.handleSuccess = function(jsonResult) {
this.fCallback(jsonResult);
}
Market.getQuote.handleError = function(jsonResult) {
console.error(jsonResult);
}
Market.makeRequest = function() {
//Abort any open requests
if (this.xhr) {
this.xhr.abort();
}
//Start a new request
this.xhr = $.ajax({
data: {
symbol: this.symbol
},
url: this.DATA_SRC,
dataType: "jsonp",
success: this.handleSuccess,
error: this.handleError,
context: this
});
};
function addStock() {
var xForm = document.forms[0];
var xField = xForm.elements[0];
alert("Stock: " + xField.value);
Stocks.push(xField.value);
console.log(Stocks);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Stock Market Game PRE ALPHA BETA</title>
</head>
<body>
<form onsubmit="addStock()">
<input type="text" name="stock" value="">
<br>
<br>
<input type="submit" value="Get Price">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
</body>
</html>
Good day.
I'm trying to add Google Places Autocomplete on dynamically created inputs using code below:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var container = document.getElementById('AutoComplInputs');
container.innerHTML += "<br>" + _id;
var _elem_for_upd = document.createElement("input");
_elem_for_upd.type = "text";
_elem_for_upd.id = _id;
container.appendChild(_elem_for_upd);
assignAutoCompl(_id);
}
</script>
</head>
<body>
<div id="AutoComplInputs"></div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
But when I press on button, autocomplete works only on last input, and all prevoius become broken. I think that it can be connected to dynamic creation of inputs, as the code below works fine:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
document.getElementById(_id).hidden = false;
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
assignAutoCompl("AutoCompl0");
assignAutoCompl("AutoCompl1");
}
</script>
</head>
<body>
<div id="AutoComplInputs">
<input id="AutoCompl0" type="text" hidden>
<input id="AutoCompl1" type="text" hidden>
</div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
I don't understand what I'm doing wrong ...
Don't use innerHTML to add content to container, you will lose all handlers bound to existing elements.
Use appendChild instead:
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode(_id));