I have a table consisting of rows with inputs. Rows are cloned and added dynamically whenever an autocomplete value is selected in the first input of each row.
Each time a new row is added, I want to apply .autocomplete to the first input. Normally this is easy, as seen in this jsfiddle.
I have a somewhat different approach, where I'm changing the ID of the input where a selection is made. I think that's why I'm unable to apply autocomplete to the cloned line, but I can't figure out why??
Here's the code in question (jsfiddle here)
// Make new line. (I have additional code for improved functionality in my production code)
function newLine() {
// Send the line to backend for updating mysql. Data returned is
// the mysql id for the "autocompleted" line. Emulated here by a random number
var randomNumber = Math.floor(Math.random() * 100) + 1
$("#idLine0").attr("id", "idLine" + randomNumber)
//Make clone of the last line
var row = $("#test tr:last").clone(true);
//Give the ID "idLine0" (which I've reserved for the bottom line) to the new line.
$(".AC", row).val("").attr({
"id": "idLine0",
"placeholder": "Autocomplete does not work here"
})
row.insertAfter("#test tr:last");
//$(".AC").autocomplete("destroy")
applyAutocomplete("#idLine0")
}
function applyAutocomplete(id) {
$(id).autocomplete({
source: [{
value: "ActionScript",
type: "type 1",
comment: "none"
}, {
value: "TestScript",
type: "type 2",
comment: "lots"
}, {
value: "AlphaScript",
type: "type 3",
comment: "even more"
}, {
value: "BravoScript",
type: "type 4",
comment: "lots and lots"
}, {
value: "CharlieScript",
type: "type 5",
comment: "comment"
}, {
value: "DeltaScript",
type: "type 6",
comment: "no comment"
}],
minLength: 1,
open: function (event, ui) {
var header = "<li style='border-bottom: 1px solid black; padding-top: 10px;'>" +
"<a style='font-size:1em;font-weight:bold; display:inline-block;'>" +
"<span class='ui-span'>Product</span><span class='ui-span'>Type</span>" +
"<span class='ui-span'>Comment</span></a></li>"
$("ul.ui-autocomplete[style*='block']").find("li:first").before(header);
},
select: function (event, ui) {
console.log($(this.element))
newLine()
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a><span class='ui-span'>" + item.value +
"</span><span class='ui-span'>" + item.type +
"</span><span class='ui-span' style='width:250px;'>" + item.comment + "</span></a>")
.appendTo(ul);
};
}
After working on your problem a bit, i've seen this line:
var row = $("#test tr:last").clone(true);
And this line is the problem, more specifically the "true" bool parametter.
As you can see on jquery .clone docs:
A Boolean indicating whether event handlers should be copied along with the elements...
This basically means that everything on that element will be clonned, handdlers, triggers, etc... Every time you use your first input element, you will be able to see the autocomplete working and cloning lines.
So, change this:
var row = $("#test tr:last").clone(true);
To this:
var row = $("#test tr:last").clone();
I've made a more "clean" version of your jsfiddle: http://jsfiddle.net/JuanHB/8uhNq/3/
Related
image of the issue
When I try to remove the specified data from this dropdownlist I am still left with a selectable white space where the item use to be, this is the case even if I try to specify by id, I attached an image to demonstrate the issue. Any suggestions would be greatly appreciated
{
contentElement.append(
$("<p>All boardrooms are available at this time.</p><br/>"),
$("<div style='margin-top:10%' />").attr("id", "selector").dxSelectBox({
placeholder: "Choose the boardroom you would like to book",
//
valueExpr: "id",
displayExpr: function(item) {
if(item && item.name != "Training Room" && item.name != "Ada Lovelace" && item.name != "Alexander G Bell")
return item.name + " " + '('+item.seats+ " "+'seats'+')';
},
onOpened: function(e){
e.component.option("dataSource", availBoardrooms)
e.component.getDataSource().reload();
},
onValueChanged: function(e){
$("[name='boardroom']").val(e.value);
$("[name='boardroom']").change();
window.name = quickSelectDate;
}
})
)
}
I presume you are getting invalid data from your data source, you can add a slight validation where you are adding the dropdown options
onValueChanged: function(e){
if(e.value.length)
{
// Add dropdown option
}
}
i'm build a web-app chat and i make a upload system on it,
first i make a image input[type="file"]
then a record button [upload as wav]
example:
anyway i I am viewing files with if(condition) ,
example :
if (data.file == 'audio') {
$('<audio style="display:block;width:250px;" controls src="' + data.message + '"></audio>').appendTo($('.messages ul'));
}else if (data.file == 'image'){
$(''<img class="imageChat" ' +
'src="' + filterXSS(data.message) + '"' +
'href="' + filterXSS(data.message) + '"' + '>'
+).appendTo($('.messages ul'));
}
but what i need is to AUTO-detect file type and create the element based on the type of it ?
Update:
example:
showFile('assets/this-is-img.php?a=b') // will return an $('img') element
i know how to get the file type but i need to pass the file type to script and it will return the preview element like img for photos , iframe for PDFs,audio for audios,etc
is this possible?
thanks in advance :)
Here is a very basic example. The core function here is makeElement(), it takes some basic data passed to it as a object and create a jQuery Object based on the HTML Element.
The heavy lifting is done by fileToElem() which takes some info about the files and can based on the type of file take some conditional actions. If it sees a specific file and has a data template for it.
$(function() {
var files = [{
file: "audio",
message: "assets/this-is-img.php?a=b"
},
{
file: "image",
message: "assets/this-is-img.php?a=b"
}
];
function makeElement(d, t) {
var el = $("<" + d.nodeName + ">", d.attr).prop(d.prop);
if (t != undefined) {
el.appendTo(t);
}
return el;
}
function fileToElem(data, target) {
var item;
switch (data.file) {
case "audio":
item = makeElement({
nodeName: "audio",
attr: {
class: "audioChat",
style: "display:block;width:250px;",
src: data.message
},
prop: {
controls: true
}
}, target);
break;
case "image":
item = makeElement({
nodeName: "img",
attr: {
class: "imageChat",
src: data.message
},
prop: {}
}, target);
break;
case "video":
item = makeElement({
nodeName: "video",
attr: {
class: "videoChat",
src: data.message
},
prop: {
controls: true
}
}, target);
break;
case "pdf":
item = makeElement({
nodeName: "a",
attr: {
class: "pdfChat",
href: data.message,
target: "_BLANK"
},
prop: {}
}, target);
break;
}
// Do other things with 'item' if needed here
}
$.each(files, function(i, data) {
var listItem = $("<li>").data("date", new Date().toString()).appendTo($(".messages ul"));
fileToElem(data, listItem);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="messages">
<ul></ul>
</div>
You can keep adding more conditions to your switch() based on the file types you expect. If you're not familar with switch() it's a complex if handler.
The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.
See More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Hope that helps.
Assuming that the user can only upload one file at a time, you can get the filelist from the input[type=file] document.getElementById("Id of the input").files[0]. It returns a file object which has a type property. Hope this helps
I have a multidimensional array of stores and states, which makes a json as follows:
<?php
$list[$store][$state] = $city;
echo json_encode ($list);
{"store 1": {"state x": "city 1", "state y": "city 2"}, "store 2": {"state z": "city 3"}}
?>
I need to create a select that changes the second select according to what was chosen, using the data of the array in question.
Something like this http://www.daviferreira.com/blog/exemplos/cidades/index.php
How can I handle this data in php for javascript?
And how can I separate them to use them in each select?
I've already tried:
var list = JSON.parse ("<? php echo json_encode($list)?>");
But it did not work :(
EDIT The structure of the selects should look like this.
{"store 1": {"state x": "city 1", "state y": "city 2"}, "store 2": {"state z": "city 3"}}
First select
Store 1
Store 2
if store 1 selected
Second select
State x
State y
if store 2 selected
Second select
State z
Something like that
You can simply do this using jQuery:
$(document).ready(function(){
var list = <?= json_encode($list); ?>;
var storeSelect = $("<select></select>");
storeSelect.attr('id', 'storeSelect');
for(var item in list)
{
storeSelect.append('<option value="' + item + '">' + item + '</option>');
}
$('#theForm').append(storeSelect);
var storeStates = $("<select></select>");
storeStates.attr('id', 'storeState');
$('#theForm').append(storeStates);
$('#storeSelect').change(function ()
{
var storeName = $(this).val();
for(var item in list[storeName])
{
storeStates.html('<option value="' + item + '">' + item + '</option>');
}
});
$('#storeSelect').change();
});
It simply uses loops to create the select menu. And uses the onChange event to manipulate the values.
Here's how to do it using jQuery. If you're using plain JS, converting it is an exercise for the reader.
var list = <?php echo json_encode($list); ?>;
$.each(list, function(store) {
$("#store_menu").append($("<option>", {
value: store,
text: store
}));
});
$("#store_menu").change(function() {
var store = $(this).val();
$("#state_menu").empty();
$.each(list[store], function(state) {
$("#state_menu").append($("<option>", {
value: state,
text: state
}));
});
});
I want to get the json data from a file which has a nested JSON objects, like this.
{
"userId": "1",
"data": {
"id": 1,
"name" : "Lorem Ipsum",
"value" : "Salut Dolor"
}
}
And once I get it I want to create a select object with the Id as the displayed text and append it to a div.
Once the select object is created, I also want to automatically open the select options when the page gets loaded.
Once a value is selected from there, I want to display the name that is present in the json for that id.
I'm able to fetch only the UserId from this code, how will i meet the requirements?
$.ajax({
url: 'obj.json',
dataType: 'JSON',
success: function (data) {
var items = [];
$.each(data, function (key, value) {
items.push('<option id="' + key + '">' + value + '</option>');
});
$('<select/>', {
class: 'intrest-list',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function () {
alert("There was a problem");
}
}
});
what is this good for? do you want to fetch more then 1 user in the future?
you could so something like this:
//user.json
[{id:1,name:'xxxx'},...]
....
for(var i = 0;i<data.length;i++){
items.push('<option id="' + data[i].id + '">' + data[i].name+'</option>');
}
...
or in your case, you can access it directly with:
data.data.id
data.data.name
data.data.value
would get you the right values
Solved it myself. Although i came up with an alternative to display the list of select elements as:
<select name="" id="details" size="2"></select>
also created a container to post the values of the JSON object selected from the select box:
<div id="container"></div>
and the jQuery part where the magic happens goes like this:
$.getJSON('obj.json', function(obj) {
$.each(obj, function(key, value) {
$("#details").append('<option>'+ value.name +'</option>')
});
$( "select" ).change(function () {
var value = $( "select option:selected").val();
$.each(obj, function(key, val) {
if (val.name == value) {
$("#container").html(val.value);
}
});
});
});
This pretty much made the select box as a list of items and the value.name selected in it makes the value.value visible in the div container.
I have the following JSON:
var questions = {
section: {
"1": question: {
"1": {
"id" : "1a",
"title": "This is question1a"
},
"2": {
"id" : "1b",
"title": "This is question2a"
}
},
"2": question: {
"1": {
"id" : "2a",
"title": "This is question1a"
},
"2": {
"id" : "2b",
"title": "This is question2a"
}
}
}
};
NOTE: JSON changed based on the answers below to support the question better as the original JSON was badly formatted and how it works with the for loop below.
The full JSON will have 8 sections and each section will contain 15 questions.
The idea is that the JS code will read what section to pull out and then one by one pull out the questions from the list. On first load it will pull out the first question and then when the user clicks on of the buttons either option A or B it will then load in the next question until all questions have been pulled and then do a callback.
When the button in the appended list item is clicked it will then add it to the list below called responses with the answer the user gave as a span tag.
This is what I have so far:
function loadQuestion( $section ) {
$.getJSON('questions.json', function (data) {
for (var i = 0; i < data.length; i++) {
var item = data[i];
if (item === $section) {
$('#questions').append('<li id="' + item.section.questions.question.id + '">' + item.section.questions.question.title + ' <button class="btn" data-response="a">A</button><button class="btn" data-response="b">B</button></li>');
}
}
});
}
function addResponse( $id, $title, $response ) {
$('#responses').append('<li id="'+$id+'">'+$title+' <span>'+$response+'</span></li>');
}
$(document).ready(function() {
// should load the first question from the passed section
loadQuestion( $('.section').data('section') );
// add the response to the list and then load in the next question
$('button.btn').live('click', function() {
$id = $(this).parents('li').attr('id');
$title = $(this).parents('li').html();
$response = $(this).data('response');
addResponse( $id, $title, $response );
loadQuestion ( $('.section').data('section') );
});
});
and the HTML for the page (each page is separate HTML page):
<div class="section" data-section="1">
<ul id="questions"></ul>
<ul id="responses"></ul>
</div>
I've become stuck and confused by how to get only the first question from a section and then load in each question consecutively for that section until all have been called and then do a callback to show the section has been completed.
Thanks
Do not have multiple id's in html called "section."
Do not have multiple keys in your JSON on the same level called "section". Keys in JSON on the same level should be unique just as if you are thinking about a key-value hash system. Then you'll actually be able to find the keys. Duplicate JSON keys on the same level is not valid.
One solution can be section1, section2, etc. instead of just section. Don't rely on data-section attribute in your HTML - it's still not good if you have "section" as the duplicate html id's and as duplicate JSON keys.
If you have only one section id in HTML DOM, then in your JSON you must also have just one thing called "section" e.g.:
var whatever = {
"section" : {
"1": {
"question" : {
"1" : {
"id" : "1a",
"title" : "question1a"
},
"2" : {
"id" : "2a",
"title" : "question2a"
}
}
},
"2": {
"question" : {
"1" : {
"id" : "1a",
"title" : "aquestion1a"
},
"2" : {
"id" : "2a",
"title" : "aquestion2a"
}
}
}
}
}
console.log(whatever.section[1].question[1].title); //"question1a"
To get question, do something like this:
function loadQuestions(mySectionNum) {
$.getJSON('whatever.json', function(data){
var layeriwant = data.section[mySectionNum].question;
$.each(layeriwant, function(question, qMeta) {
var desired = '<div id="question-' +
qMeta.id +
'"' +
'>' +
'</div>';
$("#section").append(desired);
var quest = $("#question-" + qMeta.id);
quest.append('<div class="title">' + qMeta.title + '</div>');
//and so on for question content, answer choices, etc.
});
});
}
then something like this to actually get the questions:
function newQuestion(){
var myHTMLSecNum = $("#section").attr('data-section');
loadQuestions(myHTMLSecNum);
}
newQuestion();
//below is an example, to remove and then append new question:
$('#whatevernextbutton').on('click',function(){
var tmp = parseInt($("#section").attr('data-section'));
tmp++;
$("#section").attr('data-section', tmp);
$("#section").find('*').remove();
newQuestion();
});
Technically your getJSON function always retrieves the same data. Your code never compares the id given to the id you're extracting.
Your getJSON should look something like:
function loadQuestion( $section ) {
for (var i = 0; i < questions.section.length; i++) {
var item = questions.section[i];
if (item.id === $section) {
for (var j = 0; j < item.questions.length; j++) {
$('#questions').append('<li id="' +
item.questions[i].id + '">' +
item.questions[i].title +
' <button class="btn" data-response="a">A</button><button class="btn" data-response="b">B</button></li>'
);
}
}
}
}
Modify your JSON to:
var questions = {
section: [{
id: 1,
questions: [{
id: "1a",
title: "This is question1a"
},{
id: "2a",
title: "This is question2a"
}]},{
id: 2,
questions: [{
id: "1a",
title: "This is question1a"
},{
id: "2a"
title: "This is question2a"
}]
}]
};
Edit: your first parameter of getJSON is the URL of the JSON returning service.
You don't need getJSON at all if your JSON is already defined on the client. I have modified the code above.