Bootstrap Dual Listbox problems while populate via JavaScript - javascript

I have some problem while using Bootstrap Dual Listbox (http://www.virtuosoft.eu/code/bootstrap-duallistbox/). It is not working as expected when the ListBox is populated via java Script.What I mean with not working is the list is not populated properly and the transferring selected items from both list box is not as what as it should work. Somehow when the list is populated by hard coded, it is working well.
This is the part where everything working fine :
<div class="row-fluid">
<div class="container">
<select multiple="multiple" size="10" name="SelectItem" class="eItems" id="SelectItem">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3" selected="selected">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
<option value="option6" selected="selected">Option 6</option>
<option value="option7">Option 7</option>
<option value="option8">Option 8</option>
</select>
<script type="text/javascript">
var demo2 = $('.eItems').bootstrapDualListbox({
nonselectedlistlabel: 'Non-selected',
selectedlistlabel: 'Selected',
preserveselectiononmove: 'moved',
moveonselect: false,
bootstrap2compatible : true
});
</script>
</div>
</div>
but when populate using JavaScript, it is populated but the functions is not functioning well :
The data collector from Controller :
<script type="text/javascript">
function ProductChange() {
$.getJSON("/WEBAPP/MasterData/GetItems", null, function (data) {
var items;
$.each(data, function (i, item) {
items += "<option value=" + item.Value + ">" + item.Key + "</option>";
});
$("#SelectItem").html(items);
})
}
</script>
The list box populating here :
<div class="row-fluid">
<div class="row-fluid">
<div class="container">
<select id="SelectProduct"></select>
</div>
</div>
<div class="row-fluid">
<div class="container">
<select multiple="multiple" size="10" name="SelectItem" class="eItems" id="SelectItem"></select>
<script type="text/javascript">
var demo2 = $('.eItems').bootstrapDualListbox({
nonselectedlistlabel: 'Non-selected',
selectedlistlabel: 'Selected',
preserveselectiononmove: 'moved',
moveonselect: false,
bootstrap2compatible : true
});
$(function () {
$("#SelectProduct").change(function () {
ProductChange();
});
});
</script>
</div>
</div>
</div>
The controller :
[HttpGet]
public JsonResult GetItems(int productID = 0)
{
try
{
var items =
from item in dbItem.items.ToList()
join p in dbItem.Productitems.ToList()
on item.itemID equals p.itemID
where item.Language.LanguageCode.Trim() == repLanguage
where p.ProductID == productID
orderby item.DisplaySequence
select new { Key = item.itemDescription, Value = item.itemID };
if (items.Count() == 0)
{
items = from item in dbItem.items.ToList()
where item.Language.LanguageCode.Trim() == repLanguage
orderby item.DisplaySequence
select new { Key = item.itemDescription, Value = item.itemID };
}
return Json(items, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
Is it because the java script is reloaded every time the trigger action takes place?
Apologize if the explanation is not so clear and just let me know if u need more information.
Thanks a lot

I cannot populate the list box properly by calling and a populate function directly as normal drop down. I changed the populate code as below
<select multiple="multiple" size="10" name="SelectItem" class="eItems" id="SelectItem"></select>
<script type="text/javascript">
var demo2 = $('.eItems').bootstrapDualListbox({
nonselectedlistlabel: 'Non-selected',
selectedlistlabel: 'Selected',
preserveselectiononmove: 'moved',
moveonselect: false,
bootstrap2compatible: true
});
$(function () {
$("#SelectProduct").change(function () {
$('#SelectItem').empty();
demo2.trigger('bootstrapduallistbox.refresh');
$.getJSON("/WEBAPP/MasterData/GetItems", { productID: $("#SelectProduct").val() }, function (data) {
var items;
$.each(data, function (i, item) {
demo2.append("<option value=" + item.Value + ">" + item.Key + "</option>");
});
demo2.trigger('bootstrapduallistbox.refresh');
})
});
});
</script>
From my understanding, the list items are re-populate using original code. Correct me if I am wrong.

You should try something like this:
demo2.trigger('bootstrapDualListbox.refresh' , true);
This works form me!

For me, bootstrapDualListbox is case sensitive - bootstrapduallistbox did not work. I wanted to post this in case any body else has this issue.

Related

Select Box with Search Option

i have a select dropdown. i need a search in my options. i use select2 dropdown on it but the select not showing the search and the design is completely changed.
Here is my code :
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<select class="single" name="icons" onchange="TypeCheck(this);">
<option value="0">Pick an icon ...</option>
<option value="1">glass</option>
<option value="2">door</option>
<option value="3">Furniture</option>
</select>
function matchCustom(params, data) {
if ($.trim(params.term) === '') {
return data;
}
if (typeof data.text === 'undefined') {
return null;
}
if (data.text.indexOf(params.term) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += ' (matched)';
return modifiedData;
}
return null;
}
$(document).ready(function() {
$('.single').select2({
placeholder: "Select Country",
allowClear: true,
matcher: matchCustom
});
});
You can use select2 default search option rather you want to implement your own search block of code.
<select class="yourClassName" name="states[]" multiple="multiple">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>
and you can use select2 default jquery code
$(document).ready(function() {
$('.yourClassName').select2();
});
you can visit this link for more details https://select2.org/getting-started/basic-usage

Set <select> element depending on another <select> element

I need a select element's options to change depending on the value of another.
<select id="first">
<option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
<option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
<option value="thisChanges">soDoesThis</option>
<option value="thisToo">andThis</option>
</select>
<script>
$("#first").on("change", function() {
<pseudo>
if #first == "1"
#second = {"this", "that", "the other"}
else if #first == "2"
#second = {"more", "even more", "yet another", "still more"}
</pseudo>
}
</script>
This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.
Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.
JSFiddle
HTML:
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button>
Click me
</button>
JS:
var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
alert('click');
var sel = $('#sel');
alert('1');
sel.empty();
alert('2');
for (i = 0, i < list.length; i+2) {
$('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
}
alert('3');
});
I think you requirement similiar to the cascading dropdownlist, if i have understood correctly.
Ex jquery code:
$(document).ready(function () {
$("#state").prop("disabled", true);
$("#country").change(function () {
if ($("#country").val() != "Please select") {
var options = {};
options.url = "/home/getstates";
options.type = "POST";
options.data = JSON.stringify({ country: $("#country").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (states) {
$("#state").empty();
for (var i = 0; i < states.length; i++) {
$("#state").append("<option>" + states[i] + "</option>");
}
$("#state").prop("disabled", false);
};
options.error = function () { alert("Error retrieving states!"); };
$.ajax(options);
}
else {
$("#state").empty();
$("#state").prop("disabled", true);
}
});
});
Kindly refer this good article for the complete code:
http://www.binaryintellect.net/articles/b58fde6b-415e-454d-985b-d5dc4ad2fca8.aspx
Hope it will helps
Thanks
Karthik
Since you specified jQuery, I'll give you a jQuery answer! Grab the value and the text from the selected option, and append a new one to the select:
$(document).on('change', '#two', function() {
var option_to_add = $(this).find("option:selected").text();
var number_of_options = $('#two option').length
$('#one').append($('<option>', {
value: number_of_options,
text: option_to_add
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
<option value="cash">Cash</option>
<option value="money">Money</option>
</select>
<select id="two">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
<option value="op1">Should be option 1: <a id="option1"></a></option>
</select> Should also be option 1:
<div id="option1"></div>
Based on your comments and changes to your post, if you just want to replace the options in a select element using a dummy array (or array of arrays,) you can do so the following way see code comments for details:
// dummy data array of arrays
var list = [
[11, "Eleven"],
[12, "Twelve"],
[13, "Thirteen"]
];
// click the button, replace the select contents
$('#btn').on('click', function() {
// build an array of option objects from an array of arrays
// see below
var opt_array = build_opt_array(list);
$('#sel').empty();
// add the new options
$(opt_array).each(function(index) {
$('#sel').append(opt_array[index]);
});
});
// helper function
// builds a new array of option html objects from
// an array of arrays
function build_opt_array(items) {
var opt_array = [];
$(items).each(function(index) {
var new_option = $('<option>', {
value: items[index][0],
text: items[index][1]
});
opt_array.push(new_option);
});
return opt_array;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button id="btn">
Click me
</button>
To get the text found in the first Select field, use the .text() function after using find(":selected") on your desired select field.
$("#two").focus(function() {
document.getElementById("option1").innerHTML = $("#one").find(":selected").text();
});

Converting a JavaScript function to jQuery - Select option list

This is literally the first time I've worked with jQuery and I've read the entire chapter in my textbook but am finding a hard time wrapping my head around it. I'm attempting to convert a JavaScript function (a simple option selection drop-down list) to jQuery. I've attempted a few lines of code that I've gotten from the book or from w3schools and api.query but to no avail. I'll try to make this quick and simple, I just cannot understand jQuery for some reason.
What I've attempted usually doesn't work. Before my option list works fine, then I tried experimenting but I didn't get too far.
I also apolgize for the vagueness of the question, I'd appreciate any help!
Here's something I've tried:
$(document).ready( function () {
var c = ???
if ($(c...
calc.js and index.html below it
function selectedCountry() {
var c = document.getElementById("countryChooser").value;
var message;
if (c == "nothing") { //if they selected the default option, error pops up.
alert("Please select a country.");
} else if (c == "usa") {
message = "United States of America";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else if (c == "canada") {
message = "Canada";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else {
message = "Mexico";
document.getElementById("count").innerHTML = "Your country is: " + message;
}
}
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser" onchange="selectedCountry()">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Through jQuery you can do it like below:-
Example:-
$(document).ready(function(){
$('#countryChooser').change(function(){ // on change of select
if($(this).val()!=='nothing'){ // if selected value is some country
$('#count').html("Your country is: "+$("#countryChooser option:selected").text()); // get country name and add it to paragraph
}else{
$('#count').html("");
alert('Please select a country.'); // alert for selecting a country
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Get an element by id:
var c = $('#countryChooser');
Get the value of this input/select element
var value = c.val();
Set the html of an element using the element id
$('#count').html('some html');
or set the text (html is not parsed this way)
$('#count').text('some html');
You can also handle the events with jQuery
$(document).ready(function() {
$('#countryChooser').on('change', function(event) {
// this is the DOM element with the id 'countryChooser'
// same as the native: var val = this.value;
var val = $(this).val();
// ...
});
});
I have bind the onchange() event of your select list inside the jQuery(document).ready() method. check this out-
// Updated code--
$(document).ready(function (){
$('#countryChooser').on('change' ,function () {
if(this.selectedIndex){
$('#count').html("Your country is: "+ this.options[this.selectedIndex].text);
}else{
$('#count').html("");
alert("Please select a country.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
$('#countryChooser').change(function(){
var selectedCountry = $(this).val();
if(selectedCountry == 'nothing'){
console.log('Select A country');
}
else{
$('#count').html('Your country is '+$('#countryChooser option:selected').text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--JavaSript link -->
<select name="countrylist" id="countryChooser" >
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Please check the code might help you out
thanks

Event listener inside a function

I have a select on my page:
<select id='cat'>
<option value='a'>A</option>
<option value='b'>B</option>
<option value='all'>all</option>
</select>
With a javascript function that handles which options have to be displayed:
function funcName(aList) {
// populates the options for the select tag
$("#cat").on("change", function(){
// some computation;
});
// uses aList to update some div data
}
What I'm trying to do is if the selected option is all, I have to display everything in aList, otherwise based on the selected option I have to display only the related options. Is my usage of onchange event correct?
Initially I thought of making aList global, but after some reading on globals in JS, I got to know it is not a very good practice.
Thanks in advance!
UPDATE: aList contains some string values.
$(function () {
$("#ddl").change(function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
var assignedRoleId = new Array();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
if(selectedValue== "all")
{
$("#ddl option").each(function()
{
if(this.value=="all")
{
assignedRoleId.push();
}
else
{
assignedRoleId.push(this.value);
assignedRoleId.push(" ");
$("#selected").html(assignedRoleId);
}
});
}
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Select something:
<select id="ddl">
<option value="">select one</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="all">all</option>
</select>
<div id="selected">
</div>

option is still visible in select after remove()

Hi all I have two select fields, on select field first if user select option value one or two then in select field of second all options are visible but if it select option two in first then option two want to remove from select id second. Following is my code:
<script type="text/javascript">
var index3,str;
</script>
<select id="first" onchange="chk();">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<select id="second">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<script type="text/javascript">
function chk()
{
index3 = document.getElementById("first");
str= index3.options[index3.selectedIndex].value;
alert("str:"+str);
if (str=="two")
{
$("#second option[value='two']").remove();
}
else
{
if ( $("#second option[value='two']").length == 0 )
{
$("#second").append('<option value="two">two</option>');
}
}
}
</script>
In fiddle it works fine here, But on mobile problem is: If I select option two from select id second, and then select option value two in first select id, then also option two is visible in second select id, if I click on second select id then only it removes. But in jsFiddle it works perfect. Any suggestion will be appreciated, Thanks in advance.
Here i have done complete bin for above issue. please go through demo link.
Demo http://codebins.com/bin/4ldqp7p
HTML
<select id="first">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
<select id="second">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
jQuery
$(function() {
$("#first").change(function() {
var optVal = $(this).val().trim();
if (optVal == "two") {
$("#second").find("option[value=" + optVal + "]").remove();
} else {
if ($("#second").find("option[value=two]").length <= 0) {
$("<option value=\"two\">two</option>").insertAfter($("#second").find("option[value='one']"));
}
}
});
});
Demo http://codebins.com/bin/4ldqp7p
check this Edit
$('#first').change(function() {
$("#second option[value='" + $(this).val() + "']").remove();
});
Your code looks a bit odd overall. If your intention is to remove the item from 'second' if it is selected in 'first', try this update: http://jsfiddle.net/NWbXt/58/
$(function() {
var first = $('#first'),
second = $('#second'),
removed;
first.change(function() {
var selected = first.val();
second.append(removed); //.. add back old option
removed = second.find('option[value="' + first.val() + '"]').remove();
}).trigger('change');
});​

Categories

Resources