【问题标题】:jQuery - remove value from input attributejQuery - 从输入属性中删除值
【发布时间】:2017-08-20 11:00:59
【问题描述】:

我的 jQuery 脚本将产品 ID 添加到输入 type="hidden" value="id1,id2,id3"

脚本正在运行并在复选框更改时添加 id,但如果我取消选中该框,则必须从该输入中删除 id。

我的部分代码:

<input type="hidden" value="100" class="productid100">

<script>

 var productid = jQuery(".productid<?php echo $_item->getId(); ?>").val();
 var defaultcombo = jQuery('.combodata').val();

 if(jQuery(this).is(":checked")) {

 jQuery('.combodata').attr("value", defaultcombo + productid+",");

 }else{

 var test = jQuery('#combo input:hidden[value=""]', productid+',').remove();
 console.log(test);

 }
</script>

<div id="combo">
<input type="hidden" class="hidden combodata" value="">
</div>

console.log()

Uncaught Error: Syntax error, unrecognized expression: 100,
at Function.ga.error (jquery-1.11.1.min.js:2)
at ga.tokenize (jquery-1.11.1.min.js:2)
at ga.select (jquery-1.11.1.min.js:2)
at Function.ga [as find] (jquery-1.11.1.min.js:2)
at m.fn.init.find (jquery-1.11.1.min.js:2)
at m.fn.init (jquery-1.11.1.min.js:2)
at new m (jquery-1.11.1.min.js:2)
at m.fn.init (jquery-1.11.1.min.js:2)
at m (jquery-1.11.1.min.js:2)
at HTMLInputElement.<anonymous> ...

此代码位于页面中每个产品显示的 PHP foreach 中。

最后我只需要在复选框单击时添加产品 id 并在取消选中时删除指定的 id。

问题来了:

jQuery('#combo input:hidden[value=""]', productid+',').remove();

【问题讨论】:

  • 试试jQuery('#combo input:not(:checked)').attr('value').remove();
  • 组合输入不是复选框
  • 对不起,我误解了你的问题,请看@RoryMcCrossan 的回答

标签: javascript jquery checkbox replace


【解决方案1】:

您的代码问题是由于您使用remove() 的语法造成的。它旨在从 DOM 中删除元素,而不是元素属性中字符串的一部分。

您可以通过构建与选中复选框相关的隐藏输入值的数组来简化问题,然后在该数组上调用 join() 并将其设置为隐藏字段的值,如下所示:

$('.checkbox').change(function() {
  var values = $('.checkbox:checked').map(function() {
    return $(this).next('.myclass').val();
  }).get();
  
  $('#output').val(values.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox" class="checkbox" value="id1" /> 
  <input type="hidden" value="100" class="myclass">
  id1
</label>
<label>
  <input type="checkbox" class="checkbox" value="id2" /> 
  <input type="hidden" value="200" class="myclass">
  id2
</label>
<label>
  <input type="checkbox" class="checkbox" value="id3" /> 
  <input type="hidden" value="300" class="myclass">
  id3
</label>

<input type="text" id="output" />

请注意,对于此示例,该字段是一个文本输入,因此您可以看到正在更改的值。

【讨论】:

  • 您好,感谢您的代码,我尝试过并且正在工作,但是它获取了复选框的值,我需要隐藏输入的值,可以这样做吗? &lt;input type="checkbox" class="checkbox" value="1" /&gt; &lt;input type="hidden" value="100" class="myclass"&gt;复选框值我用它作为产品价格,另一个输入是产品ID。
  • hidden是直接在checkbox后面输入吗?这将有助于查看您的实际 HTML - 如果您可以编辑您的问题以包含它
  • 是的,是在复选框之后,我正在更新。
  • 如果它直接在复选框之后就可以了。我为你更新了答案
  • 太棒了,这么简单,花了我很多时间。非常感谢您的宝贵时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
相关资源
最近更新 更多