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()
});
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 have a function like this:
$('input[type=radio][name=editList]').change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")",
function (data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" +item.ID+item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
I want to get that item.ID to use into another function as:
$(function getCuadrilla() {
var items = "";
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "?ProveedorID=" + ID, function (data) {
$.each(data, function (index, item) {...
});
$("#lstcuadrilla").html(items);
});
});
I try to use $('input[type=radio][name=editList]').val() as
$(function getCuadrilla() {
var items = "";
$('input[type=radio][name=editList]').val();
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "?ProveedorID=" + ID, function (data) {
$.each(data, function (index, item) {...
});
$("#lstcuadrilla").html(items);
});
});
but instead item.ID I receive string "Proveedor", can any one explain me how can I access to item.ID? Regards
Complete JS:
<script type="text/javascript">
$(function getResponsable() {
$('input[type=radio][name=editList]')
.change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores ", "Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.ID + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("
GetUnidades ", "
Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.Codigo + "-" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario ", "Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + " " + item.Apellido + "</option>";
});
$("#lstProveedor").html(items);
});
}
});
$(function getCuadrilla() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
});
As James comment, I try it and JS hit first line but it donĀ“t pass over there
Update:
New js structure:
<script type="text/javascript">
$(function getResponsable() {
$('input[type=radio][name=editList]')
.change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.ID +
item.NombreComercial +
"</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("GetUnidades", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.Codigo +
"-" +
item.Nombre +
"</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.Nombre +
" " +
item.Apellido +
"</option>";
});
$("#lstProveedor").html(items);
});
}
});
$("#lstProveedor").change(function() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
}
);
});
});
</script>
You can try this. Keep in mind that the ID you are passing to the handler function is either a provider id or a sucursal id or a usuario id, depending on which radio button populated the drop down the first time around. Also this handler will remain on the dropdown even when it has been populated by Cuadrillas.
Change
$(function getCuadrilla() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
to
$("#lstProveedor").change(function (e) {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
}
);
});
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);
}
});
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>');
});
I have 3 drop down list. 1 is for selecting department. second is selecting subject. this drop down should be populated based on department drop down. third is student drop down. this should also populated based on department drop down. how can i perform this? Any help???
$(function () {
var items = '<option>Select Subject</Option>';
$('#DepartmentID').change(function () {
$.getJSON('/Mark/SubjectList/' + $('#DepartmentID').val(), function (data) {
$.each(data, function (i, subject) {
items += "<option value='" + subject.Value + "'>" + subject.Text + "</option>";
});
alert("changed");
$('#SubjectID').html(items);
});
});
});
$(function () {
var items = '<option>Select Subject</Option>';
$('#DepartmentID').change(function () {
$.getJSON('/Mark/StudentList/' + $('#DepartmentID').val(), function (data) {
$.each(data, function (i, student) {
items += "<option value='" + student.Value + "'>" + student.Text + "</option>";
});
$('#StudentID').html(items);
});
});
});
these are the two functions that I want to combine.
Just put both AJAX calls within one change handler for DepartmentID:
$(function () {
$('#DepartmentID').change(function () {
$.getJSON('/Mark/SubjectList/' + $('#DepartmentID').val(), function (data) {
var items = '<option>Select Subject</Option>';
$.each(data, function (i, subject) {
items += "<option value='" + subject.Value + "'>" + subject.Text + "</option>";
});
alert("changed");
$('#SubjectID').html(items);
});
$.getJSON('/Mark/StudentList/' + $('#DepartmentID').val(), function (data) {
var items = '<option>Select Subject</Option>';
$.each(data, function (i, student) {
items += "<option value='" + student.Value + "'>" + student.Text + "</option>";
});
$('#StudentID').html(items);
});
});
});
(Note: I did also move the var items = ... bit inside each respective callback function so they each have their own variable. I suspect one was supposed to say "Select Student")
This code will now make 2 AJAX requests whenever DepartmentID dropdown is changed, a populates 2 different select elements
Just combine this way:
$(function () {
var items = '<option>Select Subject</Option>';
$('#DepartmentID').change(function () {
$.getJSON('/Mark/SubjectList/' + $('#DepartmentID').val(), function (data) {
$.each(data, function (i, subject) {
items += "<option value='" + subject.Value + "'>" + subject.Text + "</option>";
});
alert("changed");
$('#SubjectID').html(items);
});
});
var stuitems = '<option>Select Subject</Option>';
$('#DepartmentID').change(function () {
$.getJSON('/Mark/StudentList/' + $('#DepartmentID').val(), function (data) {
$.each(data, function (i, student) {
stuitems += "<option value='" + student.Value + "'>" + student.Text + "</option>";
});
$('#StudentID').html(stuitems);
});
});
});