HTML checkbox onclick called in Javascript

前端 未结 4 817
南方客
南方客 2020-12-09 01:32

I am having a bit of trouble trying to figure out how to get a certain part of my code to work.



        
相关标签:
4条回答
  • 2020-12-09 02:01

    How about putting the checkbox into the label, making the label automatically "click sensitive" for the check box, and giving the checkbox a onchange event?

    <label ..... ><input type="checkbox" onchange="toggleCheckbox(this)" .....> 
    
    function toggleCheckbox(element)
     {
       element.checked = !element.checked;
     }
    

    This will additionally catch users using a keyboard to toggle the check box, something onclick would not.

    0 讨论(0)
  • 2020-12-09 02:02

    You can also extract the event code from the HTML, like this :

    <input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" />
    <label for="check_all_1">Select All</label>
    
    <script>
    function selectAll(frmElement, chkElement) {
        // ...
    }
    document.getElementById("check_all_1").onclick = function() {
        selectAll(document.wizard_form, this);
    }
    </script>
    
    0 讨论(0)
  • 2020-12-09 02:08

    Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll() when you click on a label, right? Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label

    <label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
      <input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
      Select All
    </label>
    
    0 讨论(0)
  • 2020-12-09 02:23

    jQuery has a function that can do this:

    1. include the following script in your head:

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
      

      (or just download the jQuery.js file online and include it locally)

    2. use this script to toggle the check box when the input is clicked:

      var toggle = false;
      $("#INPUTNAMEHERE").click(function() {
              $("input[type=checkbox]").attr("checked",!toggle);
              toggle = !toggle;
      }); 
      

    That should do what you want if I understood what you were trying to do.

    0 讨论(0)
提交回复
热议问题