javascript - 将输入值 .val() 替换为 jQuery

标签 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 上的示例以查看它的实时情况。

有什么建议吗?我猜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

关于javascript - 将输入值 .val() 替换为 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11760418/

相关文章:

jquery - div 中的 Kendo 散点图 - 部分图表不可见

javascript - 三个js物体绕球体旋转

javascript - 限制 Google 自定义搜索引擎中的日期范围

javascript - 返回后循环后的字符串列表

javascript - 我需要重构 javascript 代码(使其更好、更小)

Javascript - 在选择时更改图像和文本

javascript - 当参数作为对象发送时,为什么 Node 服务器不读取 React 中的 axios post ?

JavaScript 验证 : regex to validate numbers with comma

javascript - 为什么这个 JavaScript 会失败?

jquery - 通过缓慢滑动到侧面动画隐藏单击时的 div