我在选择复选框输入字段时只尝试获取唯一数据。但是由于从单个输入中获取两个值,我无法使用唯一函数。
jQuery('#showselected').on('click', function() {
var selected = jQuery("#checkboxes input:checked").map(function(i, el) {
return {
datatitle: jQuery(this).attr('data-title'),
dataid: jQuery(this).attr(' data-value')
};
}).get();
jQuery('#rez').empty();
jQuery.each(jQuery.unique(selected), function(key, value) {
jQuery('#rez').append(value.datatitle);
});
});
#rez {border:1px solid red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkboxes">
<input type="checkbox" name="1" data-title="something1" data-value="someid1" />
<label>something1</label>
<input type="checkbox" name="2" data-title="something2" data-value="someid2" />
<label>something2</label>
<input type="checkbox" name="3" data-title="something3" data-value="someid3" />
<label>something3</label>
<input type="checkbox" name="4" data-title="something3" data-value="someid3" />
<label>something3</label>
</div>
<button id="showselected">
show selected
</button> Select above input boxes to see what's been selected.
<div id="rez">
</div>
答案 0 :(得分:1)
您使用jQuery.unique
作为对象值,它不起作用。
使用此代码更新您的最后一行
var data = [];
jQuery.each(selected, function(key, value) {
if(jQuery.inArray(value.datatitle, data) < 0){
data.push(value.datatitle);
}
});
jQuery('#rez').append(data.join(', '));
答案 1 :(得分:0)
我认为你可以使用vanilla JS和Set
更轻松地实现这一点,不需要大型库:
document.querySelector('#showselected').addEventListener('click', () => {
const dataTitles = [...document.querySelectorAll('#checkboxes input:checked')]
.map(checkbox => checkbox.getAttribute('data-title'));
const titlesDeduped = [...new Set(dataTitles)];
document.querySelector('#rez').textContent = titlesDeduped.join(', ');
});
#rez {border:1px solid red}
<div id="checkboxes">
<input type="checkbox" name="1" data-title="something1" data-id="someid1" />
<label>something1</label>
<input type="checkbox" name="1" data-title="something2" data-id="someid2" />
<label>something2</label>
<input type="checkbox" name="1" data-title="something3" data-id="someid3" />
<label>something3</label>
<input type="checkbox" name="1" data-title="something3" data-id="someid3" />
<label>something3</label>
</div>
<button id="showselected">
show selected
</button> Select above input boxes to see what's been selected.
<div id="rez">
</div>