generate JSON data based on input fields - javascript

I would like to generate JSON data based on the following input fields:
name
uRL
where the JSON data output would look something like this:
{
"items": [
{
"url": "content/San-Francisco/berkeleyCampanile.jpg",
"name": "Image 1 name"
},
{
"url": "content/San-Francisco/castro.jpg",
"name": "Image 2 name"
},
{
"url": "content/San-Francisco/Tenderloin.jpg",
"name": "Image 3 name"
}
]
}
How it works right now is that theres two input field, name and url, and users can add another set of name and url inputs by clicking on the add button as shown on the picture
What I want is that when the user hits on generate it output based on all of the input filled the json data as shown on the format above.
Below is the code:
<head>
<link href="css/style.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<fieldset id="buildyourform">
<legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />
<script>
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" \"id=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
var url = $("<input type=\"text\"id=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
</script>
</body>
</html>
Any help will be greatly appreciated
Update:
<html>
<head>
<link href="css/style.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<form id="myform">
<fieldset id="jsonBuilder">
<legend id="legendHead">Neighboorhood Creation</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="submit" value="generate" class="add">
</form>
<script>
function showValues() {
var frm = $('#myform');
var data = JSON.stringify(frm.serializeArray());
}
</script>
<script>
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" \"id=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
var url = $("<input type=\"text\"id=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#jsonBuilder").append(fieldWrapper);
});
});
</script>
</body>
</html>

A suggestion:
same ids are getting repeated so i changed it to class.
All you need is this:
$('#preview').click(function(){
var o = {"items":[]}; // create an object with key items to hold array
$('.fieldwrapper').each(function(){ // loop in to the input's wrapper
var obj = {
url : $(this).find('.url').val(), // place the url in a new object
name : $(this).find('.name').val() // place the name in a new object
};
o.items.push(obj); // push in the "o" object created
});
$('#console').text(JSON.stringify(o)); // strigify to show
});
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" \" placeholder=\"Name of Neighborhood\"class=\"name fieldname\" />");
var url = $("<input type=\"text\" placeholder=\"Paste here the URL of the Image\"class=\"url fieldname\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
$('#preview').click(function(){
var o = {"items":[]}; // create an object with key items to hold array
$('.fieldwrapper').each(function(){ // loop in to the input's wrapper
var obj = {
url : $(this).find('.url').val(), // place the url in a new object
name : $(this).find('.name').val() // place the name in a new object
};
o.items.push(obj); // push in the "o" object created
});
$('#console').text(JSON.stringify(o)); // strigify to show
});
});
#console {
background: #c5c5c5;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="buildyourform">
<legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />
<div id='console'></div>

I have made a JSFiddle for your guidance. Please take a look.
JSFiddle
$( "form" ).submit(function( event ) {
var items = {};
items["items"] = $( this ).serializeArray();
console.log(JSON.stringify(items));
event.preventDefault();
});
<form>
<input type="text" name="url" />
<input type="text" name="image" />
<input type="text" name="url" />
<input type="text" name="image" />
<button class="generate" type="submit" id="generate">Generate</button>
</form>

You can use the JQuery .serializeArray() method, here's the documentation
Here's an example:
var json = $('#form').serializeArray();
If you don't want to add the form tag to your code, here's a script that creates the JSON from your current form, FIDDLE
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" placeholder=\"Name of Neighborhood\"class=\"fieldname\" name=\"name\" />");
var url = $("<input type=\"text\" placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" name=\"url\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
$('#preview').click(function(){
var json = {};
json.items = [];
$('.fieldwrapper').each(function(e){
var obj = {};
obj.name = $(this).find('input[name=name]').val();
obj.url = $(this).find('input[name=url]').val();
json.items.push(obj);
});
console.log(json);
});
});

With Json Indentation
html
<fieldset id="buildyourform">
<legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />
<pre id="json"></pre>
Javascript
var items = {'items':[]}
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" \"class=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
var url = $("<input type=\"text\"class=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
$('#preview').on('click',function(){
$('.fieldwrapper').each(function(){
items.items.push({'url':$(this).find('.url').val(),'name':$(this).find('.fieldname').val()});
});
document.getElementById("json").innerHTML = JSON.stringify(items, undefined, 2);
});
});
here is a Fiddle

Here is another one without the form demo#fiddle
$("#preview").click(function() {
var arr = {};
arr.items = [];
$(".fieldwrapper").each(function() {
var entry = {}
var neighborhood = $(this).find("input[name='neighborhood']").val();
var url = $(this).find("input[name='url']").val();
entry["url"] = url;
entry["name"] = neighborhood;
arr.items.push(entry);
});
alert (JSON.stringify(arr, null, 4));
});
P.S. I have added name attributes to your input elements.

Related

How can I replace a variable in one method from another method

I am working a project where I can add checkboxes but at first I make a textbox and then I press done and then the another button will replace that textbox with the value of that textbox.
When I have them in different methods the variable is not defined and when I put it in the same method it prints out in the console as twice the ids I need.
The first one below is the one that doubles the id - look at the console For both.
$("#addBtn").click(function() {
var lastField = $("#buildyourform div:last"); // Getting the id of #buildyourownform and getting the last div
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1; // Changing the Id
const fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
// console.log(intId);
var fName = $("<input type=\"text\" class=\"fieldname\" />");
var ftype = $("<input type=\"checkbox\" class=\"giannisCheckbox\" />");
fieldWrapper.append(ftype);
fieldWrapper.append(fName);
$("#buildyourform").append(fieldWrapper);
$("#doneBtn").click(function() {
// $("#yourform").remove();
$("#buildyourform div").each(function() {
var id = "checkbox" + $(this).attr("id").replace("field", "");
console.log(id);
var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
fName.replaceWith(label);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="addBtn" value="Add" />
<input type="button" id="doneBtn" value="Done" />
<fieldset id="buildyourform"></fieldset>
$("#addBtn").click(function() {
var lastField = $("#buildyourform div:last"); // Getting the id of #buildyourownform and getting the last div
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1; // Changing the Id
const fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
// console.log(intId);
var fName = $("<input type=\"text\" class=\"fieldname\" />");
var ftype = $("<input type=\"checkbox\" class=\"giannisCheckbox\" />");
fieldWrapper.append(ftype);
fieldWrapper.append(fName);
$("#buildyourform").append(fieldWrapper);
});
$("#doneBtn").click(function() {
// $("#yourform").remove();
$("#buildyourform div").each(function() {
var id = "checkbox" + $(this).attr("id").replace("field", "");
// console.log(id);
var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
fName.replaceWith(label);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="addBtn" value="Add" />
<input type="button" id="doneBtn" value="Done" />
<fieldset id="buildyourform"></fieldset>
Try this
let $buildyourform = $("#buildyourform");
$("#addBtn").click(function() {
let intId = $buildyourform.children().length + 1;
$("#buildyourform").append(`
<div class="fieldwrapper" id="field${intId}">
<input type="checkbox" class="giannisCheckbox" />
<input type="text" class="fieldname" />
</div>
`);
});
$("#doneBtn").click(function() {
$buildyourform.children().each(function() {
let $checkbox = $(this).find('.giannisCheckbox');
let $fieldname = $(this).find('.fieldname');
let id = "checkbox" + $(this).attr("id").replace("field", "");
$checkbox.attr('id', id);
$fieldname.replaceWith(`<label for="${id}">${$fieldname.val()}</label>`);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="addBtn" value="Add" />
<input type="button" id="doneBtn" value="Done" />
<fieldset id="buildyourform"></fieldset>

Looping dynamic data in JavaScript append

I'm trying to add dynamic fields in my view with jQuery and it's working, the issue that i have is to load my dynamic data in appended part by jQuery.
Here is my code:
$(document).ready(function() {
$("#add").click(function() {
var loopsData = [
#foreach($attributes as $attribute) {
value: '{{ $attribute->id }}',
text: '{{ $attribute->title }}'
}
#unless($loop - > last),
#endunless
#endforeach
];
console.log(loopsData);
var lastField = $("#buildyourform div:last");
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1;
var fieldWrapper = $("<div class=\"col-md-12 mt-20\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
var fName = $("<label for=\"title\">Title</label><input type=\"text\" name=\"title[]\" class=\"form-control\" />");
var fType = $("<label for=\"attribute_id\">Parent</label><select name=\"attribute_id\" id=\"attribute_id\" class=\"form-control\"><option value=\"\">Select</option><option value=" + loopsData['value'] + ">" + loopsData['text'] + "</option></select>");
var removeButton = $("<input type=\"button\" class=\"btn btn-xs btn-danger\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(fType);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="buildyourform">
<div class="col-md-12 mt-20">
Title
<input type="text">
</div>
<div class="col-md-12 mt-20">
Parent
<select name="attribute_id" id="attribute_id" class="form-control">
<option value="">Select</option>
#foreach($attributes as $attribute)
<option value="{{$attribute->id}}">{{$attribute->title}}</option>
#endforeach
</select>
</div>
</div>
<!-- buttons -->
<input type="button" value="Add a field" class="add" id="add" />
<!-- buttons -->
Issue
When I use console.log(loopsData); it returns my data correctly.
But in my form is says undefined
I think I need to use $each in this part:
<option value="+loopsData['value']+">"+loopsData['text']+"</option>
but when I used that i gets me syntax error.
Help wanted
I need your help to loop my code without getting syntax error?
thanks.
SOLVED
here is how i solved my problem thanks to those who vote-down without even trying to help!
First i added this code tho my script:
var loopsData = [
#foreach($attributes as $attribute)
{ value: '{{ $attribute->id }}', text: '{{ $attribute->title }}' }
#unless ($loop->last)
,
#endunless
#endforeach
];
var helpers = '';
$.each(loopsData, function(key, value) {
helpers += '<option value="'+value.value+'">'+value.text+'</option>';
});
And then I changed my append part to use helpers var instead of option html code.
<select name=\"attribute_id[]\" id=\"attribute_id\" class=\"form-control\"><option value=\"\">Select</option>"+helpers+"</select>
Here is full code:
$(document).ready(function() {
$("#add").click(function() {
//my data from controller
var loopsData = [
#foreach($attributes as $attribute)
{ value: '{{ $attribute->id }}', text: '{{ $attribute->title }}' }
#unless ($loop->last)
,
#endunless
#endforeach
];
//looping my data in jQuery and return result as option html
var helpers = '';
$.each(loopsData, function(key, value) {
helpers += '<option value="'+value.value+'">'+value.text+'</option>';
// += will add new option to my select box for each one of my loop data
});
//add it to my code
var lastField = $("#buildyourform div:last");
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1;
var fieldWrapper = $("<div class=\"col-md-4 mt-20\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
var fName = $("<label for=\"title\">Title</label><input type=\"text\" name=\"title[]\" class=\"form-control\" />");
var fType = $("<label for=\"attribute_id\">Parent</label><select name=\"attribute_id[]\" id=\"attribute_id\" class=\"form-control\"><option value=\"\">Select</option>"+helpers+"</select>");
var removeButton = $("<button type=\"button\" class=\"btn btn-danger\"><i class=\"fa fa-minus\"></i></button>");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(fType);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
Hope it helps someone else.

C# - Loop through HTML textarea

I am generating HTML text areas with javascript code below:
<script>
$(document).ready(function () {
var i = 1;
$('#add').click(function () {
i++;
$('#dynamic_field').append('<tr id="row' + i + '"><td><textarea runat="server" id="choice" placeholder="Enter choice text" class="form-control"></textarea></td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function () {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
});
After generating text areas, i want to get values of it. I have tried to get values with the code below:
foreach (Control item in this.Controls)
{
ArrayList ary = new ArrayList();
//We just need HtmlInputCheckBox
System.Web.UI.HtmlControls.HtmlTextArea _cbx = item as System.Web.UI.HtmlControls.HtmlTextArea;
if (_cbx != null)
{
ary.Add(_cbx.Attributes["id"].ToString());
}
}
But, it can not find any values. Any help will be appreciated, thank you.

How to fetch search data from databse in php

Here in my code I take a div TextBoxContainer. Now I want that when I click on DynamicTextBox in script inputbox, it displays search values, which are already in the database. I have tried already autocomplete for that but it doesn't work.
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$( "#DynamicTextBox" ).autocomplete({
source: 'search1.php'
});
$("#btnGet").bind("click", function() {
var values =
$.map($("input[name=DynamicTextBox]"), function(el) {
return el.value
}).join(",\n");
$("#anotherTextbox").val(values);
});
$("#btnGet").bind("click", function() {
var values =
$.map($("input[name=DynamicTextBox1]"), function(el) {
return el.value
}).join(",\n");
$("#anotherTextbox1").val(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" style="width:280px;margin-left:10px;" id="DynamicTextBox" class="skills" type="text" value = "' + value + '" /> ' + '<input style="width:280px;" name = "DynamicTextBox1" type="text" value = "' + value + '" /> ' +
'<span type="button" class="remove glyphicon glyphicon-remove"></span>'
}
</script>
<html>
<div id="TextBoxContainer"></div>
</html>

write data in some text

i have following code
<html>
<script type="text/javascript">
function writeit()
{
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
tbox.value = '';
}
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
tbox.value = '';
}
}
</script>
<form name="a_form">
Product name:
<input type="text" id="a_tbox_1" name="a_tbox" value="" />
price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</html>
main idea of program is that i should give me possibilites to write two value product name and price and click after write ii it should write these informations in some text how to do it?please help
function writeit()
{
var strValue = '';
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
//tbox.value = '';
// add:
strValue = 'name: ' + tbox.value;
}
if(strValue != '')
strValue += ', ';
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
//tbox.value = '';
// add:
strValue += 'price: ' + tbox.value + ' € :)';
}
alert(strValue);
// or do whatever you want with it...
}
Your questin is not clear, but try the code below and see if its what you are looking for:
<html>
<head>
<title></title>
<script type="text/javascript">
function writeit() {
var tbox = document.getElementById('a_tbox_1'), tbox2 = document.getElementById('a_tbox_2');
if (tbox.value && tbox2.value){
alert('product = ' + tbox.value + " :: price = " + tbox2.value);
// sendData('action.php?product=' + tbox.value + '&price=' + tbox2.value); (you can send your data via ajax)
tbox.value = '';
tbox2.value = '';
return false;
}
}
</script>
</head>
<body>
<form name="a_form">
Product name: <input type="text" id="a_tbox_1" name="a_tbox" value="" />
Price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</body>
</html>

Categories

Resources