Filtering JSON reply in jQuery - javascript

I'm attempting to filter out the reply I get from a JSON query to the Glosbe.com API.
Currently I've been able to break the JSON down to only receive the meanings but I'm unsure how to remove all of the commas and other aspects of the JSON response. I basically just want to display each meaning on a line of it's own.
jquery code:
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
$('#definition').empty();
}
});
var getDefinition = function(){
var word = $('#term').val();
if(word === ''){
$('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");
}
else {
$('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=" +word+ "&pretty=true&callback=?", function(json) {
if (json !== "No definition has been found."){
var reply = JSON.stringify(json,null,"\t");
var n = reply.indexOf("meanings");
var sub = reply.substring(n+8,reply.length);
var subn = sub.indexOf("]");
sub = sub.substring(0,subn);
$('#definition').html('<h2 class="loading">We found you a definition!</h2> <h3>'+sub+'</h3>');
}
else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=rus&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#definition').html('<h2 class="loading">Nothing found.</h2><img id="thedefinition" src=' + json.definition[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getDefinition();
}
});
});
HTML page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<header>
<h1>Dictionary Application</h1>
</header>
<section id="fetch">
<input type="text" placeholder="Enter a word..." id="term" />
<button id="search">Define!</button>
</section>
<section id="definition">
</section>
<footer>
<p>Created by Matthew & Spencer</p>
</footer>
</div>
Thanks.

JSON is JavaScript Object Notation. You can use it to send JavaScript objects around. You should take advantage of this, not flatten it and mess with string parsing.
Your json variable contains something like this:
{
...
"tuc": [
{
"authors": [
1
],
"meaningId": null,
"meanings": [
{
"language": "eng",
"text": "The process of applying a test as a means of analysis or diagnosis."
},
{
"language": "eng",
"text": "difficult, tough"
},
{
"language": "eng",
"text": "Present participle of test."
},
{
"language": "eng",
"text": "The act of conducting a test; trialing, proving"
}
]
},
...
]
}
You can access the section with the meanings with json["tuc"]; each of those contains an array of meanings (ie json["tuc"][0]["meanings"]). You can loop through each of those and extract the text property to build up your output.
For example, inside .getJSON, once you've verified that you do have data:
var meanings = "";
json["tuc"].forEach(function(tuc) {
tuc["meanings"].forEach(function(m) {
meanings += "<p>"+m["text"]+"</p>\n";
});
});
$("#definition").html(meanings);

Related

POST request not posting the value of one property Javascript/jQuery

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.

How to restrict dynamic input to one digit only and locked for key press except spin buttons using pure Javascript?

I have created a dynamic input and its should accept numbers between 0 to 5 only using spinner (arrow buttons) and should restrict manual input from key board. I have tried [this][1] but its not working in my code. I have two java script files data.js contains object to be read and other file contains a function which read objects and display them dynamically Please help me knowing where I am doing mistake? Thank you
//data.js
var catalogArray = [
{
code: 100,
name: "T Shirt c100",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 150,
image: "./images/img100.jpg"
},
{
code:101 ,
name: "T Shirt c101",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 250,
image: "./images/img101.jpg"
}
];
//function.js
function chargerArticles() {
var articles = document.getElementById("content");
var catalog=catalogArray;
for (var i =0; i < catalog.length; i++) {
//Command Input Area
var zoneCmd=document.createElement("div");
zoneCmd.setAttribute("class", "border");
var inputCmd=document.createElement("Input");
inputCmd.setAttribute("class", "qty");
//inputcmd all properties
inputCmd.type="number";
// inputcmd.maxLenght="1";
// inputcmd.onKeydown=false;
inputCmd.value=0;
inputCmd.min=0;
inputCmd.max=5;
zoneCmd.appendChild(inputCmd); //child 1
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<script src="js/data.js"></script>
<script src="js/codeboutique.js"></script>
</head>
<body onload="chargerArticles()">
<!-- <div class="border"><input class="qty" id="0-qte" type="number" min="0" max="5"
"><button class="cartBtn hvr-underline-btn" id="0-cmd"
"> ADD TO CART</button></div> -->
<div class="mainDivClass">
<section id="content">
</section>
</div>
</body>
</html>
It is unclear what type of thing a "spin button" is, so I can't address that part of your question.
But another of your requirements is an input that does not respond to the keyboard.
This can be accomplished easily.
In order to prevent keyboard events from affecting an input, simply write a listener function that responds to 'keydown' events.
let input = document.createElement('input');
document.body.appendChild(input);
input.addEventListener('keydown', e => {
// console.log('keydown e.key:', e.key);
// prevent default input response
e.preventDefault();
// take action on up or down arrow key
if (e.key === "ArrowUp") {
input.value = 'Up Arrow';
} else if (e.key === 'ArrowDown') {
input.value = 'Down Arrow';
} else {
console.log('key blocked: ', e.key);
}
});

Javascript Localstorage: Comparing input value with value stored in array in localstorage

My purpose is to check if value entered by user in the input field is already available in an array stored in the localstorage. If yes, print the array if not add the new value in the storage. I am getting my array back on button click but the code isn't working correctly. The output is:
["hh", "try", "vogue", "vogue", "try2", "try2", "try2", "try2"]
Above are the entered values which are getting added repetitively. I know it's a stupid issue but have least experience with handling arrays in localstorage. Any help would be appreciated. (I tried the solutions provided in similar questions on stackoverflow but no luck)
<html class=" reevoomark_ATY">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Special Offers</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
</head>
<body>
<input id="coupon"> <button style="width:50px;padding:10px;background:grey;height:30px;border:1px solid grey" id="button">Apply</button>
<input id="stored">
<script>
var coupons = ['hh'];
var storedNames;
localStorage.setItem("coupons", JSON.stringify(coupons));
$('#button').on('click', function(){
storedNames = JSON.parse(localStorage.getItem("coupons"));
var enteredValue = $('#coupon').val();
for(i=0; i <storedNames.length; i++) {
if(enteredValue === storedNames[i]) {
console.log("value Exist!!");
console.log(storedNames[]);
}
else {
console.log("in else");
coupons.push(enteredValue);
localStorage.setItem("coupons", JSON.stringify(coupons));
storedNames = JSON.parse(localStorage.getItem("coupons"));
}
}
});
</script>
</body>
</html>
You would like to push the names if it doesn't exist in the stored names. Refer attached code.
<html class=" reevoomark_ATY">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Special Offers</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
</head>
<body>
<input id="coupon"> <button style="width:50px;padding:10px;background:grey;height:30px;border:1px solid grey" id="button">Apply</button>
<input id="stored">
<script>
var coupons = ['hh'];
localStorage.setItem("coupons", JSON.stringify(coupons));
$('#button').on('click', function(){
var storedNames = JSON.parse(localStorage.getItem("coupons"));
var enteredValue = $('#coupon').val();
if (storedNames.includes(enteredValue)) {
console.log("value Exist!!");
console.log(storedNames);
} else {
console.log("in else");
storedNames.push(enteredValue);
localStorage.setItem("coupons", JSON.stringify(storedNames));
}
});
</script>
</body>
</html>

Retrieving the text input's value which was stored into localStorage

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>

Grabbing Name attribute of Tags/Tag in Rally

I have been looking at the rally Object model, but I can't figure out how to grab the Name attribute of a Defect's Tag.
I made sure to include Tag and Tags in my fetch statement. I am storing all the defects into an array of objects called defectsNEWDEFECTS[]
I can return a Tag object by doing this:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags;
document.write(tagNEWDEFECTS);
which will return this:
[object Object]
But, I can't seem to get it to return the NAME of the tag.
I tried:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Tag.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tag.Name;
But they all return 'undefined'.
Any ideas how to get the name of a tag? Ultimately, the goal here is to have user-input custom tags that I can flag in my program to do certain things. For example, one tag will be named 'RollOverDefect'.
I need to be able to determine which Defects have a Tag called 'RollOverDefect'
Thanks!
Tags is a collection, so you'll ultimately need a nested loop over the Tags collection attribute to handle this. Once you've nested into an additional loop, you can reference the Tag Name via:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags[j].Name;
Hope this is helpful - let us know if that gets the job done.
You may find this example to be useful:
<html>
<head>
<title>App Example: Defects with Tags</title>
<meta name="Name" content="App Example: Defects with Tags" />
<meta name="Version" content="2013.2" />
<meta name="Vendor" content="Rally Labs" />
<script type="text/javascript" src="/apps/1.33/sdk.js?apiVersion=1.43""></script>
<script type="text/javascript">
var table = null;
function defectsWithTagsExample() {
var rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__'
);
function itemQuery() {
var queryObject = {
key: 'defects',
type: 'Defect',
fetch: 'FormattedID,Name,State,Description,Tags,Name',
query: '(State = "Submitted")'
};
rallyDataSource.findAll(queryObject, populateTable);
}
function populateTable(results) {
if (table) {
table.destroy();
}
var tableDiv = document.getElementById('aDiv');
var config = {
'columnKeys' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnHeaders' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnWidths' : ['100px', '400px', '200px', '85px', '300px']
};
table = new rally.sdk.ui.Table(config);
table.addRows(results.defects);
for (i=0;i<results.defects.length;i++) {
myDefect = results.defects[i];
myTags = results.defects[i].Tags;
myTagString = "";
for (j=0;j<myTags.length;j++) {
myTag = myTags[j];
myTagName = myTags[j].Name;
if (j == 0) {
myTagString += myTagName;
} else {
myTagString += ", " + myTagName;
}
}
linkConfig = {item: {FormattedID: myDefect.FormattedID, "_ref" : myDefect._ref}};
defectLink = new rally.sdk.ui.basic.Link(linkConfig);
table.setCell(i, 0, defectLink.renderToHtml());
table.setCell(i, 4, myTagString);
}
table.display(tableDiv);
};
itemQuery();
}
rally.addOnLoad(defectsWithTagsExample);
</script>
</head>
<body>
<div id="aDiv"></div>
</body>
</html>

Categories

Resources