Generating JSON String from Form - javascript

I am new to JSON and trying hard to understand it's working.
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID">
<button type="submit" class="btn btn-success" >Submit Data</button>
</form>
JSON String to be generated as:
{"latency":1.6,"throughput":6.01,"outUID":{"V_ID":"40"},"inUID":{"V_ID":"16"}}
Here's the form and JSON String to be generated
Could some one guide me how do I create that nested JSON object?

Since it looks like you want the values of outUID and inUID to be nested for some reason you'll need to build the object manually. Here's a simple example:
var $latency = $('#latency'),
$throughput = $('#throughput'),
$outUID = $('#outUID'),
$inUID = $('#inUID');
var myJSONObject = {
latency:$latency.val(),
throughput:$throughput.val(),
outUID:{
V_ID:$outUID.val()
},
inUID:{
V_ID:$inUID.val()
}
};
var stringJSON = JSON.stringify(myJSONObject);

Pure javascript example
var els=document.getElemtById('edge').getElementsByTagName('input');
or
var els=document.querySelectorAll('input[class=input-"xlarge"]');
to get the elements
then
var array=[]
for(var a=0,b;b=els[a]; ++a){
array[a]=b.value
}
array is the json object
JSON.styringify(array)
is the json string
tip: if you plan to use this with ajax
there is a new way called FormData();
so:
var fd=FormData(document.getElemtById('edge'));
contains the whole form , including files

This code allow you to add more fields if required to do so without hard coding the field attributes
http://jsfiddle.net/6vQY9/
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID" data-prop="V_ID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID" data-prop="V_ID">
<button type="submit" class="btn btn-success">Submit Data</button>
</form> <pre></pre>
JS
function submit() {
var JSONString = "";
jQuery('#edge input').each(function () {
var that = jQuery(this);
var val = that.val();
var partJSON = "";
var quote = "\"";
if (that.data('prop')) {
partJSON = "{ " + quote +that.data('prop') + quote+ " : " + quote + val + quote + " }";
} else {
partJSON = val;
}
var comma = that.next('input').length > 0 ? "," : "";
partJSON = quote + that.prop('id') + quote + ":" + partJSON + comma;
JSONString += partJSON
});
JSONString = "{ " + JSONString + " }";
jQuery('pre').text(JSONString);
}

Related

Passing a Query from one Domain to another using JavaScript

I need to be able to create a query based off the users input of "Test" in an INPUT of Site A (SiteA.com) that will open Site B in the same window once submitted, passing along the query (SiteB.com/search.aspx?k=test).
Code on SiteA.com
var siteSearch = "SiteB.com/search.aspx";
$("#sitesubmitBtn").click(submitClick);
function submitClick() {
var q = $(location).attr('protocol') + "//" + $(location).attr('hostname') + siteSearch;
var k = $("#sitesearchInput").val();
window.location.href = q + "?k=" + k;
return false;
}
<input name="search" placeholder="Search" id="sitesearchInput" type="text">
<button id="sitesubmitBtn" type="submit"></button>
You are describing a simple HTML form. You don't need JavaScript/jQuery for that to happen.
<form method="GET" action="//SiteB.com/search.aspx">
<input type="text" name="k" placeholder="Search term" />
<button type="submit">Search</button>
</form>
change this line
var q = $(location).attr('protocol') + "//" + $(location).attr('hostname') + siteSearch;
to :
var q = $(location).attr('protocol') + "//" + siteSearch;
because you already define your hostname in this line:
var siteSearch = "SiteB.com/search.aspx";

How to save user input to local storage

I am creating a score keeping app and need to save the name of the players and the game name in local storage, have no idea how to apply it to the code I have
$(document).ready(function() {
$("#add-playername").click(function(e) {
e.preventDefault();
var numberOfPlayernames = $("#form1").find("input[name^='data[playername]']").length;
var label = '<label for="data[playername][' + numberOfPlayernames + ']">Playername ' + (numberOfPlayernames + 1) + '</label> ';
var input = '<input type="text" name="data[playername][' + numberOfPlayernames + ']" id="data[playername][' + numberOfPlayernames + ']" />';
var removeButton = '<button class="remove-playername">Remove</button>';
var html = "<div class='playername'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-playername").before(html);
});
});
$(document).on("click", ".remove-playername", function(e) {
e.preventDefault();
$(this).parents(".playername").remove(); //remove playername is connected to this
$("#form1").find("label[for^='data[playername]']").each(function() {
$(this).html("Playername " + ($(this).parents('.playername').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form2" method="post">
<div class="gamename">
<label><b>Enter Game Name</b></label>
<input type="text" name="game name" placeholder="Game Name" id="user_input">
</div>
</form>
<form id="form1" method="post">
<div class="playername">
<label for="data[playername][0]">Add Player Name</label>
<input type="text" name="data[playername][0]" placeholder="Enter player's name" id="data[playername][0]" />
</div>
<button id="add-playername">Add Player</button>
<br>
<br>
<input type="submit" value="Submit" />
</form>
Grab game and players using the jquery selector on form submit by preventing the form using jquery
Prepare object for the game and players
Convert the object to a string using the JSON.stringify( your_data_object) function
Save to localStorage using localStorage.setItem( 'key' , 'value' ) function
<script>
$('#form1').submit(function(){
var game_name = $("#form2 #user_input").val();
var players = [];
var players_inputs = $("#form1").find("input[name^='data[playername]']");
$.each(players_inputs, function(){
var player = $(this).val();
players.push(player);
});
var data = {
game_name : game_name,
players: players
}
console.log(data);
// save to localstorage
localStorage.setItem('game_players', JSON.stringify(data) );
event.preventDefault();
});
</script>
late to answer but something like this
<input type="submit" value="Submit" id="btn_submit" />
<script type="text/javascript">
$(document).ready(function(){
$("#btn_submit").click(function(e){
e.preventDefault();
var jsonObj = [];
players = {}
count = 0;
$('input[type=text]').each(function(){
if($.trim($(this).val()) && ($(this).attr('name').indexOf("playername") >= 0)){
players[count++] = $(this).val()
}
});
players['game_name'] = $("#user_input").val();
jsonObj.push(players);
console.log(jsonObj);
var jsonString= JSON.stringify(jsonObj);
localStorage.setItem("jsonString", jsonString);
/* remove localstorage */
// localStorage.removeItem("jsonString");
/* get localstorage */
// console.log(localStorage.getItem("jsonString"));
});
</script>

Count values from <input type="text"

Hello i want to count the ids inside a input type="text"
the values return as this 1,4,6 etc
<input type="hidden" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
here the only javascript version :
var testme = function() {
var myInput = document.getElementById('selected_ids');
var myValue = myInput.value;
var myCount = myValue.split(',').length;
document.body.innerHTML += '<br>myValue = ' + myValue + ' | myCount = ' + myCount;
}
<input type="text" class="selected_ids" value="1,4,6" name="selected_ids[]" multiple="yes" id="selected_ids" />
<button onclick='testme()'>test me</button>
You can use split function. for example :
var curval = document.getElementById('selected_ids').value;
var curval_arr = curval.split(',');
var cnt = curval_arr.length;
First, your input type needs to be text and not hidden. It's not possible to enter values in a hidden text box.
So your text box should be :-
<input type="text" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
Now suppose the user enters 1,4,6 into the text box(make sure the numbers are separated by a comma). Then on the PHP side you can access as follows.
<?php
$array = explode(',', $_POST['selected_ids']); //this array consists all the elements.
//To get length, do :-
count($array);
?>

return string in javascript

I want to get apiUrl depending on a user's input
<form name="test">
<input type="text" name="Edit">
<input type="button" value="Test" onClick="gettext()">
<input type="text" name="Edit2" readonly style="border:1px solid white">
</form>
Then i have a script which does not work, to form a url based on that
<script>
function gettext(Edit, Edit2) {
document.test.Edit2.value=document.test.Edit.value;};
var apiKey = '07gh4c95ca7e23d41ghggf/';
var userWord = Edit2;
var txtjson = '/json';
var apiUrl = 'http://words.bighugelabs.com/api/2/' + apiKey + userWord + txtjson;
</script>
I need var userWord to be a string to insert its value in the apiUrl.
Please help me with that. Thank you
Edit2 is not declared outside the gettext function. Try this:
function gettext(Edit, Edit2) {
document.test.Edit2.value = document.test.Edit.value;
return document.test.Edit2.value;
}
var userWord = gettext(<param1>, <param2>);

What's the best way to update the input names when dynamically adding them to a form?

I'm trynig to come up with a clean and efficient way of handling form input names when dynamically adding more to the POST array.
For example, if I have the following form:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I then click an 'addmore' button which duplicates that HTML and adds it back into the document. Resulting in:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I'm trying to find the best way to increment that name index so I can use the data on the server. So far, I've been using the following code:
$('.addmore').click(function()
{
var $button = $(this);
var $fieldset = $button.prev('fieldset');
var $newset = $('<div class="new">' + $fieldset[0].innerHTML + '</div>');
$newset.insertBefore($button);
updatenames($newset, $('fieldset').length + 1);
});
function updatenames($set, newIndex)
{
/*
updates input names in the form of
set-index.name
set-index
*/
var findnametype = function(inputname)
{
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') != -1)
{
var data1 = inputname.split('-');
var data2 = data1[1].split('.');
// [type, set, index]
return [1, data1[0], parseInt(data2[0])]
}
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') == -1)
{
var data = inputname.split('-');
return [2, data[0], data[1]];
}
return false;
};
var type = findnametype($set.find('input:eq(0)')[0].name);
$set.find('input, select').each(function()
{
var $input = $(this);
var oldname = $input[0].name;
var newname = false;
switch (type[0])
{
case 1: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
case 2: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
}
$input[0].name = newname;
});
return type;
}
That updatenames function is a variation of what I've been using lately. In this case, I check to find the format of the input name. I then increment the index.
The incrementing, as you've probably noticed, happens in the DOM. As a 'part 2' to my question, I'd like to learn how to have that object returned for me to then insert into the DOM.
Something like:
$newset = updatenames($newset, $('fieldset').length +1);
$newset.insertBefore($button);
Your help is appreciated. Cheers.
Have you considered using array-based field names? You wouldn't have to alter those at all:
<input type="text" name="users.firstname[]" />
<input type="text" name="users.lastname[]" />
whether this works for you will of course depend on what you're going to do with the fields.
<script type="text/javascript">
$(document).ready(function () {
$('.addmore').click(function () {
var fieldset = $(this).prev('fieldset');
var newFieldset = fieldset.clone();
incrementFieldset(newFieldset);
newFieldset.insertBefore($(this));
});
});
function incrementFieldset(set) {
$(set).find('input').each(function () {
var oldName = $(this).attr('name');
var regex = /^(.*)-([0-9]+)\.(.*)$/;
var match = regex.exec(oldName);
var newName = match[1] + '-' + (parseInt(match[2]) + 1) + '.' + match[3];
$(this).attr('name', newName);
});
}
</script>
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
<input type="button" class="addmore" value="Add" />
<fieldset>
<input index=1 var=user prop=firstname />
<input index=1 var=user prop=lastname />
</fieldset>
<fieldset>
<input index=2 var=user prop=firstname />
<input index=2 var=user prop=lastname />
</fieldset>
before you submit your form
get the custom attributes and construct your 'name' attribute
[update]
its jsp but shouldn't be hard for u to convert to php
<%
for (int i = 0; i < 1000; i++) {
%>
<fieldset>
<input index=<%=i%> var=user prop=firstname />
<input index=<%=i%> var=user prop=lastname />
</fieldset>
<%
}
%>
for the js code
$('button').click(function(){
$('input').each(function(i, node){
var $node = $(node);
$node.attr('name', $node.attr('var') + $node.attr('index') + "."+ $node.attr('prop'))
});
});

Categories

Resources