使用onchange函数获取复选框值

时间:2018-09-08 05:28:04

标签: javascript jquery checkbox

我正在使用多个复选框来执行某些操作。我的要求是,如果选中此复选框,则获取on;如果不选中此复选框,则获取off。但是,如果我选中/取消选中复选框,则得到的值为on

<label class="cont">
   <input type="checkbox" name="listingstatus" id="listingstatus<?php echo $doc->module_video_id; ?>" onchange="listingStatus('<?php echo $doc->module_video_id; ?>')">
   <span class="checkmark"></span>
</label>


function listingStatus(module_video_id)
{
  var a = $('#listingstatus'+module_video_id).val();
  console.log(a);
}

4 个答案:

答案 0 :(得分:3)

使用三元运算符尝试is(":checked")

var a = $('#listingstatus'+module_video_id).is(":checked") ? 'on' : 'off';

答案 1 :(得分:0)

使用普通的Javascript,您可以使用以下内容:

btn.addEventListener('click', () => {
  const checkedInputs = Array.from(document.querySelectorAll('input:checked'));
  const values = [];
  checkedInputs.forEach((checkbox) => {
    values.push(checkbox.value);
  })
  console.log(values);
})
<input type="checkbox" value="foo" />
<input type="checkbox" value="bar" />
<input type="checkbox" value="baz" />
<input type="checkbox" value="wtf" />
<button type="button" id="btn">Console.log checked values</button>

如果您需要其他不同的内容,请尝试更清楚地了解您的要求。

答案 2 :(得分:0)

使用.checked代替.value:

 <input type="checkbox" id="chkBox" onchange="foo()">

<script>
function listingStatus()
{
  var isChecked = document.getElementById('chkBox').checked;
  console.log(isChecked);
}
</script>

答案 3 :(得分:0)

您可以使用以下脚本检查复选框是否已选中

function listingStatus(module_video_id)
    {
        if ($('#listingstatus' + module_video_id).prop('checked')) {
            console.log('checked do stuff here');
        } else {
            console.log('not checked');
        }
    }