Populating selected items at the right box of DualListBox - javascript

I am using this plugin to create a DualListBox for a selection field for a form in twitter-bootstrap-3. The form is created for edition purpose. So i am trying to add the previously selected values in the right-sided box. And also non-selected values are added manually.
To achieve this i have collected data from a JSON and make options string manually. Here is my code -
// Getting data related to the country of operations
$.getJSON(country_of_operation_json_url)
.done(function (data) {
var options = '';
for (var i = 0; i < data.length; i++) {
var a = 1;
for (var j = 0; j < port_ids.length; j++) {
// Appending "selected" attribute to the values which are already selected
if (port_ids[j] == data[i]["id"]) {
options += '<options value="' + data[i]["id"] + '" selected="selected">' + data[i]["port_iso"] + '</options>';
a = 0;
}
}
if (a == 1) {
options += '<options value="' + data[i]["id"] + '">' + data[i]["port_iso"] + '</options>';
}
}
// Appending the options at the selected box of the dual box
$("select#country-of-operation-edit").empty().append(options);
// Loading Country of operating dual-box field
$("#country-of-operation-edit").DualListBox();
});
Here is the html file that is generating select field -
<div class="form-group row">
<label class="col-sm-2 form-control-label">Country of operation</label>
<div class="col-sm-10">
<select class="form-control" multiple="multiple" data-json="false" id="country-of-operation-edit">
</select>
</div>
</div>
Problem is there are no values showing in the field. Here is the screenshot -
I couldn't find what am i doing wrong here. If this is not the way to populate the DualListbox with values, what are the other ways? Any help would be appreciated much. I am stuck here for hours.
EDIT-1: Here is my json - http://codebeautify.org/jsonviewer/cb7e1573
EDIT-2: For checking, you can take this values as selected -
port_ids = ["41", " 47", " 61"]

Change options to option man :)
for (var i = 0; i < data.length; i++) {
var a = 1;
for (var j = 0; j < port_ids.length; j++) {
// Appending "selected" attribute to the values which are already selected
if (port_ids[j] == data[i]["id"]) {
options += '<option value="' + data[i]["id"] + '" selected="selected">' + data[i]["port_iso"] + '</option>';
a = 0;
}
}
if (a == 1) {
options += '<option value="' + data[i]["id"] + '">' + data[i]["port_iso"] + '</option>';
}
}
https://jsfiddle.net/hh2zrt82/

Related

How to design UI for multiple selection in a drop down list?

I'm setting up a UI for my application. I would like to have some idea about your guy's experiences.
I need to have multiple selections from different sources.
Input (Sources): Companies, Department. Multiple companies, departments allowed.
Output: People who belong to selected items
For example, I can select company1, company2, and select department1, department2 from a dropdown list.
I select one by one property( Select company1, company2, then go to another dropdown to select department1,2...)
In the end, I have company1,2,3 checked, department 1,2,3 checked.
Then the result will tell me user1...n belong to the selected list above.
The problem is nothing if I have only a few company and department but if coming to be complicated if I have multiple (more than 6 companies and departments). I can't come up with any good UI design for this problem.
I expected the output of (selected(checked company1,2,3... + department1,2,3)) -> result person1,2,3 belong to checked items.
Try the following code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Select Company: </p>
<select name="companySelector" multiple>
</select>
<p>Select Department: </p>
<select name="departmentSelector" multiple>
</select>
<p>Persons: </p>
<ul id="persons">
</ul>
<script>
var companySelector = document.querySelector("[name='companySelector']");
var departmentSelector = document.querySelector("[name='departmentSelector']");
var persons = document.getElementById("persons");
var temp, temp2 = 0;
var database = {
company_1: {
c1_department1: ["c1d1person1", "c1d1person2", "c1d1person3", "c1d1person4"],
c1_department2: ["c1d2person1", "c1d2person2", "c1d2person3", "c1d2person4"],
c1_department3: ["c1d3person1", "c1d3person2", "c1d3person3", "c1d3person4"]
},
company_2: {
c2_department1: ["c2d1person1", "c2d1person2", "c2d1person3", "c2d1person4"],
c2_department2: ["c2d2person1", "c2d2person2", "c2d2person3", "c2d2person4"],
c2_department3: ["c2d3person1", "c2d3person2", "c2d3person3", "c2d3person4"]
},
company_3: {
c3_department1: ["c3d1person1", "c3d1person2", "c3d1person3", "c3d1person4"],
c3_department2: ["c3d2person1", "c3d2person2", "c3d2person3", "c3d2person4"],
c3_department3: ["c3d3person1", "c3d3person2", "c3d3person3", "c3d3person4"]
},
company_4: {
c4_department1: ["c4d1person1", "c4d1person2", "c4d1person3", "c4d1person4"],
c4_department2: ["c4d2person1", "c4d2person2", "c4d2person3", "c4d2person4"],
c4_department3: ["c4d3person1", "c4d3person2", "c4d3person3", "c4d3person4"]
},
company_5: {
c5_department1: ["c5d1person1", "c5d1person2", "c5d1person3", "c5d1person4"],
c5_department2: ["c5d2person1", "c5d2person2", "c5d2person3", "c5d2person4"],
c5_department3: ["c5d3person1", "c5d3person2", "c5d3person3", "c5d3person4"]
}
}
for (temp in database) {
companySelector.innerHTML += '<option value="' + temp + '">' + temp.replace(/_/g, " ") + '</option>';
}
companySelector.onchange = function() {
departmentSelector.innerHTML = "";
var selectedCompnies = document.querySelectorAll("[name='companySelector'] option:checked");
for (var i = 0; i < selectedCompnies.length; i++) {
for (temp2 in database[selectedCompnies[i].value]) {
departmentSelector.innerHTML += '<option value="' + temp2 + '" data-company="' + selectedCompnies[i].value + '">' + temp2.replace(/_/g, " ") + '</option>'
}
}
}
departmentSelector.onchange = function() {
persons.innerHTML = "";
var selectedDepartments = document.querySelectorAll("[name='departmentSelector'] option:checked");
for (var i = 0; i < selectedDepartments.length; i++) {
var temp3 = selectedDepartments[i].dataset.company;
var prsonsArray = database[temp3][selectedDepartments[i].value];
for (var x = 0; x < prsonsArray.length; x++) {
persons.innerHTML += "<li>" + prsonsArray[x] + "</li>";
}
}
}
</script>
</body>
</html>
DEMO

Using variable for an identifier name (using jquery selectors)

Believe me, I've been looking for examples online for hours. None of them seem to help.
I'm working on making a table. There are some columns with dropdown menu and I've assigned ID to each menu. Inside a loop, I'm trying to assign selected value for each dropdown menu.
var row$ = $('<tr/>');
function updateDataBodyGenerator(myList) {
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
var colIndex = 0;
for (var key in myList[i]) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
var severityDropDownMenu = "severityDropDownMenu" + i;
colIndex++;
switch (key) {
case "Test Case":
...
break;
case "Test Result":
...
break;
case "Severity":
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>'+
'<option value="Yellow">Yellow</option>';
row$.append($(severitySting));
//failed
//$("#severityDropDownMenu" + i).val(cellValue);
//failed
//var selectorString = "#" + severityDropDownMenu.toString();
//$(selectorString).val("Green");
//failed
//$("#" + severityDropDownMenu).val(cellValue);
//failed
//var selectorString = '#' + severityDropDownMenu;
//$(selectorString).val(cellValue);
//works
//$('#severityDropDownMenu0').val(cellValue);
...
As you can see in the comments, I've tried several approaches and only 1 worked which was $('#severityDropDownMenu0').val(cellValue); but that will only change 1 dropdown menu.
I appreciate your time and assistance.
Currently you're trying to use the # selector to target the dropdown by ID.
The issue here (as mentioned in the comments) is that this selector will search the DOM for the element, however because you've never added this element to the DOM, it doesn't exist on the page; the selector will return nothing.
What you can do instead is actually turn your severitySting into a jQuery element to set its value. Whenever you do append it, the value will be properly set. Like so:
var $severity = $(severitySting); //This is the <td>
var $dropdown = $severity.find("select") //This is the <select>
$dropdown.val(cellValue); //Set dropdown value
Demo:
var severityDropDownMenu = "mytest";
var cellValue = "Yellow";
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>' +
'<option value="Yellow">Yellow</option>';
var $severity = $(severitySting);
var $dropdown = $severity.find("select");
$dropdown.val(cellValue);
$("tr").append($severity);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>

jQuery: building a form dynamically from an array with a for loop

I have a jQuery function that receives id of div element and json array
function FormBuilder(selector,myList){
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
if(rowHash['id'] > 0 ){
$(selector).append('<form id="DialerInfo">');
for (var key in rowHash) {
$(selector).append(key +': <input type="text" name="' + key + '" value="' + rowHash[key] + '"><br/>');
}
$(selector).append('</form>');
}
}
}
And I expected this to build a proper form, i.e. all inputs should be between <form> and </form> tags. But I'm receiving something completely different:
First goes
<form id="DialerInfo"></form>
then below all input fields. Why are they outside the form tags? does jQuery close all tags automatically? how to prevent this behavior then?
DOM creation using jQuery doesn't work like string concatenation
You can create a form and append all the elements to it
function FormBuilder(selector, myList) {
var $form = $('<form id="DialerInfo"></form>').appendTo(selector);
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
if (rowHash['id'] > 0) {
for (var key in rowHash) {
$form.append(key + ': <input type="text" name="' + key + '" value="' + rowHash[key] + '"><br/>');
}
}
}
}
//use
$.each(arrayorJSON,function(KEY,VALUE){
//YOUR CODE HERE
})
//it is a jquery looper which accepts both array and json values and compatible with all browsers instead of for loop

Double for loop multidimensional array javascript

Im using ajax to return some json. Here is what the json looks like.
[{"optionValue":"11","optionDisplay":"Canon","preitem":`[{"preitemId":"15","preitemLabel":"Canon EF 100mm f\/2.8L Macro IS USM "},{"preitemId":"18","preitemLabel":"12412"},{"preitemId":"21","preitemLabel":"Sonydas1df Test"}]},{"optionValue":"20","optionDisplay":"Nikon","preitem":""},{"optionValue":"21","optionDisplay":"Audio & Aerial","preitem":""},{"optionValue":"23","optionDisplay":"Sony","preitem":[{"preitemId":"19","preitemLabel":"Sony 1412Test"},{"preitemId":"20","preitemLabel":"Son124124y Test"}]}]`
From what you can see here each option has a few preitems.
For example Canon has the preitems Canon EF 100mm, 12412 and Sonydas1df Test.
The goal is to output everything onto a html page.
So canon will have its own heading with its pre items under it.
Here is my code.
for (var i = 0; i < j.length; i++) {
for (var u = 0; u < j[i].preitem.length; u++) {
preitems += j[i].preitem[u].preitemLabel+'<br>';
}
options += '<div class="itemBlock"><b>'+ j[i].optionDisplay +'</b><input class="subcheckboxes" type="checkbox" id="checkit" value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</input><div class="" id="subcat' + j[i].optionValue + '">'+preitems+'</div></div>';
}
$("#subcat").html(options);
The main options (canon,etc) get displayed fine. However it does not output the only the pritems which are in the option. It outputs every single preitem in the whole json returned.
I want to only show the preitems which are in the option.
Thanks
You aren't resetting preitems
You probably want...
for (var i = 0; i < j.length; i++) {
preitems = '';
for (var u = 0; u < j[i].preitem.length; u++) {
...
When traversing multi-dimensional data objects, you need more specifically identify which actions happen how many times and where. Your plan of just scooping up all of the pre-items and dumping them for each item is fine if you reset the pre-items as rjdown suggests. I'd try something like this instead though:
for (var i = 0, lenj = j.length; i < lenj; i++) {
options += '<div class="itemBlock"><b>'+ j[i].optionDisplay +'</b><input class="subcheckboxes" type="checkbox" id="checkit" value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</input><div class="" id="subcat' + j[i].optionValue + '">';
for (var u = 0, lenu = j[i].preitem.length; u < lenu; u++) {
options += j[i].preitem[u].preitemLabel+'<br>';
}
options += '</div></div>';
}
$("#subcat").html(options);
I feel like this is much more readable and fixes your problem.

Creating a loop that populates a select tag

function buildOrder(data) {
var $fragment;
$fragment = $('<div/>');
for (var i = 0; i < data.length; i++) {
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$('#review-section').append($fragment);
}
I essentially want to add a tag with 50 options being dynamically created using a for loop. But I'm not sure what the syntax would be to add it to the <div class="row-container"/> I know in php I would just throw the loop in the middle and echo the options, however that doesnt work in javascript.
EDIT:
It would look like this:
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><select><option value="1">1</option> etc...</select><div class="clear"></div></div>');
You could pass a function to .append and do your loop there:
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
});
// returns a jQuery object with one div element (with children):
// <div>
// <select>
// <option value="1">1</option>
// ...
// </select>
// </div>
Mixed into your code it would be along the lines of:
var $fragment = $("<div>");
for (var i = 0; i < data.length; i++) {
var $container = $("<div>").addClass("row-container")
.appendTo($fragment);
$("<div>").addClass("row cupcake-row")
.text(data[i].name)
.appendTo($container);
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
}).appendTo($container);
$("<div>").addClass("clear")
.appendTo($container);
}
$("#review-section").append($fragment);
Try something like this
function buildOrder(data) {
var $fragment = $('<div></div>');
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$fragment.html(options.join("\n"));
$('#review-section').append($fragment);
}
According to your posted code:
function buildOrder(data) {
var $fragment;
$fragment = '<div><div class="row-container">';
for (var i = 0; i < data.length; i++) {
$fragment += '<div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div>';
}
$fragment += '</div></div>';
$('#review-section').append($fragment);
}
But in your posted code doesn't match with your post title, where you mentioned about select tag and in your code you're trying with div.
If you want to create a select, then something like:
function buildOrder(data) {
var $fragment;
$fragment = '<div class="row-container"><select>'; // taking select within your div
for (var i = 0; i < data.length; i++) {
// adding options to select
$fragment += '<option value="'+ data[i].name +'">' + data[i].name + '</option>';
}
$fragment += '</select></div>'; // end select and div
$('#review-section').append($fragment);
}

Categories

Resources