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

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>

Related

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.

loop through div with different elements

I generated elements and put them in MyDiv
$("#MyDiv").append('<input type=text class = "form-control" id=tb' + row.PropertyName + ' ' + 'value="Text' + row.PropertyName + '" />');
$("#MyDiv").append(' <input type="hidden" name="hid" value= "' + row.PropertyId + '">');
Now I need to extract the row.PropertyName and row.PropertyId
I need something like this:
var arrText = new Array();
$('#MyDiv > input[type = text]').each(function () {
var id = $(this).id.val();
var text = $(this).text.val();
var data = {
'id': id,
'text': text
}
I guess this is what you want.
$(function(){
var PropertyName = "pn1";
var PropertyId = "pn2";
$("#MyDiv").append('<input type="text" class = "form-control" id="tb"' + PropertyName + ' ' +
'value="Text' + PropertyName + '" />');
$("#MyDiv").append(' <input type="hidden" name="hid" value= "' + PropertyId + '">');
$('#MyDiv > input[type = "text"]').each(function(){
var id = $(this).val();
var text = $(this).next('input[type = "hidden"]').val();
var data = {
id: id,
text: text
}
alert(data.id + data.text);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="MyDiv"></div>
var arrText = [];
$('#MyDiv > input[type=text]').each(function () {
arrText.push({
'id': this.id,
'text': this.value
});
});
console.log( arrText );

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.

Validate dynamically generated input box with dynamic ID and name

I have a button that adds two input field onclick. Below is the code:
<button type="button" class="btn btn-warning btn-xs" id="additem">
Click here to add Items</button>
<form>
<div id="inputboxes"></div>
<input type="submit">
</form>
and JQuery is
var i = 1,
j = 1,
k = 1,
l = 1;
$("#additem").click(function () {
$("#inputboxes").append("<div class='form-group'><input type='text' id='iname" +
(j++) +
"' name='iname" +
(i++) +
"' class='form-control' placeholder='Enter Item Name' required='required'/></div> " +
"<div class='form-group'><input type='text' id='iprice" +
(k++) +
"' name='iprice" +
(l++) +
"' class='form-control' placeholder='Enter Item Price' required='required'/></div>");
})
How can i validate these dynamically added input boxes for empty and correct values on submitting the form?
You can do something like:
$('.form-group').each(function(){
var input = $(this).children('input');
if(input.val() == '' || input.val() == undefined){
// the errors you will give
}else{
if(input.attr('id').substring(0, 5) == 'iname'){
//function to validate your iname
}else if(input.attr('id').substring(0, 6) == 'iprice'){
//function to validate your iprice
}
}
});

javascript value does not add up

I try to make a count up function whenever there is pressed on a button (button is not in this code).
the result of the count up should be in the read only text field.
var html='';
var huidig = 0;
$('body').off('click', '[data-type=product]').on('click', '[data-type=product]', function(e)
{
e.preventDefault();
var price = $(this).attr('data-price');
var name = $(this).attr('data-name');
var id = $(this).attr('data-id');
if($('input[value='+id+']').length > 0)
{
var parent = $('input[value='+id+']').parent();
console.log("parent: " + parent);
var currentValue = parseFloat(parent.find('input[name^=product_amount]').val());
console.log("currentValue: " + currentValue);
currentValue++;
console.log("currentValue: " + currentValue);
parent.find('input[name^=product_amount]').val(parseFloat(currentValue));
console.log(parent.find('input[name^=product_amount]').val(parseFloat(currentValue)));
}
else
{
html+='<div class="row-fluid"><div class="span1"><input type="hidden" name="product[]" value="'+id+'"/><input type="text" readonly="readonly" name="product_amount[]" value="0" /></div> <div class="span7">'+name+'</div> <div class="span3 offset1">€'+price+'</div> </div>';
}
$('.bill').html(html);
amount = amount + parseFloat(price);
$('.total_bill').html(amount.toFixed(2));
});

Categories

Resources