Javascript checkbox onChange

后端 未结 10 1183
孤街浪徒
孤街浪徒 2020-11-28 06:00

I have a checkbox in a form and I\'d like it to work according to following scenario:

  • if someone checks it, the value of a textfield (totalCost)
相关标签:
10条回答
  • 2020-11-28 06:24

    If you are using jQuery.. then I can suggest the following: NOTE: I made some assumption here

    $('#my_checkbox').click(function(){
        if($(this).is(':checked')){
            $('input[name="totalCost"]').val(10);
        } else {
            calculate();
        }
    });
    
    0 讨论(0)
  • 2020-11-28 06:27

    HTML:

    <input type="checkbox" onchange="handleChange(event)">
    

    JS:

    function handleChange(e) {
         const {checked} = e.target;
    }
    
    0 讨论(0)
  • 2020-11-28 06:28

    Pure javascript:

    const checkbox = document.getElementById('myCheckbox')
    
    checkbox.addEventListener('change', (event) => {
      if (event.target.checked) {
        alert('checked');
      } else {
        alert('not checked');
      }
    })
    My Checkbox: <input id="myCheckbox" type="checkbox" />

    0 讨论(0)
  • 2020-11-28 06:28

    The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.

    const checkbox = $("#checkboxId");
    
    checkbox.change(function(event) {
        var checkbox = event.target;
        if (checkbox.checked) {
            //Checkbox has been checked
        } else {
            //Checkbox has been unchecked
        }
    });
    
    0 讨论(0)
  • 2020-11-28 06:29

    Use an onclick event, because every click on a checkbox actually changes it.

    0 讨论(0)
  • 2020-11-28 06:40
    function calc()
    {
      if (document.getElementById('xxx').checked) 
      {
          document.getElementById('totalCost').value = 10;
      } else {
          calculate();
      }
    }
    

    HTML

    <input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
    
    0 讨论(0)
提交回复
热议问题