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
I have 3 radio buttons like:
<input type="radio" name="editList" value="Proveedor">Proveedor
<input type="radio" name="editList" value="Usuario">Usuario
<input type="radio" name="editList" value="Sucursal">Sucursal
I want to load my dropdown depending of radio selected
Dropdown
<select id="lstProveedor" class="form-control select2 select2-accessible" aria-hidden="true">
</select>
JS:
<script type="text/javascript">
$(function () {
var items = "";
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
</script>
As you can see I populate dropdown with one #Url.Action but I want to change it and .each data depending of radio button selected.
For example:
if proveedor radio button is selected load this part of js:
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
if Sucursal is selected load this part of js
$.getJSON("#Url.Action("GetSucursal", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Sucursal+ "</option>";
});
$("#lstProveedor").html(items);
How can I achieve it?. Regards
Update:
As answer of Ramon I do:
<script type="text/javascript">
$(function getJsonProveedores() {
var items = "";
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
$(function getJsonUnidades() {
var items = "";
$.getJSON("#Url.Action("GetUnidades", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
});
$(function getJsonUsuarios() {
var items = "";
$.getJSON("#Url.Action("GetUsuario", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
$('input[type=radio][name=editList]').change(function () {
if (this.value == 'Proveedor') {
getJsonProveedores();
}
else if (this.value == 'Sucursal') {
getJsonUnidades();
}
else if (this.value == 'Usuario') {
getJsonUsuarios();
}
});
});
</script>
But in Chrome console I get two errors:
Uncaught ReferenceError: getJsonProveedores is not defined Uncaught
ReferenceError: getJsonUnidades is not defined
I created an html file and it is working like this:
function getJsonProveedores() {
var items = "";
console.log('teste proveedor');
};
function getJsonUnidades() {
var items = "";
console.log('unidades');
};
function getJsonUsuarios() {
console.log('usuarios');
};
$(function() {
$('input[type=radio][name=editList]').change(function() {
if (this.value == 'Proveedor') {
getJsonProveedores();
} else if (this.value == 'Usuario') {
getJsonUsuarios();
} else if (this.value == 'Sucursal') {
getJsonUnidades();
}
});
});
I am populating two dependent dropdown lists using an ajax call. The problem is that if I change my selection(master dropdown list) more than once, all the dependent options(the earlier values) show up in the dependent dropdown list. Here's my ajax call
$.ajax({
type: "GET",
url: "index.php?r=orders/on-select",
data: {myVar: myVar},
success: function (data) {
var jdata = JSON.parse(data);
var cluster = jdata.Clusters;
var sites = jdata.Sites;
$.each(cluster, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
$('[ref="region"]').find('[name="list box element"]').append(option);
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
$('[ref="region"]').find('.selectBoxInput').find('.dropDownBox').append(opnGrpval);
});
$.each(sites, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
$('[ref="sites"]').find('[name="list box element"]').append(option);
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
$('[ref="sites"]').find('.selectBoxInput').find('.dropDownBox').append(opnGrpval);
});
}
});
Change append to html then .
$.ajax({
type: "GET",
url: "index.php?r=orders/on-select",
data: {myVar: myVar},
success: function (data) {
var jdata = JSON.parse(data);
var cluster = jdata.Clusters;
var sites = jdata.Sites;
var regionOptions = '';
var dropdownOptions = ''
$.each(cluster, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
regionOptions += option;
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
dropdownOptions += opnGrpval;
});
$('[ref="region"]').find('[name="list box element"]').html(listoptions); $('[ref="region"]').find('.selectBoxInput').find('.dropDownBox').html(dropdownOptions);
var sitesOptions = '';
var sitesDropdownOptions = '';
$.each(sites, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
sitesOptions += option;
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
sitesDropdownOptions += opnGrpval;
});
$('[ref="sites"]').find('[name="list box element"]').html(sitesOptions); $('[ref="sites"]').find('.selectBoxInput').find('.dropDownBox').html(sitesDropdownOptions);
}
});
I have a dropdown-menu.
JS
$.each(responseData.assignments, function(i, v) {
var assessmentId = v.assessmentId;
var assessmentType = v.assessmentType;
// Auto Populate the dropdown-menu
$('#student-dd').append('<option value="' + assessmentId + '">' + assessmentType + '</option>');
});
Goal
I want to show only one HOMEWORK/COURSE_BENCHMARK, doesn't matter how many of them are there. How can I check for uniqueness in Javascript ?
You can check for length of option element with same text in that dropdown using filter function before appending new:
$.each(responseData.assignments, function(i, v) {
var assessmentId = v.assessmentId;
var assessmentType = v.assessmentType;
// Auto Populate the dropdown-menu
var optionwithsametext = $('#student-dd option').filter(function(){
return $(this).text() == assessmentType ;
})
if(!optionwithsametext.length)
$('#student-dd').append('<option value="' + assessmentId + '">' + assessmentType + '</option>');
});
There is more than one way to do this. This is an another example;
var assignments = {};
$.each(responseData.assignments, function(i, v) {
assignments[v.assessmentType] = v.assessmentId;
});
$.each(assignments, function(i, v) {
// Auto Populate the dropdown-menu
$('#student-dd').append('<option value="' + v + '">' + i + '</option>');
});
Attempting to populate a drop down menu with JSON data but cant quite figure out what I am doing wrong.
JSON Data
{"dropdownValue1":"1x1","dropdownDisplay1":"1x1","dropdownValue2":"1x2","dropdownDisplay2":"1x2","dropdownValue3":"1x3","dropdownDisplay3":"1x3","dropdownValue4":"1x4","dropdownDisplay4":"1x4","dropdownValue5":"1x5","dropdownDisplay5":"1x5","dropdownValue6":"1x6","dropdownDisplay6":"1x6"}
Java/HTML
<script type="application/javascript">
$(function(){
$("select#size").change(function(){
$.getJSON("getDropdown",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + i + '">' + j[i] + '</option>';
}
$("select#size").append(options);
})
})
}) </script>
<div class="input select orderBoxContent">
<select name="size" id="size">
</select>
</div>
Actual JSON request
function getDropdown()
{
var people_no = $('#howmanypeople').val();
$.getJSON("../../getdata.php?getDropdown=yes&people_no="+people_no, function(response) {
$('#getDropdown').html(response.getDropdown);
});
}
Cheers
Ryan
Your JSON is an object but you are itterating it like an array.
var i;
for (i in j) {
if (j.hasOwnProperty(i)) {
// i = 'dropdownValue1'
// j[i] = "1x1"
// but the order is unknown
options += '<option value="' + j[i] + '">' + j[i] + '</option>';
}
}
$(function(){
$("select#size").change(function(){
$.getJSON("getDropdown",{id: $(this).val(), ajax: 'true'}, function(j){
var i;
for (i in j) {
if (j.hasOwnProperty(i)) {
// i = 'dropdownValue1'
// j[i] = "1x1"
// but the order is unknown
options += '<option value="' + j[i] + '">' + j[i] + '</option>';
}
}
$("select#size").append(options);
})
})
})
I've created this fiddle, it allows the user to click on either art or video, dynamically populating the the second listbox with the list associated with those selections. There are two buttons, one to add the selection to the box, the other which removes the selection.
What I would like to do is prevent the user from adding some that has already been added. The value of the options will all be Guids. Bonus points if you can modify the fiddle to use Guid instead of ints.
I've tried this:
$.each($("#SelectBox2 option:selected"), function (i, ob) {
if (i == $(this).val()) {
} else {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
I would like to enable the user to remove the selected items from the list.
Thanks,
UPDATE Just letting you guys know what the solution is that I came up with, I got the bonus points because i added GUID to it in a really smart way :) fiddle, I also tidied up the html to make it look nice and neat.
MAJOR UPDATE A massive thanks to everyone who has contributed to this question, I have taken on board everyones comments and fiddles and have generated this >> fiddle <<
I think you would want to do something like this: Check if value is in select list with JQuery.
Modifying your code to something like this should work:
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var exists = false;
$('#SelectedItems option').each(function(){
if (this.value == optionVal) {
exists = true;
}
});
if(!exists) {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
Removing selected items would look like this:
$('#remove').click(function () {
$("#SelectedItems option:selected").remove();
});
If you want to dynamically add and delete rows seamlessly try this way
http://jsfiddle.net/WX4Nw/
Adding a pointer to the selecteditems list as a data attrib to the root item key will help you control so that you can easily manage add/remove.
Snippet from fiddle:-
$('#SelectBox').change(function () {
var str = "",
inHTML = "",
key = $('#SelectBox').val(),
items;
items = $(this).val() == 'art' ? artItems : vidItems;
$.each(items, function (i, ob) {
if($('#SelectedItems option[value="' + i + '"][data-key="' + key + '"]').length == 0)
inHTML += '<option value="' + i + '" data-key="' + key + '">' + ob + '</option>';
});
$("#SelectBox2").empty().append(inHTML);
});
$('#add').click(function () {
var itemsToAdd = [];
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var key = $(this).data('key');
if ($('#SelectedItems option[value="' + optionVal + '"][data-key="' + key + '"]').length == 0) {
itemsToAdd.push($(this).removeAttr('selected'));
}
});
$("#SelectedItems").append(itemsToAdd);
});
Try:
$(function () {
var artItems = ["Art 1", "Art 2", "Art 3", "Art 4", "Art 5", "Art 6"];
var vidItems = ["Video 1", "Video 2", "Video 3", "Video 4", "Video 5", "Video 6"];
$('#SelectBox').change(function () {
var str = "",
inHTML = "",
items;
items = $(this).val() == 'art' ? artItems : vidItems;
$.each(items, function (i, ob) {
inHTML += '<option value="' + i + '">' + ob + '</option>';
});
$("#SelectBox2").empty().append(inHTML);
});
$('#SelectBox2').change(function () {
$("#selectedValues").text($(this).val() + ';' + $("#SelectBox").val());
$('#hidden1').val($(this).val());
});
$('#add').click(function () {
inHTML = "";
$("#SelectBox2 option:selected").each(function () {
if ($("#SelectedItems option[value=" + $(this).val() + "]").length == 0) {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
$("#SelectedItems").append(inHTML);
});
$('#remove').click(function () {
$('#SelectedItems option:selected').remove();
});
});
Fiddle here
Ok to fix your add function just add the following if condition::
if($("#SelectedItems option:contains("+$(this).text()+")").length<=0)
inHTML += '<option value="' + $(this).text() + '">' + $(this).text() + '</option>';
to remove items::
$('#remove').click(function () {
$("#SelectedItems option:selected").each(function () {
$(this).remove();
});
});
here is the example after i updated it jsfiddle
Have a look at this solution:- Using the data attribute to keep track of the items parent list selector and avoiding a loop with the help of this selector and data attribute.
http://jsfiddle.net/pramodsankar007/rMpBv/
$('#add').click(function () {
var itemsToAdd = [];
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var key = $(this).data('key');
if($('#SelectedItems option[value="' + optionVal + '"][data-key="' + key +'"]').length == 0)
{
itemsToAdd.push($(this).removeAttr('selected').clone(true));
}
});
$("#SelectedItems").append(itemsToAdd);
});
});
SEE THE LINK
write if condition as
if($("#SelectedItems option:contains("+$(this).val()+")").length<=0)
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
Then add
$('#remove').click(function(){
$('#SelectedItems :selected').each(function(i, selected) {
$(this).remove();
});
});
Get existing list of options, check if those you're adding already exist, if not, add them:
http://jsfiddle.net/bZXs4/
$('#add').click(function () {
var inHTML = "";
var $opts = $('#SelectedItems').find('option');
$("#SelectBox2 option:selected").each(function () {
var allowItemToBeAdded = true;
var selectedVal = $(this).val();
$opts.each(function(index, element){
if($(this).val() === selectedVal){
allowItemToBeAdded = false;
}
});
if(allowItemToBeAdded){
inHTML += '<option value="' + selectedVal + '">' + $(this).text() + '</option>';
}
});
if(inHTML !== ''){
$("#SelectedItems").append(inHTML);
}
});
try this if you want to prevent the user from adding an option that already exists
$("#SelectBox2 option:selected").each(function () {
if( $("#SelectedItems option[value='"+$(this).val()+"']").length <=0)
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
http://jsfiddle.net/j2ctG/8/
Updated the fiddle for remove also.
Really Clean and Simple (works great and only a few lines):
$("#icon_move_right").click(function(){
$("#available_groups option:selected").each(function(){
available_group = $(this).val();
$("#assigned_groups").append("<option value='" + available_group + "'>" + available_group + "</option>");
});
$("#available_groups option:selected").remove()
});
$("#icon_move_left").click(function(){
$("#assigned_groups option:selected").each(function(){
assigned_group = $(this).val();
$("#available_groups").append("<option value='" + assigned_group + "'>" + assigned_group + "</option>");
});
$("#assigned_groups option:selected").remove()
});
$("#icon_move_right_all").click(function(){
$("#available_groups option").each(function(){
available_group = $(this).val();
$("#assigned_groups").append("<option value='" + available_group + "'>" + available_group + "</option>");
});
$("#available_groups option").remove()
});
$("#icon_move_left_all").click(function(){
$("#assigned_groups option").each(function(){
assigned_group = $(this).val();
$("#available_groups").append("<option value='" + assigned_group + "'>" + assigned_group + "</option>");
});
$("#assigned_groups option").remove()
});