Converting list box to checkboxes - javascript

I am having one dropdown and when I select one item from that dropdown a list appears corresponding to that item comes from a json in the list box. But I don't want to have list box, I want to have checkboxes so that I can select multiple items. I'm trying to convert this list box into checkboxes but not getting the intended result.. Please help!!!
This is my javascript code
$('#dropdown1').change(function () {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
// var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
var optionHtml = '';
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
return false;
}
});
});
This is my html code
<form name="myform" id="myForm">
<select id="dropdown1"></select>
<select id="listbox", multiple></select>
<br>
</form>
More js code
$(document).ready(function() {
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}

After filling the dropdown with what you required, when u select an option the data u get instead of making a <select> make a <div>. Then fill the div with:
<input type="checkbox" name="yourDataName" value="yourDataName">yourDataName</input>
Check this demo on jsfiddle : https://jsfiddle.net/jagrati16/s566ss58/
This is just a demo. Hope it solves your problem
Change this:
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
var optionHtml = '';
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
return false;
}
});
to this:
var check = '';
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
check += '<input type="checkbox" name="'+attr+'" value="' + attr + '">' + value[attr] + '<br>';
}
$('#listbox').append(check);
}
});

Related

how Allow duplicates selection in select2 with tag editor

Im add duplicates tags with item in Select2 input?
but dont allow add new tag input .
when new tag dont allow.
You have to choose item from dropdown.
this my pic
dont allow tag
test
to add dropdown
this my code:
$("#AutoMessage").select2({
width: '100%',
dir: "rtl",
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term + $("#AutoMessage").val(),
newOption: true
}
},
templateResult: formatResultData
});
function formatResultData(data) {
if (!data.id) {
var $result = $("<span></span>");
$result.text(data.text);
return $result;
// $("#AutoMessage").append('<option value="' + e.params.data.text + '">' + e.params.data.text + '</option>');
};
if (data.element.selected) return;
return data.text;
};
$("#AutoMessage").on("select2:select", function (e) {
var data = e.params.data;
//alert("as");
//if ((e.currentTarget).find("option[value='" + data.id + "']").length == 0)
// return;
$("#AutoMessage").append('<option value="' + e.params.data.text + '">' + e.params.data.text + '</option>');
});
$("#AutoMessage").on("select2:unselect", function (e) {
var data = e.params.data;
//if ($(e.currentTarget).find("option[value='" + data.id + "']").length > 0)
// return;
e.params.data.element.remove();
});

Where to place my code to select first option of <select> with jQuery?

I need to select first option of select with jQuery. My code is a bit complex and can't figure out how to make it work. Thanks
Html:
'sortingHtml': '<select id="bc-sf-filter-top-sorting-select">{{sortingItems}}</select>'
Javascript:
BCSfFilter.prototype.buildFilterSorting = function() {
if (bcSfFilterTemplate.hasOwnProperty('sortingHtml')) {
jQ(this.selector.topSorting).html('');
var sortingArr = this.getSortingList();
if (sortingArr) {
// Build content
var sortingItemsHtml = '';
for (var k in sortingArr) {
sortingItemsHtml += '<option value="' + k +'">' + sortingArr[k] + '</option>';
}
sortingItemsHtml = '<option disabled="disabled" selected>Sort by</option>' + sortingItemsHtml
var html = bcSfFilterTemplate.sortingHtml.replace(/{{sortingItems}}/g, sortingItemsHtml);
jQ(this.selector.topSorting).html(html);
// Set current value
jQ(this.selector.topSorting + ' select').val(this.queryParams.sort);
}
}
};
Code to select the first option:
$("#bc-sf-filter-top-sorting-select").val($("#bc-sf-filter-top-sorting-select option:first").val());
$("#bc-sf-filter-top-sorting-select option:first").prop("selected", true);

JQuery Dynamic Objects load selectors

I've a form when I click one radio button to load a subform.
Ok this work perfectly, but has 3 selectors that I need external data when only this subform loaded.
So, I did in this way:
$(document).on('focus', '#reemb', function () {
$.getJSON("/banks.php", function (json) {
$('#bank').empty();
$.each(json, function (i, obj) {
$('#bank').append($('<option>').text(obj.name).attr('value', obj.code));
});
});
$.getJSON('/statecity.json', function (data) {
var items = [];
var options = '<option value="">State</option>';
$.each(data, function (key, val) {
options += '<option value="' + val.name + '">' + val.name + '</option>';
});
$("#state").html(options);
$("#state").change(function () {
var options_city = '';
var str = "";
$("#state option:selected").each(function () {
str += $(this).text();
});
$.each(data, function (key, val) {
if (val.name == str) {
$.each(val.city, function (key_city, val_city) {
options_city += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#city ").html(options_city);
}).change();
});
});
This work fine, but everytime that I need to change one date the selectors clear and load again.
I tried to add tag onload to start the function to load selectors in this subform, but don't works. Also tried change events to .on, but also don't work.
How I need to do this?
Thx!!
Not knowing what #reemb is, I would empty the relevant sub selects:
If the container holding the selects is ALSO emptied, you need to delegate all even handlers of objects inside too - like $(document).on("change","#bank", function() {
$(document).on('click', '#reemb', function() {
$.getJSON("/banks.php", function(json) {
$('#bank').empty();
$.each(json, function(i, obj) {
$('#bank').append($('<option>').text(obj.name).attr('value', obj.code)).change();
});
});
$('#bank').on("change", function() {
$('#city').empty();
$.getJSON('/statecity.json', function(data) {
var items = [];
var options = '<option value="">State</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.name + '">' + val.name + '</option>';
});
$("#state").html(options).change(); // if needed
});
$("#state").on("change", function() {
var options_city = '';
var str = "";
$("#state option:selected").each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.name == str) {
$.each(val.city, function(key_city, val_city) {
options_city += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#city ").html(options_city).change(); // if needed
});
});
});

How to Add Handler Id to Options value loaded by jQuery

I am trying to load a select options by using jQuery from 3 arrays to one select list on click which so far works fine for me at here
But I have an issue here.if you look at the values I have same value on three list so I have to upgrade them by adding also the id of the clicked button to the value some thing like this:
<option value="regi1NNN">NNN</option>
instead of
<option value="NNN">NNN</option>
depends on what button clicked.
Here is my code:
$(document).ready(function () {
var opt1 = ["AAAA", "BBBB", "NNN", "JJJJJ"];
var opt2 = ["KKKK", "FFFF", "NNN", "TTTTT"];
var opt3 = ["MMM", "NNN", "OOOO", "PPPPP"];
$("#regi1").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt1.length; i++) {
option += '<option value="' + opt1[i] + '">' + opt1[i] + '</option>';
}
$('#items').append(option);
});
$("#regi2").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt2.length; i++) {
option += '<option value="' + opt2[i] + '">' + opt2[i] + '</option>';
}
$('#items').append(option);
});
$("#regi3").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt3.length; i++) {
option += '<option value="' + opt3[i] + '">' + opt3[i] + '</option>';
}
$('#items').append(option);
});
});
When you create your options like so:
option += '<option value="' + opt1[i] + '">' + opt1[i] + '</option>';
Simply add the id of the clicked element as a prefix:
option += '<option value="' + this.id + opt1[i] + '">' + opt1[i] + '</option>';
Working example: http://jsfiddle.net/g8euy/ This way when you combine all your click handlers into one function (which you should, since you have three functions that do the same thing) you'll be all set.
UPDATE: I rewrote your code to only use a single funciton. Example here: http://jsfiddle.net/n2tBC/1/
I added a class and a data attribute to your buttons:
<div class="container">
<div class="well">
<div class="btn-group">
<button type="button" class="btn btn-default listy" id="regi1" data-vals="opt1">Left</button>
<button type="button" class="btn btn-default listy" id="regi2" data-vals="opt2">Middle</button>
<button type="button" class="btn btn-default listy" id="regi3" data-vals="opt3">Right</button>
</div>
<br />
<br />
<select id="items"></select>
</div>
</div>
And then the script combines your value lists into an object, and there's a single function that gets the data based on the data-val of the clicked button:
$(document).ready(function () {
var myVals = {
opt1: ["AAAA", "BBBB", "NNN", "JJJJJ"],
opt2: ["KKKK", "FFFF", "NNN", "TTTTT"],
opt3: ["MMM", "NNN", "OOOO", "PPPPP"]
}
$(".listy").click(function () {
$('#items option').remove();
var clickedButton = $(this);
var valueList = myVals[clickedButton.data('vals')];
var option = '';
for (i = 0; i < valueList.length; i++) {
option += '<option value="' + this.id + valueList[i] + '">' + valueList[i] + '</option>';
}
$('#items').append(option);
});
});
Now when you add more buttons, you don't add more code.

Making an onchange event also run to pageload

I have some onchange events setup in jQuery which are used to populate a select dropdown boxbased on what is selected in another select dropdown.
I need these to also run on page load that so that results are returned based on what the first select box is at on page load (otherwise I end up with an empty select box). I've had a look around the internets but can't find anything that fits exactly what I want to do
My jQuery code is
$(function(){
//Get Contacts for Company
$("select#ContactCompanyId").change(function(){
var url = "contactList/" + $(this).val() + "";
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
$.each(j, function(key, value){
options += '<option value="' + key + '">' + value + '</option>';
})
$("select#QuoteContactId").html(options);
})
})
//Get list of product Categories
$("select#ProductCategory").live('change', function(){
var url = "productList/" + $(this).val() + "";
var id = $(this).attr('name');
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
options += '<option value="0">None</option>';
$.each(j, function(key, value){
options += '<option value="' + key + '">' + value + '</option>';
})
$("select#QuoteItem" + id + "product_id").html(options);
})
})
//Function to add product data into the form
$(".Product").live('change', function(){
var url = "productData/" + $(this).val() + "";
var id = $(this).attr('title');
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
$("#QuoteItem" + id + "name").val(j['Product']['name']);
$("#QuoteItem" + id + "price").val(j['Product']['price']);
$("#QuoteItem" + id + "description").val(j['Product']['description']);
})
})
})
Thanks in advance for your help
You can just trigger the event just after binding it with .trigger() like this:
$("select#ContactCompanyId").change(function(){
var url = "contactList/" + $(this).val() + "";
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
$.each(j, function(key, value){
options += '<option value="' + key + '">' + value + '</option>';
})
$("select#QuoteContactId").html(options);
});
}).trigger('change');
$(document).ready(function() {
$('#your_select_id').change();
});
This fires the change event for your select, with its current value. Its the equivlent of a user selecting the current value, and it will fire any events attached to it that would fire from an onchange event.

Categories