Jquery在列表框中添加和删除项目 [英] Jquery adding and removing items from listbox

查看:106
本文介绍了Jquery在列表框中添加和删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个小提琴,它允许用户点击艺术或视频,动态填充第二个列表框与这些选择相关联的列表。有两个按钮,一个用于将选项添加到框中,另一个用于删除选择。

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.

我想要做的是阻止用户添加一些已被添加。选项的价值都是Guids。如果您可以修改小提琴使用Guid而不是整数,则可以获得奖励。

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.

我试过这个:

$.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.

谢谢,

更新只是让你们知道我提出的解决方案是什么,我得到了奖励积分,因为我以一种非常聪明的方式添加了GUID :) 小提琴,我还整理了html来制作它看起来很整洁。

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 <<

推荐答案

我想你会想做这样的事情:检查值是否在带有JQuery的选择列表中

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();
});

这篇关于Jquery在列表框中添加和删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆