所以基本上这是我的 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);
});
});
关于javascript - 将输入值 .val() 替换为 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11760418/