如何将复选框中的选中值收集为 javascript 数组/字符串


How to collect checked values in checkboxes as a javascript array/string?

我想知道如何在mysql数据库中以复选框的形式搜索用户提供的输入。但在此之前,我需要将选中的字段放入 javascript 数组/字符串中,以便我可以使用 url 将其传递给 PHP。

<form>
    <input type="checkbox" id="interests" name="interests" value="Food">`
    <input type="checkbox" id="interests" name="interests" value="Movies">`
    <input type="checkbox" id="interests" name="interests" value="Music">`
    <input type="checkbox" id="interests" name="interests" value="Sports">`
</form>

我能够对其他表单元素(例如文本)进行上述操作并选择输入,但不确定如何为复选框执行此操作。请帮忙。谢谢

而不是

<form> 
<input type="checkbox" id="interests" name="interests[]" value="Food"> 
<input type="checkbox" id="interests1" name="interests[]" value="Movies"> 
<input type="checkbox" id="interests2" name="interests[]" value="Music"> 
<input type="checkbox" id="interests3" name="interests[]" value="Sports">

将名称属性从interests更改为interests[]应该解决你的问题。如果我对属性有误,我很抱歉,有点不符合 PHP 的实践,但我很确定。无需对javascript做任何事情。这样更容易。当然,如果你不想要简单...

就您关于通过数据库搜索它的第一个问题而言,我不明白您为什么需要这样做?如果它是一个复选框,你确切地知道它应该是什么,所以只需让它像这样插入你的数据库:

INSERT INTO your_table values(user_id_i_guess, interests...);

你明白了吧?

代码中的问题

  • 不要对多个元素使用相同的id

  • 将复选框的名称更改为interests[]

jQuery

var vals = [];
$(':checkbox:checked[name^=interests]').val(function() {
   vals.push(this.value);
});

如果要将数组转换为逗号分隔的字符串,请尝试

val.join(',');

注意

$(':checkbox:checked[name^=interests]')选择器选中所有选中的复选框name并以 interests 开头。

  1. 您必须为复选框使用不同的 id(元素的 id 必须是唯一的)
  2. 为复选框命名 interest[] 并提交表单 - 在服务器上您可以使用数组 $_POST['interest'] 或 $_GET['interest']

假设您的表单有一个名称,

var c = [],
    els = document.forms.formName.elements,
    len = els.length;
for ( var i = 0; i < length; i++ ) {
    if ( els[ i ].type === 'checkbox' ) {
        // If you want to add only checked checkboxes, you can use:
        if ( els[ i ].checked ) c.push( els[ i ].value );
        // If you don't care, just use:
        c.push( els[ i ].value );
    }
}
console.log( c ); // Array of the checkboxes values

如果您不关心旧版浏览器,您可以使用map来获得更干净的代码:

var c = [].map.call( document.forms.formName.elements, function( el ) {
    if ( el.type === 'checkbox' ) {
        if ( el.checked ) return el.value;
    }
} );

如果你有jQuery,这里有一些codez:

var c = $( ':checkbox:checked' ).map( function() {
    return $( this ).val();
} );
console.log( c ); // Array of the checkboxes values
// To be more precise (so, more performant), you can use the following selector:
$( ':checkbox:checked', document.forms.formName.elements )