How to create a custom JSON based on form values? - javascript

I am creating a JSON based on a dynamic form values below, when the user submits, i am displaying the json feed in #results
Is it also possible to get all the values in the form when generating the JSON, I want to get the
name, ids,
title information,
input value etc
and then create/display the JSON in the order below?
A working version can viewed here :
http://jsfiddle.net/dev1212/GP2Y6/25/
Currently its not retuning any values and getting some undefined..
the code peice i tried is below
<script>
x = function(selector){
var attrs = [];
$(selector + " input").each(function(){
var attrObject = {};
$(this.attributes).each(function(index, attr){
attrObject[attr.name] = attr.value;
attrObject[attr.va] = attr.value;
//console.log(attrObject)
});
attrs.push(attrObject);
attrObject = {};
});
return attrs;
}
$(document).ready(function(){
alert(JSON.stringify(x("#myform")));
});
</script>

<script type="text/javascript" src="/www/include/js/jquery.min.js"></script>
<script>
x = function(selector){
var attrs = [];
$(selector + " input").each(function(){
var attrObject = {};
$(this.attributes).each(function(index, attr){
attrObject[attr.name] = attr.value;
//console.log(attrObject)
});
attrs.push(attrObject);
attrObject = {};
});
return attrs;
}
$(document).ready(function(){
alert(JSON.stringify(x("#myForm")));
});
</script>
<form id="myform" class="form-wd">
<input class="ui-dform-text" type="text" title="data for network.node1.eth0.ipaddr" name="network.node1.eth0.ipaddr">
</form>

Related

Getting to specific data in jQuery

I am trying to add an ability to change the contents of one of the columns in the data table (its data cells should be editable). I was using this tutorial as a reference:
https://www.youtube.com/watch?v=LbhVVN5ffi0
its source code:
https://github.com/divanov11/table-edit-backend
And so, I have the following functions in my template:
function edit_description(place){
var targetId = $(this).attr("id");
var value = $(this).text();
var targetIN = $(this).attr("identificationNumber");
$(this).unbind();
$(this).html(`<input class="description form-control" data-target="${targetId}" type="text" value=${value}>`);
$(`.description`).on('keypress', function(e){
if (e.which == 13) {
var target = $(this).attr("data-target");
var description = $(`#${target}`).text($(this).val());
save_description(description, targetIN);
return false;
}
})
}
function save_description(description, identification_number){
console.log('Saved!');
var user_input = {"identificationNumber":identification_number, "description":description};
update_description_POST(user_input);
}
After typing in for example "chipset" I get the following description's value:
<td identificationnumber = "1234" id="description-1234">chipset</td>
I would need the description's value to be just "chipset". How to achieve that?

How to replace hidden input with global variable to hold data

Currently I save data in input type="hidden" and access them from any JS script using getDocumentById("sourceJson"). For example:
<input type="hidden" id="sourceJson" name="sourceJson" >
var val = document.getElementById("sourceJson").value
But it forces me to scatter many hidden inputs in the HTML file. What is good replacement to hold data and have access to it from all scripts? Some kind of global variables that can also be submitted to the server.
If you declare a variable in any normal script it should be available from any other script.
<html><body>
<script>
var varOne = "Hello ..";
</script>
<script>
var varTwo = ".. world";
</script>
<script>
alert(varOne + varTwo);
</script>
</body></html>
Update
To Store array data we can use localStorage.setItem("data", JSON.stringify(data));
const data = localStorage.getItem("data")? JSON.parse(localStorage.getItem("data")):[];
function setData(name, value){
data.push({"name":name, "value":value});
localStorage.setItem("data", JSON.stringify(data));
}
function getData(name){
var ret = undefined;
for(var x = 0; x < data.length; x++){
if(data[x].name == name){
ret = data[x].value;
}
}
return ret;
}

Storage and show multiple outputs

I have a simple text input where users type anything and after sumbitting text appear on a page and stays there, which I done with localStorage, but after refreshing the page only last typed input is showing, Ill post my code to be more specific:
HTML:
<body>
<input id="NewPostField" type="text" value="">
<button onclick="myFunction()">Post</button>
<div id="Posts"></div>
</body>
JavaScript:
function myFunction() {
var NewPostField =
document.getElementById("NewPostField");
var newPost = document.createElement("p");
localStorage.setItem('text',
NewPostField.value);
newPost.innerHTML = NewPostField.value;
var Posts = document.getElementById("Posts");
Posts.appendChild(newPost);
}
(function() {
const previousText = localStorage.getItem('text');
if (previousText) {
var NewPostField = document.getElementById("NewPostField");
NewPostField.value = previousText;
myFunction();
}
})();
Any help will be great!
It seems that your code is only storing the last value posted.
To store more than one post, one idea is to stringify an array of values to store in localStorage.
Then, parse that stringified value back into an array as needed.
Here's an example:
function getExistingPosts() {
// fetch existing data from localStorage
var existingPosts = localStorage.getItem('text');
try {
// try to parse it
existingPosts = JSON.parse(existingPosts);
} catch (e) {}
// return parsed data or an empty array
return existingPosts || [];
}
function displayPost(post) {
// display a post
var new_post = document.createElement("p");
new_post.innerHTML = post;
posts.appendChild(new_post);
}
function displayExistingPosts() {
// display all existing posts
var existingPosts = getExistingPosts();
posts.innerHTML = '';
inputPost.value = '';
if (existingPosts.length > 0) {
existingPosts.forEach(function(v) {
displayPost(v);
});
inputPost.value = existingPosts.slice(-1)[0];
}
}
function addPost(post) {
// add a post
var existing = getExistingPosts();
existing.push(post);
localStorage.setItem('text', JSON.stringify(existing));
displayPost(post);
}
function clearPosts() {
// clear all posts
localStorage.removeItem('text');
displayExistingPosts();
}
var posts = document.getElementById("posts");
var inputPost = document.getElementById("input_post");
var btnPost = document.getElementById('btn_post');
var btnClear = document.getElementById('btn_clear');
btnPost.addEventListener('click', function() {
addPost(inputPost.value)
});
btnClear.addEventListener('click', clearPosts);
displayExistingPosts();
<input id="input_post" type="text" value="">
<button type="button" id="btn_post">Post</button>
<button type="button" id="btn_clear">Clear</button>
<div id="posts"></div>
Since localStorage isn't supported in StackSnippets, here's a JSFiddle to help demonstrate.

Get input from textarea to sort and print out. I am getting in data but am not able to sort nor print out.

<html>
<body>
//My text area
<textarea id="emailTextarea" rows ="30" cols="30" >
sara#yahoo.com
adam#yahoo.com
todd#yahoo.com
henry#yahoo.com
wright#yahoo.com
</textarea>
<p id="demo"></p>
<script>
//Getting input from the textarea for the email list
//The email list
var emailList = document.getElementById("emailTextarea").value;
//function to remove the yahoo extension
//remove the extension
var emailUserHash = emailList.reduce(function(emailUsers, email, i) {
var username = email.slice(0, email.indexOf('yahoo.com'));
if(!emailUsers[username]) emailUsers[username] = true;
return emailUsers;
}, {});
//calling the emailUserHash function
//call the emailUserHash function
var emailUsers = Object.keys(emailUserHash)
//Sort the email list
//sort the email list
emailUsers.sort();
//Print out the list
//output the list
document.write(emailUsers.join('</br>'));
</script>
</body>
Think this might be what you are trying to accomplish:
var emailList = document.getElementById("emailTextarea").value;
var emailListArray = emailList.split("\n");
var usernamesArray = emailListArray.map(function(val, index, arr) {
return val.slice(0, val.indexOf('#yahoo.com'));
});
var sortedUsernames = usernamesArray.sort();
document.write(sortedUsernames.join('</br>'));
This will output the list of email usernames sorted and with the #yahoo.com removed
You shall parse your textarea to array.
I made example with JQuery: https://jsfiddle.net/k8te23mf/
var arrayOfLines = $('#emailTextarea').val().split('#yahoo.com\n');
$('#demo').append(arrayOfLines+', ');

How to compare two before / after input values using jquery data

I'm working on a form where I need to compare values of an input. Let's say for example, I have an input which comes from the server with value name1 and then the user changes it to name2. How can I get the initial value and the new value? My script below shows my attempt at resolving this, but when I look at the console output oldAddressNameValue does not have the old value and neither does newAddressNameValue.
What am I doing wrong?
var $el = $('#inputAddressName');
var oldAddressNameValue = $el.data('oldVal', $el.val());
console.log(oldAddressNameValue);
var newAddressNameValue = $el.change(function () {
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
});
console.log(newAddressNameValue);
Thanks
The data function assigns the value to the attribute but will then return the element for jquery chaining.
If you output $el.data('oldVal') directly it should return the value.
console.log($el.data('oldVal'))
or you can assign the result of the single parameter version of .data() to the variable.
The code inside el.change is not executing until the input changes, hence the log is logging nothing, also I'm not so sure about the way you are declaring your variables. This works.
var $el = $('#inputAddressName');
var oldAddressNameValue = $el.val(),
newAddressNameValue;
console.log(oldAddressNameValue);
$el.on('change', function () {
var $this = $(this);
$this.data('newVal', $this.val());
newAddressNameValue = $this.val();
console.log(newAddressNameValue);
});
A working example here
You just placed your console logs at wrong places and the code below shows that your oldVal and newVal are both present.
$(document).ready(function() {
var $el = $('#inputAddressName');
var oldAddressNameValue = $el.data('oldVal', $el.val());
console.log(oldAddressNameValue.data("oldVal"));
var newAddressNameValue = $el.change(function() {
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
console.log(newAddressNameValue.data("newVal"));
console.log(newAddressNameValue.data("oldVal"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="inputAddressName" value="123" type="text" />
The data function returns the jQuery wrapped element. If you want to get the actual stored value, you should use $el.data(key) instead.
Here is what you need to do:
var $el = $('#inputAddressName');
$el.data('oldVal', $el.val());
$el.change(function () {
var $this = $(this);
$this.data('newVal', $this.val());
console.log($this.data('oldVal'));
console.log($this.data('newVal'));
});
And here is a fiddle too.
To find the initial value of an <input />, in JavaScript, simply use the defaultValue property:
var input = document.getElementById('inputAddressName'),
oldValue = input.defaultValue,
newValue = input.value;
For example, in jQuery:
$('#inputAddressName').on('change', function () {
var el = this,
oldValue = el.defaultValue,
newValue = el.value;
});
$('#inputAddressName').on('change', function () {
var el = this,
oldValue = el.defaultValue,
newValue = el.value;
console.log(oldValue, newValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inputAddressName" value="Default value" />
Or, instead, you can use getAttribute('value'), which returns the value from the HTML attribute (which isn't updated as the value changes, only the value property changes):
$('#inputAddressName').on('change', function() {
var el = this,
oldValue = el.getAttribute('value'),
newValue = el.value;
console.log(oldValue, newValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inputAddressName" value="Default value" />
Try
var $el = $("#inputAddressName");
$el.data({"oldVal":$el.val(), "newVal":void 0});
var oldAddressNameValue = $el.data("oldVal")
, newAddressNameValue;
$el.on("change", function () {
var $this = $(this);
$this.data("newVal", $this.val());
newAddressNameValue = $this.data("newVal");
console.log(oldAddressNameValue, newAddressNameValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input id="inputAddressName" value="name1" />

Categories

Resources