Looping dynamic data in JavaScript append - javascript

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.

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>

Asp.net Core MVC Dynamically add Select List via JS

I am trying to provide a view where people will be able to create a list of categories and sub categories. Therefore I need to allow users to dynamically add Rows.
Each Row will allow user to add a category and then if they wish a Sub Category. For the first row I am able to use asp-items attributes to bind to a SelectList in my ViewBag, however when I add a new row via JS I cannot do it, I have tried 2 methods JS (both shown in the code):
1 - Storing the SelectList in a variable and looping through it
2 - Setting the asp-items to the SelectList
Does anyone know how I can populate my newly added rows? Also how would I bind the enetred in data to my Model; would it have to be done in the controller?
The code is as follows:
<script type="text/javascript">
$(document).ready(function () {
var categories = "#ViewBag.Categories";
var catOptions = '';
for (var i = 0; i < categories; i++) {
catOptions = catOptions + '<option value="' + categories[i].CategoryId + '">' + categories[i].Name + '</option>'
}
$(document).on("click", "#btnAddCat", function () {
var newCat =''+
'<tr class="categorieRows">' +
'<td colspan="2">' +
'<select>' +
catOptions +
'</select>' +
'</td>' +
'<td>' +
'<button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>' +
'</td>' +
'</tr>';
$('#categoryTable').append(newCat);
});
$(document).on("click", "#btnAddSubCat", function () {
var newSubCat = '' +
'<tr class="categorieRows">' +
'<td></td>' +
'<td>' +
'<select asp-items="ViewBag.SubCategories"></select>' +
'</td>' +
'<td></td>' +
'</tr>';
$('#categoryTable').append(newSubCat);
});
});
</script>
#model IEnumerable<Categories>
#{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Surveys</h4>
<hr />
<table class="table table-striped" id="categoryTable">
<thead>
<tr>
<th>
Category
</th>
<th>
Sub Categories
</th>
<th>
<button type="button" id="btnAddCat" class="btn btn-xs btn-primary classAdd">Add Category</button>
</th>
</tr>
</thead>
<tbody>
<tr class="categorieRows">
<td colspan="2">
<select asp-items="ViewBag.Categories"></select>
</td>
<td>
<button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>
</td>
</tr>
</tbody>
</table>
<div>
<a asp-action="Index">Back to List</a>
</div>
Used Ajax calls to retrieve Categories data:
<script>
$(document).ready(function () {
$(document).on("change", "#selectCategroy", function () {
var subCat = this;
$.ajax({
url: "ReturnJsonSubCategories/?categoryId=" + $(subCat).val(),
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function (result) {
var categories = "";
$(result).each(function () {
categories = categories + '<option value="' + this.subCategoryId + '">' + this.name + '</option>'
});
var subCateList = $("#selectSubCategroy");
subCateList.empty();
subCateList.append(categories);
},
error: function (data) {
return "Error";
}
});
});
});
</script>
With the server side code looking like:
public JsonResult ReturnJsonSubCategories(int categoryId)
{
var jsonData = _context.SubCategories.Where(x => x.CategoryId == categoryId).ToList();
return Json(jsonData);
}
Similar with the last answer but a bit shorter
$(function () {
$('#CategoryId').change(function () {
$('#SubCategoryId').empty();
var url = '#Url.Content("~/")' + "api/CategoryApi/ListSubCategories";
$.getJSON(url, { categoryId: $('#CategoryId').val() })
.done(function (data) {
var subcategories = "";
$(data).each(function () {
subcategories += '<option value="' + this.CategoryId + '">' + this.Title + '</option>'
});
$('#SubCategoryId').append(subcategories);
})
});
});
and on server side
[HttpGet]
[Route("ListSubCategories")]
public IActionResult ListSubCategories(int categoryId)
{
var subCategories = _categorySvc.ListSubCategories(categoryId);
return Ok(subCategories);
}

Add button inside a new div created dynamically with a button using Javascript

I'm building kind of a form.
Trying to insert a button into a new div created dynamically with javascript. Apparently, the code isn't working because the new div created is a local variable inside the function that created it.
Without the additional button, the code is working fine.
The idea is that the additional button add extra inputs of the original type of input of the Form.
Any advice of how could I accomplish this?
HTML:
<div id="dynamicInputs">
</div>
Título de la pregunta: <input name="qName" type="text"><br>
Tipo: <select name="inputSelect">
<option value="text">Respuesta corta</option>
<option value="radio">Selección múltiple</option>
<option value="checkbox">Checkboxes</option>
<option value="textarea">Desarrollo</option>
</select><br>
<input type="button" class="btn btn-default btn-sm" value="Agregar pregunta" onclick="addAllInputs('dynamicInputs', document.myForm.qName.value, document.myForm.inputSelect.value)">
Javascript:
//agegar pregunta en formulario
var counterDynInput = 0;
function addAllInputs(divName, qName, inputType){
var newDiv = document.createElement('div');
var newDivName = "";
newDivName = "divInputs_" + (counterDynInput + 1);
newDiv.setAttribute("id", newDivName);
newDiv.innerHTML =
(counterDynInput + 1)
+ ". "
+ inputLabel(qName)
+ "<br>"
+ inputFields(inputType)
+ "<hr>";
addButtonToDiv(newDivName);
counterDynInput++;
document.getElementById(divName).appendChild(newDiv);
}
function inputLabel(qName){
var putStr = "";
putStr = "<input type='text' name='qLabel' value='" + qName + "' placeholder='Título de la pregunta...'>";
return putStr;
}
function inputFields(inputType){
var putStr = "";
putStr = "<input type='" + inputType + "' name='myInputs[]'><br>";
return putStr;
}
function addButtonToDiv(newDivName){
var btn = document.createElement('BUTTON');
var div = document.getElementById(newDivName);
div.appendChild(btn);
}

jquery edit post doesn't work

I am trying to make a edit post using jquery. But my code doesn't worked.
It need to work when i click the edit button then the editMarkUp wil be put in messageB1 but it doesn't work.
Anyone can help me here what i am missing and what is the solution?
This is DEMO from jsfiddle.net
Js
$(document).ready(function() {
$("body").on("click", ".editBtn", function() {
var ID = $(this).attr("id");
var currentMessage = $("#messageB" + ID + " .postInfo").html();
var editMarkUp = '<textarea rows="5" cols="80" id="txtmessage_' + ID + '">' + currentMessage + '</textarea><button name="ok" ">Save</button><button name="cancel">Cancel</button>';
$("#messageB" + ID + " .postInfo").html(editMarkUp);
});
});
HTML
<div class="container">
<div class="postAr" id="messageB1">
<div class="postInfo">
fdasfads fasd fadsf adsf adsf adsf asd fasd f dfsa
</div>
<div class="editBtn" id="1">Edit</div>
</div>
</div>
You're not defining editobj variable anywhere in your code, and I guess you probably meant .postInfo instead:
$(document).ready(function() {
$("body").on("click", ".editBtn", function() {
var ID = $(this).attr("id");
$('.postInfo').prop('disabled', 'true');
var currentMessage = $("#messageB" + ID + " .postInfo").html();
var editMarkUp = '<textarea rows="5" cols="80" id="txtmessage_' + ID + '">' + currentMessage + '</textarea><button name="ok" ">Save</button><button name="cancel">Cancel</button>';
$("#messageB" + ID + " .postInfo").html(editMarkUp);
});
});
MODIFIED DEMO

generate JSON data based on input fields

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.

Categories

Resources