0

所以基本上这里是我的 jsFiddle - http://jsfiddle.net/CmNFu/

和代码也在这里 -

HTML -

<b style="float: left; margin-right: 10px;">category 1</b><input type="checkbox" value="category1" style="float: left;" class="portfolio-category" /><br />
<b style="float: left; margin-right: 10px;">category 2</b><input type="checkbox" value="category2" style="float: left;" class="portfolio-category" /><br />
<br />
<br />
<input type="text" name="categories" id="portfolio-categories" />​

jQuery -

jQuery(document).ready(function() {
    jQuery(".portfolio-category").click(function() {
        if(jQuery(this).is(":checked")) {
            jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+" "+jQuery(this).val());
        }
        else {
            var portfolioCategories = jQuery("#portfolio-categories").val();    
            alert("before + "+portfolioCategories);
            var currentElement = jQuery(this).val()+" ";
            alert(currentElement);
            portfolioCategories = portfolioCategories.replace(currentElement, "");
            alert(portfolioCategories);
        }
    });
});

​嗯,基本上我想要实现的是,当用户选中复选框时,值会自动添加到输入字段中(完成,它正在工作,哇!),但问题是当它取消选中复选框时,值应该从输入框(问题从这里开始),它不会删除任何东西。您可以看到我尝试将 val() 函数分配给变量,但也没有成功。检查我在 jsFiddle 上的示例以查看它。

有什么建议么?我猜 replace() 不适用于 val(),是吗?

那么,还有其他建议吗?

4

3 回答 3

3

我会这样做:

jQuery(document).ready(function() {
    jQuery(".portfolio-category").on('change', function() {
        var string = "";
        $('input[type="checkbox"]').each(function() {
            var space = string.length>0?' ':'';
            string += this.checked?space+this.value:'';
        });
        $("#portfolio-categories").val(string);
    });
});

小提琴

于 2012-08-01T13:40:02.137 回答
2

您对输入框中的空格有很大的问题。但我们稍后会谈到。

首先,这会起作用(如果不是因为空间问题):

在最后一个警报之前添加此行:

 jQuery("#portfolio-categories").val(portfolioCategories);

这会起作用,但并非总是如此,因为您附加的最后一个元素后面没有空格。

但是如果您将第 4 行更改为:

jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+jQuery(this).val()+" ");

它会起作用,因为它在每个元素之后添加空格,而不是之前。

http://jsfiddle.net/CmNFu/5/

您的问题是您更改了变量中的值:portfolioCategories,但您没有更新输入本身。(注意,改变一个字符串的值,不会改变它最初来自的输入的值)

于 2012-08-01T13:40:04.193 回答
0

您需要将字符串portfolioCategories 插入回输入中。空间也产生了很多问题。您可以使用 $.trim(str) 从字符串中删除任何前导和尾随空格。使用有效的解决方案更新了您的小提琴。

http://jsfiddle.net/CmNFu/11/

希望这可以帮助。

于 2012-08-01T13:46:35.217 回答