将输入值.val()替换为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上查看我的示例以查看它的实况。

有什么建议吗?我想replace()对val()无效,是吗?

那么,还有其他建议吗?

我会这样做:

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

输入框中的空格有很大问题。但我们稍后会讨论的。

首先,这是可行的(如果不是因为空间问题):

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

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

这将起作用,但并不总是,因为您附加的最后一个元素后面没有空格

但如果你把第4行改成这个:

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

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

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

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

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

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

希望这能有所帮助。

最新更新