用jQuery替换输入值.val()

时间:2012-08-01 13:33:07

标签: javascript jquery

所以基本上这里是我的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上的示例以查看它的实时。

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

那么,还有其他建议吗?

3 个答案:

答案 0 :(得分: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);
    });
});

FIDDLE

答案 1 :(得分:2)

您在输入框中的空格存在相当大的问题。但我们马上就会谈到这一点。

首先,这将是一种工作(如果它不是空间问题):

在最后一次提醒之前添加此行:

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

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

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

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

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

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

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

答案 2 :(得分:0)

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

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

希望这有帮助。