Number of autocomplete search box is dynamic based an #AddButton. Autocomplete is working, but when I select the values, it doesnt rendered it properly. Please tell me where Am I missing.
Fiddle setup is at http://jsfiddle.net/jakenrush/kELm3/1/
Jquery code below
$(function() {
var projects = [
{
"label": "ajax",
"value": "1003",
"desc": "foriegn"
},
{
"label": "jquery",
"value": "1000",
"desc": "dd"
},
{
"label": "wordpress theme",
"value": "1000",
"desc": "h"
},
{
"label": "xml",
"value": "1000",
"desc": "j"
}];
$("#addButton");
var counter = 13;
$("#addButton").click(function() {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var roleInput = $('<input/>', {
type: 'text',
placeholder: 'Role',
name: 'Role' + counter,
id: 'project-description' + counter
});
var searchInput = $('<input/>', {
type: 'text',
placeholder: 'search',
name: 'search' + counter,
id: 'project' + counter
});
var hidd = $('<input/>', {
type: 'hidden',
name: 'searchhid' + counter,
id: 'project-id' + counter
});
newTextBoxDiv.append(roleInput).append(searchInput).append(hidd);
newTextBoxDiv.appendTo("#TextBoxesGroup");
$("#project" + counter).autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
$("#project" + counter).val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#project" + counter).val(ui.item.label);
$("#project-id" + counter).val(ui.item.value);
$("#project-description" + counter).val(ui.item.value);
$("#project-icon" + counter).attr("src", "images/" + ui.item.icon);
return false;
}
})
counter++;
});
});
html code :
<div id="project-label"></div>
<input type="hidden" id="project-id" />
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1" class="form-inline control-group">
</div>
</div>
<input type='button' value='Add' id='addButton' />
i have update your fiddle and it is working, the problem is with your counter variable which never been incremented, because you have place at end of script, but you have return statement above it.
your fiddle here http://jsfiddle.net/kELm3/6/
var counter = 0;
$("#addButton").click(function() {
counter++;
Related
I have a js file that is supposed to create a list of things with a delete button
The list gets created, and the first time that an element is deleted, it works fine. However, when I click on the delete button the second time, nothing happens. Why is this?
let sales = [{
"salesperson": "James D. Halpert",
"client": "Shake Shack",
"reams": 100
},
{
"salesperson": "Stanley Hudson",
"client": "Toast",
"reams": 400
},
{
"salesperson": "Michael G. Scott",
"client": "Computer Science Department",
"reams": 1000
},
];
function makeEntries(sales) {
$("#main").empty()
$.each(sales, function(index, value) {
var outer = $("<div class='main-page'>")
var start = $("<div class='start'></div>")
start.html(value["salesperson"])
var nameAttr = index;
var mid1 = $("<div class='mid-1'></div>")
mid1.html(value["client"])
var mid2 = $("<div class='mid-2'></div>")
mid2.html(value["reams"])
var ends1 = $("<div class='ends'>")
var ends = $("<button class='delete-button' id='" + nameAttr + "'></button></div>")
outer.append(start)
outer.append(mid1)
outer.append(mid2)
outer.append(ends1)
outer.append(ends)
$("#main").prepend(outer)
})
}
$(document).ready(function() {
makeEntries(sales)
console.log("does this get hoisted?")
console.log(sales)
$(".delete-button").click(function() {
names = Number(this.id)
sales.splice(names, 1)
makeEntries(sales)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="main"></div>
You need an updated index of the Object in Array.
The simplest way to achieve it is: sales.splice(sales.indexOf(item), 1);
Don't rebuild your entire elements again and again. Just remove that single one both from DOM and Array.
Regarding your code, here's a better way to code it using jQuery:
const sales = [{
salesperson: "James D. Halpert",
client: "Shake Shack",
reams: 100,
}, {
salesperson: "Stanley Hudson",
client: "Toast",
reams: 400,
}, {
salesperson: "Michael G. Scott",
client: "Computer Science Department",
reams: 1000,
}];
const $main = $("#main");
const makeEntries = (sales) => {
const outers = sales.map(item => {
const $outer = $("<div>", {class:"outer"});
const $person = $("<div>", {text: item.salesperson, class: "start", appendTo: $outer});
const $client = $("<div>", {text: item.client, class: "mid-1", appendTo: $outer});
const $reams = $("<div>", {text: item.reams, class: "mid-2", appendTo: $outer});
const $delete = $("<button>", {
text: "Delete",
class: "delete-button",
appendTo: $outer,
on: {
click() {
sales.splice(sales.indexOf(item), 1);
$outer.remove();
console.log(sales);
}
}
});
return $outer;
});
$main.empty().append(outers);
};
jQuery($ => {
makeEntries(sales);
});
#main { display: flex; }
.outer {flex: 1; padding: 10px; border: 1px solid #aaa;}
<main id="main"></main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You rewrite the list each time but only add the eventlistener the very first time
Instead delegate
$("#main").on("click",".delete-button", function() {
const names = Number(this.id);
sales.splice(names, 1);
makeEntries(sales)
})
let sales = [{
"salesperson": "James D. Halpert",
"client": "Shake Shack",
"reams": 100
},
{
"salesperson": "Stanley Hudson",
"client": "Toast",
"reams": 400
},
{
"salesperson": "Michael G. Scott",
"client": "Computer Science Department",
"reams": 1000
},
];
function makeEntries(sales) {
$("#main").empty()
$.each(sales, function(index, value) {
var outer = $("<div class='main-page'>")
var start = $("<div class='start'></div>")
start.html(value["salesperson"])
var nameAttr = index;
var mid1 = $("<div class='mid-1'></div>")
mid1.html(value["client"])
var mid2 = $("<div class='mid-2'></div>")
mid2.html(value["reams"])
var ends1 = $("<div class='ends'>")
var ends = $("<button class='delete-button' id='" + nameAttr + "'></button></div>")
outer.append(start)
outer.append(mid1)
outer.append(mid2)
outer.append(ends1)
outer.append(ends)
$("#main").prepend(outer)
})
}
$(document).ready(function() {
makeEntries(sales)
console.log("does this get hoisted?")
console.log(sales)
$("#main").on("click",".delete-button", function() {
const names = Number(this.id);
sales.splice(names, 1);
makeEntries(sales)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="main"></div>
Alternatively do not rewrite
$(".delete-button").on("click", function() {
const names = Number(this.id);
sales.splice(names, 1);
$(this).closest(".main-page").remove()
})
let sales = [{
"salesperson": "James D. Halpert",
"client": "Shake Shack",
"reams": 100
},
{
"salesperson": "Stanley Hudson",
"client": "Toast",
"reams": 400
},
{
"salesperson": "Michael G. Scott",
"client": "Computer Science Department",
"reams": 1000
},
];
function makeEntries(sales) {
$("#main").empty()
$.each(sales, function(index, value) {
var outer = $("<div class='main-page'>")
var start = $("<div class='start'></div>")
start.html(value["salesperson"])
var nameAttr = index;
var mid1 = $("<div class='mid-1'></div>")
mid1.html(value["client"])
var mid2 = $("<div class='mid-2'></div>")
mid2.html(value["reams"])
var ends1 = $("<div class='ends'>")
var ends = $("<button class='delete-button' id='" + nameAttr + "'></button></div>")
outer.append(start)
outer.append(mid1)
outer.append(mid2)
outer.append(ends1)
outer.append(ends)
$("#main").prepend(outer)
})
}
$(document).ready(function() {
makeEntries(sales)
console.log("does this get hoisted?")
console.log(sales)
$(".delete-button").on("click", function() {
const names = Number(this.id);
sales.splice(names, 1);
$(this).closest(".main-page").remove()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="main"></div>
I've been looking around and haven't been able to find an answer to this. I can get JQuery Easyautocomplete (http://easyautocomplete.com/) to work with Links, then get it to work with images, but I can't seem to get it to work with both. I'm new to JavaScript. I'm not sure what I'm doing wrong.
Here is my code...
var options = {
data: [
{
"text": "Home",
"website_link": "http://easyautocomplete.com/",
"icon": "http://lorempixel.com/100/50/transport/6"
},
{
"text": "Github",
"website_link": "https://github.com/pawelczak/EasyAutocomplete",
"icon": "http://lorempixel.com/100/50/transport/6"
}
],
getValue: "text",
template: {
type: "custom",
fields: {
website_link: "website_link"
},
method: function(value, item) {
return "<img src='" + item.icon + "' />" + value + "";
}
}
};
jQuery("#loan-officer-select").easyAutocomplete(options);
What am I doing wrong here? Any help would be greatly appreciated.
check if this is what you want
var options = {
data: [
{
"text": "Home",
"website_link": "http://easyautocomplete.com/",
"icon": "http://lorempixel.com/100/50/transport/6"
},
{
"text": "Github",
"website_link": "https://github.com/pawelczak/EasyAutocomplete",
"icon": "http://lorempixel.com/100/50/transport/6"
}
],
getValue: "text",
template: {
type: "custom",
method: function(value, item) {
return `<div>
<img src="${item.icon}" width="50px" height="50px" />
<a href=${item.website_link}> click me to go to ${value}</a>
</div>`;
}
}
};
jQuery("#loan-officer-select").easyAutocomplete(options);
Expected Result: If row.updated_status equals to '1', will disable this two field 'UOM' & 'allocated_qty', else remaining.
Issues: Failed to disable the both fields.
"columns": [
{
"field": "id", "title": "Id", "visible": false
},
{
"field": "product__name", "title": "Product"
},
{
"field": "uom", "title": "UOM", "formatter": "uomFormatter"
},
{
"field": "allocated_qty", "title": "Alloc. Qty",
"editable": {"mode": "inline"}
}],
"rowStyle": "rowStyle"
In javascript:
For field 'UOM':
function uomFormatter(value, row, index){
var uom_list = row.uom_list;
var product_id = row.product_id;
if(product_id != null && product_id != ''){
if(row.updated_status == 1){
if(uom_list != null){
var html = '<select class="form-control defaultpicker uom_list" data-row-index="' + index + '" disabled>';
...the following codes...
}else{
...the following codes...
}
}
else{
if(uom_list != null){
var html = '<select class="form-control defaultpicker uom_list" data-width="120px" data-row-index="' + index + '">';
}
}
For Field 'allocated_qty':
function rowStyle(row, index) {
if(row.updated_status == 1){
$('#bootstrap-table').bootstrapTable('disabledColumn', 'allocated_qty');
}
}
It should be disabled, not disable:
var html = '<select class="form-control defaultpicker uom_list" data-row-index="' + index + '" disabled>';
Here is the image of current working operation I am using jquery auto complete . But my problem is when i type item1 it shows item1 as suggestion. And i want to show when i type item1 is should be show zzz1 inside suggestion box.
My code is here.
<input name="jobCat" id="jobCat" value="" type="text" placeholder="Search category by keyword"/>
<script>
$(function() {
var datasource = [
{ "label": "item1", "value": "zzz1", "id": 1 },
{ "label": "item2", "value": "zzz2", "id": 2 },
{ "label": "item3", "value": "zzz3", "id": 3 }];
$("#jobCat").autocomplete({
source: datasource,
select: function (event, ui) { }
});
</script>
Edit, I found something usefull in the documentation... For having the values in the suggestions, instead of the labels.
var datasource = [
{ "label": "item1", "value": "zzz1", "id": 1 },
{ "label": "item2", "value": "zzz2", "id": 2 },
{ "label": "item3", "value": "zzz3", "id": 3 }];
$("#jobCat").autocomplete({
source: datasource,
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.value + " - ID: " + item.id + "</div>" )
.appendTo( ul );
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<input name="jobCat" id="jobCat" value="" type="text" placeholder="Search category by keyword"/>
I am trying to build a 'form builder' where you can add sub-fields to fields, and sub-fields to those sub-fields, etc. I have that part working and the output html I have pasted here on pastebin
Which looks like:
I need to get the data into this format:
var form_structure = {
iGA2cXN3XXdmr1F: {
title: "Field 1",
help: "",
placeholder: "",
type: "multi-select",
options: {"123QWE": "Opt 1", "ASDZXC": "Opt 2", "ASDQWE": "Opt 3"},
subfields: {
m8r32skADKsQwNt: {
title: "Field 1.1",
help: "",
placeholder: "",
type: "text",
options: []
},
m8r32skADKsQwNt: {
title: "Field 1.2",
help: "",
placeholder: "",
type: "text",
options: []
},
m8r32skADKsQwNt: {
title: "Field 1.3",
help: "",
placeholder: "",
type: "text",
options: [],
subfields: {
m8r32skADKsQwNt: {
title: "Field 1.3.1",
help: "",
placeholder: "",
type: "text",
options: []
}
}
}
}
},
aBvXXN3XXdmr1F: {
title: "Field 2",
help: "",
placeholder: "",
type: "multi-select",
options: {"123QWE": "Opt 1", "ASDZXC": "Opt 2", "ASDQWE": "Opt 3"},
subfields: {
m8r32skADKsQwNt: {
title: "Field 2.1",
help: "",
placeholder: "",
type: "text",
options: []
}
}
}
};
I have tried (sorry for the bad formatting):
function buildRequestStringData(form) {
var select = form.find('select'),
input = form.find('input'),
options_arr = [],
obj = {},
requestString = '{';
for (var i = 0; i < select.length; i++) {
if(typeof $(select[i]).data('parentid') != 'undefined') {
// has parent
if($(select[i]).data('parentid') != $(select[i]).data('mainid')) {
requestString += '"' + $(input[i]).data('mainid') + '":"' + JSON.stringify(buildRequestStringData()) + '",';
}
} else {
// does not have parent
requestString += '"' + $(select[i]).attr('name') + '": "' +$(select[i]).val() + '",';
}
}
// if (select.length > 0) {
// requestString = requestString.substring(0, requestString.length - 1);
// }
for (var i = 0; i < input.length; i++) {
// if ($(input[i]).attr('type') !== 'checkbox') {
requestString += '"' + $(input[i]).attr('name') + '":"' + $(input[i]).val() + '",';
// } else {
// if ($(input[i]).attr('checked')) {
// requestString += '"' + $(input[i]).attr('name') +'":"' + $(input[i]).val() +'",';
// }
// }
}
if (input.length > 0) {
requestString = requestString.substring(0, requestString.length - 1);
}
requestString += '}]';
return requestString;
}
The best way I have been able to be close to this is on this fiddle - but that only allows me to put the id down, and does not format it into the format I need.
What is the best way to do this?
I think you're on the right track. See if you can nest your HTML in the same structure you want for your JSON, then when harvesting the details for each item, walk up the DOM tree grabbing each parent's id until you get to the form, and then create / append to the nested JSON object the data you find. If this isn't descriptive enough, I'll mod the answer to include html and js examples.