Parsing JSON from input value in Javascript? - javascript

I'm completely new to the subject of JSON and I was wondering how to parse JSON from an input value in my form.
I'm trying to string the inputs into an array like {"task" : "(input) ", "(input) "} {"description" : "(input ", "(input)"}
I tried to follow the same directions as this post: Adding a new array element to a JSON object but they're referring to strings already formulated when I want to be able to parse JSON the same way from an input in my form. I want to be able to save every input and add a new array element the same way.
Bottom code runs smoothly but I'm such a noobie at parsing JSON D: any help is appreciated.
function submitForm() {
var task = myForm.task.value;
var desc = myForm.description.value;
var FormData = {
task: task,
description: desc
};
myJSON = JSON.stringify(FormData);
localStorage.setItem("formJSON", myJSON);
text = localStorage.getItem("formJSON");
obj = JSON.parse(text);
addTask(task);
addDescription(desc);
console.log(FormData);
return false;
};
newArray = [task, description];
var taskArray = [];
var descriptionArray = [];
var task = document.getElementById("task").value;
var description = document.getElementById("description").value;
function addTask(task) {
taskArray.push(task);
console.log(
"Tasks: " + taskArray.join(", "));
}
function addDescription(description) {
descriptionArray.push(description);
console.log("Description: " + descriptionArray.join(", "));
};
<!DOCTYPE html>
<html>
<title>Task Form</title>
<body>
<form class="form-inline" name="myForm" onsubmit=" return submitForm()">
<label class="required">*Task and Description* </label>
<!first text box>
<div class="form-group">
<input type="text" id="task" placeholder="Task">
</div>
<!second comment box>
<div class="form-group">
<input type="text" id="description" placeholder="Description">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
<script type="text/javascript " src="json.js "></script>
</body>
</html>

You should be storing the array of all tasks in localStorage, not just a single task. When the user saves a new task, read the JSON from local storage, parse it, add the new task to the array, and save that.
function submitForm() {
var task = myForm.task.value;
var desc = myForm.description.value;
var FormData = {
task: task,
description: desc
};
var arrayJSON = localStorage.getItem("formJSON") || "[]";
var taskArray = JSON.parse(arrayJSON);
taskArray.push(FormData);
localStorage.setItem("formJSON", JSON.stringify(taskArray));
addTask(task);
addDescription(desc);
console.log(FormData);
return false;
};

Related

How do I get the VideoListByID query data form user with Google App Script HTML Service

Hello I am working on a Google App script project which interacts with Youtube Data API 3
Right now I am using the function videosListById
i need to get the video list id from user by a HTML form which i have already but data from the form is not connected to the script
Need help with the data input and connection with front end This is my code
I tried to get the data by id but inside the videoListByID but still no success
.Gs part
/getting Videos from Youtube with IDs/
function videosListById(data) {
var mid = data.mids;
var blogid = data.BLOGID;
// Uncomment this for furure
return mid + blogid;
Logger.log(mid+blogid)
// var mid = ('Ks-_Mh1QhMc') /** video id **/
var results = YouTube.Videos.list("id,snippet",{'id': mid});
for(var i in results.items) {
var item = results.items[i];
Logger.log('%s Description: %s', item.snippet.title,
item.snippet.description);
HTML Part of code
<html>
<head>
<base target="_top">
</head>
<body>
Please fill in the form below.<br><br>
<form id="myForm" onsubmit="google.script.run.withFailureHandler
(Logger.log(data)).withSuccessHandler
(console.log).videosListById(data);return false;">
videoID:
<input type="text" name="mids"><br><br>
BlogID:
<input type="text" name="BLOGID"><br><br>
<br>
<input type="submit" name="Submit">
</form><br>
<input type="button" value="Cancel" onclick="google.script.host.close()"/>
</body>
</html>
I got the answer by myself , the issues is when i search with keyword the extracted description is not fully extracted using this method we can pass the video id to next function and get the description
function searchByKeyword(){
var results = YouTube.Search.list("id,snippet", {q : "trailers", maxResults:
"1",type:
"video"});
Logger.log(' search results: %s', results.items);
for(var i in results.items) {
var item = results.items[i];
Logger.log("[%s] Title: %s", item.id.videoId, item.snippet.title);
}
var item = results.items[i];
var results = YouTube.Videos.list("id,snippet",{'id': item.id.videoId });
for(var i in results.items) {
var item = results.items[i];
Logger.log('%s Description: %s', item.snippet.title, item.snippet.description);
}
for(var i in results.item) {
var item = results.item[i];
}

Unable to push data to Firebase onclick

So I've recently been messing with Firebase and I came across an issue I need some help fixing. So I'm trying to send the data from the user input to Firebase, and for that data to show up in the specified div, but the data isn't showing up in my Firebase, or in that div...
Here's my HTML Code:
<form>
<input name="name" class="form-control" type="name" placeholder="Title" id="titleInput" />
<br/>
<textarea id="postInput" name="content" data-provide="markdown" rows="10"></textarea>
<hr/>
<button type="submit" class="btn" onclick="submitPost()">Submit</button>
</form>
And my JQuery Code (EDITED):
function submitPost() {
var myDataRef = new Firebase('https://EXAMPLE.firebaseio.com/');
var name = $('#titleInput').val();
var text = $('#postInput').val();
myDataRef.push({name: name, text: text});
$('#postInput').val('');
myDataRef.on('child_added', function(snapshot) {
var post = snapshot.val();
displayUserPost(post.name, post.text);
})
function displayUserPost(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#PostsDiv'));
$('#PostsDiv')[0].scrollTop = $('#PostsDiv')[0].scrollHeight;
}
};
You're dealing with asynchronous data flow, so you should listen for the data outside of the submitPost function.
var myDataRef = new Firebase('https://EXAMPLE.firebaseio.com/');
myDataRef.on('child_added', function(snapshot) {
var post = snapshot.val();
displayUserPost(post.name, post.text);
});
function submitPost(e) {
var myDataRef = new Firebase('https://EXAMPLE.firebaseio.com/');
var name = $('#titleInput').val();
var text = $('#postInput').val();
myDataRef.push({name: name, text: text});
$('#postInput').val('');
e.preventDefault();
}
function displayUserPost(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#PostsDiv'));
$('#PostsDiv')[0].scrollTop = $('#PostsDiv')[0].scrollHeight;
}

Getting values from list<String> , split them and then slice them by parts, using JavaScript

I have List<String> from Spring MVC which i want to split, slice and print on browser. The problem is that i need to enter a start and end argument of slice() method as a variable from text-field. This is my code, but it doesn't work. Can someone helps me with that? This is my code:
<body>
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction()">Press</button>
<p id="demos"></p>
</form>
<script>
function myFunction() {
var str = "${first}";
var arr = str.split(",");
var first = document.getElementById('firstvalue');
var second = document.getElementById('lastvalue');
document.getElementById("demos").innerHTML = arr.slice('first', 'second');
}
</script>
</body>
Thank you in advance!
you got some issues in your code.
if ${first} is List<String>, then you need to convert it to a concatenated single comma separated String. Because by ${first} you are just printing list object.
slice expects index which is number, you are passing String
You are not doing .value after document.getElementById
You are not passing the user input variables first and second to slice, Instead you are passing hardcoded strings 'first' and 'second'.
Below is the fixed code
HTML
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction(event)">Press</button>
<p id="demos"></p>
</form>
JS
var myFunction = function (e) {
var str = "${first}" // assuming this contains string like "1,2,3,4,5,6,7,8,9,10"; and not the List obect
var arr = str.split(",");
var first = document.getElementById('firstvalue').value;
var second = document.getElementById('lastvalue').value;
document.getElementById("demos").innerHTML = arr.slice(parseInt(first, 10), parseInt(second, 10)).toString();
e.preventDefault();
};
What do we want to achieve?
We have two input textfields: one holding a start value and one holding an end value. On a click we want to create a range from the start to the end value and output it into a container.
Solution
The solution is more simple than expected and we do not require split, slice and part. Also we do not really require a predefined list holding all values.
Example
<html>
<head>
<script>
function evalRange(){
var tS = parseInt(document.querySelector('#inFrom').value); //Our start value;
var tE = parseInt(document.querySelector('#inTo').value); //Our end value;
var tR = document.querySelector('#demos'); //Our output div
if (tE >= tS){
//We are using the Array.apply prototype to create a range
var tL = Array.apply(null, Array(tE - tS + 1)).map(function (a, i){return tS + i});
//We output the range into the demos div
tR.innerHTML = tL.join(',')
}
else tR.innerHTML = 'To has to be higher than from';
//Returning the range list
return tL
}
</script>
</head>
<body>
<input type = 'text' id = 'inFrom' value = '10' />
<input type = 'text' id = 'inTo' value = '20' />
<b onclick = 'evalRange()'>Range</b>
<div id = 'demos'></div>
</body>
</html>
And here is a fiddle for it: https://jsfiddle.net/91v3jg66/

Trigger a html button inside a web browser control

in my web browser control i am accessing a form:
<form role="form">
<div class="form-group">
<input type="text" class="form-control" id="InputEmail1" placeholder="name...">
</div>
<div class="form-group">
<input type="email" class="form-control" id="InputPassword1" placeholder="email...">
</div>
<div class="form-group">
<textarea class="form-control" rows="8" placeholder="message..."></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
How can i trigger this button automatically from vb.net application? how can i set text to the text area? am accessing the text box as follows:
WebBrowser1.Document.GetElementById("InputEmail1").SetAttribute("value", "Sample")
WebBrowser1.Document.GetElementById("InputPassword1").SetAttribute("value", "Sample")
i cannot access button and text area since it does not have an id or name? is their any possibility to do like this?
Your elements need to have IDs and if you doesn't have access to the html code you can enumerate elements like this but you must know which element is the right one:
foreach (HtmlElement element in WebBrowser1.Document.Forms[0].All)
{
if (element.TagName.ToLower() == "textarea".ToLower())
{
element.InnerText = "text";
}
}
for clicking a button try this:
element.InvokeMember("click");
In a lot of web automation, unless you can get the original devs to add ids, you have to navigate the DOM in order to find what you need.
Here is an example of doing that kind of filtering and web automation
var actionPanel = topPanel.insert_Above(40);
var ie = topPanel.add_IE_with_NavigationBar().silent(true);
var server = "http://127.0.0.1.:8080";
Action<string,string> login =
(username, password) => {
ie.open(server + "/jpetstore/shop/signonForm.do");
ie.field("username",username);
ie.field("password",password);
ie.buttons()[1].click();
};
Action loginPlaceAnOrderAndGoToCheckout =
()=>{
ie.open("http://127.0.0.1:8080/jpetstore");
ie.link("Enter the Store").click();
//login if needed
var signOffLink = ie.links().where((link)=> link.url().contains("signonForm.do")).first();
if(signOffLink.notNull())
{
signOffLink.click();
login("j2ee", "pwd1");
}
ie.links().where((link)=> link.url().contains("FISH"))[0].click();
ie.link("FI-FW-01 ").flash().click();
ie.links().where((link)=> link.url().contains("addItemToCart"))[0].flash().click();
ie.links().where((link)=> link.url().contains("checkout.do"))[0].flash().click();
ie.links().where((link)=> link.url().contains("newOrder.do"))[0].flash().click();
};
Action scrollToTotal =
()=>{
var tdElement = ie.elements().elements("TD").toList().Where((element)=> element.innerHtml().notNull() && element.innerHtml().contains("Total:")).first();
tdElement.scrollIntoView();
tdElement.injectHtml_beforeEnd("<h2><p align=right>Look at the Total value from the table above (it should be 18.50)</p><h2>");
};
Action<string> exploit_Variation_1 =
(payload) => {
loginPlaceAnOrderAndGoToCheckout();
ie.buttons()[1].flash().click();
ie.open(server + "/jpetstore/shop/newOrder.do?_finish=true&" + payload);
scrollToTotal();
};
Action<string> exploit_Variation_1_SetTotalPrice =
(totalPrice) => {
var payload = "&order.totalPrice={0}".format(totalPrice);
exploit_Variation_1(payload);
};
Another option (which I also use quite a lot) is to actually use Javascript to do those actions (which is much easier if jQuery is available (or injected) in the target page).
[Test] public void Issue_681__Navigating_libraries_views_folders__Clicking_the_icon_doesnt_work()
{
var tmWebServices = new TM_WebServices();
Func<string, string> clickOnNodeUsingJQuerySelector =
(jQuerySelector)=>
{
ie.invokeEval("TM.Gui.selectedGuidanceTitle=undefined");
ie.invokeEval("$('#{0}').click()".format(jQuerySelector));
ie.waitForJsVariable("TM.Gui.selectedGuidanceTitle");
return ie.getJsObject<string>("TM.Gui.selectedGuidanceTitle");
};
if (tmProxy.libraries().notEmpty())
{
"Ensuring the the only library that is there is the TM Documentation".info();
foreach(var library in tmProxy.libraries())
if(library.Caption != "TM Documentation")
{
"deleting library: {0}".debug(library.Caption);
tmProxy.library_Delete(library.Caption);
}
}
UserRole.Admin.assert();
tmProxy.library_Install_Lib_Docs();
tmProxy.cache_Reload__Data();
tmProxy.show_ContentToAnonymousUsers(true);
ieTeamMentor.page_Home();
//tmWebServices.script_Me_WaitForClose();;
//ieTeamMentor.script_IE_WaitForComplete();
ie.waitForJsVariable("TM.Gui.selectedGuidanceTitle");
var _jsTree = tmWebServices.JsTreeWithFolders();
var viewNodes = _jsTree.data[0].children; // hard coding to the first library
var view1_Id = viewNodes[0].attr.id;
var view5_Id = viewNodes[4].attr.id;
var click_View_1_Using_A = clickOnNodeUsingJQuerySelector(view1_Id + " a" );
var click_View_5_Using_A = clickOnNodeUsingJQuerySelector(view5_Id + " a" );
var click_View_1_Using_Icon = clickOnNodeUsingJQuerySelector(view1_Id + " ins" );
var click_View_5_Using_Icon = clickOnNodeUsingJQuerySelector(view5_Id + " ins" );
(click_View_1_Using_A != click_View_5_Using_A ).assert_True();
(click_View_5_Using_A == click_View_1_Using_Icon).assert_False(); // (Issue 681) this was true since the view was not updating
(click_View_5_Using_A == click_View_5_Using_Icon).assert_True();
}

storing user input in array

I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.

Categories

Resources