1 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
看看它是否對(duì)你有幫助。
let checkedArr = []; // initialize the variable(type = array) to global scope.
function b(e) { // called every time a the checkbox is clicked
? let totalChecked = 0; // initialize the variable with 0;
? $("input[type=checkbox]." + e).each(function() { // check every checkbox with class e(e has className)
? ? //console.log($(this));
? ? if ($(this).is(":checked")) { // check if checkboxed is checked
? ? ? totalChecked++; // increment every time
? ? }
? });
? // find if class already exists -- returns the index of matched element and -1 for no match
? let existIndex = checkedArr.findIndex((item) => item.class == e);
? console.clear();
? // console.log(existIndex);
? if (existIndex != -1) { // if class exists in array, update its value
? ? checkedArr[existIndex].checked = totalChecked;
? } else { // if not insert the value as an object
? ? checkedArr.push( {class: e, checked: totalChecked} );
??
? }
??
? $('.some_class').val(JSON.stringify(checkedArr)); // convert it to string and assign it to the input field?
??
? alert($('.some_class').val());
? console.log(checkedArr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input onchange="b(this.className)" class="kaka" type="checkbox" name="worker_name[]" value="kaka1" />kaka1
<input onchange="b(this.className)" class="kaka" type="checkbox" name="worker_name[]" value="kaka2" />kaka2
<input onchange="b(this.className)" class="kaka" type="checkbox" name="worker_name[]" value="kaka3" />kaka3
  
<input onchange="b(this.className)" class="lala" type="checkbox" name="worker_name[]" value="lala1" />lala1
<input onchange="b(this.className)" class="lala" type="checkbox" name="worker_name[]" value="lala2" />lala2
  
<input onchange="b(this.className)" class="jaja" type="checkbox" name="worker_name[]" value="jaja1" />jaja1
<input onchange="b(this.className)" class="jaja" type="checkbox" name="worker_name[]" value="jaja2" />jaja2
<!-- Make this ↓↓ hidden -- here only for demo -->
<input type="text" name="hidden_field" class="some_class" value="" />
現(xiàn)在您可以看到,輸入字段的值為checkeArr。然后,在您的中,controller您可以獲得的價(jià)值為 -
$hidden = $this->input->post('hidden_field'); // name of your hidden field
$hidden = json_decode($hidden); // convert it back to its original form
print_r($hidden);
輸出:
Array
(
? ? [0] => stdClass Object
? ? ? ? (
? ? ? ? ? ? [class] => kaka
? ? ? ? ? ? [checked] => 1
? ? ? ? )
? ? [1] => stdClass Object
? ? ? ? (
? ? ? ? ? ? [class] => lala
? ? ? ? ? ? [checked] => 1
? ? ? ? )
? ? [2] => stdClass Object
? ? ? ? (
? ? ? ? ? ? [class] => jaja
? ? ? ? ? ? [checked] => 2
? ? ? ? )
)
您現(xiàn)在可以foreach根據(jù)需要使用它來獲取其價(jià)值。
- 1 回答
- 0 關(guān)注
- 124 瀏覽
添加回答
舉報(bào)