How can I toggle radiobutton

后端 未结 7 1090
一向
一向 2020-12-31 03:57

Say this is my HTML:



         


        
7条回答
  •  离开以前
    2020-12-31 04:47

    I ran into this as well, after thinking about it and playing around with the various fiddles offered, I had a few dissatisfactions with the offered solutions.

    My main problem was the last line of the accepted answer, requiring a reset:

    // remove was checked from other radios
        $radio.siblings('input[name="rad"]').data('waschecked', false);
    

    And since I'm not using jQuery, I'd have to loop over and evaluate the siblings myself, which isn't a huge deal, but seemed inelegant to me. But, there's no way around it with that method, because you're using the dataset as a storage of information.

    After playing around, I realized is that the problem is that when a radio is clicked, it triggers the clicked event, and whatever function is attached to that click event completes itself before the function for the "onchange" event is ever evaluated, let alone called. So, if the click event "unchecks" the toggle, then no change event is ever fired.

    I've left my failed attempt here: https://codepen.io/RiverRockMedical/pen/daMGVJ

    But, if you could answer the question "will a change event happen after this click event?" then you could get a toggle working.

    The solution I came up with can be seen at this pen: https://codepen.io/RiverRockMedical/pen/VgvdrY

    But basically is as follows:

    function onClick(e) {
      e.dataset.toDo = 'uncheck';
      setTimeout(uncheck, 1, {
        event:'click',
        id:e.id,
        dataset:e.dataset
      });
    }
    

    So, on the click event, set a marker that the click has happened, and the use setTimeout() to create a pause that allows the onchange event to be evaluated and fire.

    function onChange(e) {
      e.dataset.toDo = 'leave';
    }
    

    If the onchange event fires, it undoes what was done by the onclick event.

    function uncheck(radio) {
      log('|');
      if (radio.event !== 'click') return;
      log('uncheck');
      if (radio.dataset.toDo === 'uncheck') {
        document.getElementById(radio.id).checked = false;
        radio.checked = false;
      } 
    }
    

    Then, when the uncheck function starts, it has the information of whether a change event followed the click event or not. If not, then the radio is unchecked, and functions as a toggle.

    And, it's basically self-resetting, so I don't have to loop over all the radios and reset their datasets to the initial values at the end of the function.

    Now, I'm sure there's a cooler async/await way to do this that doesn't use setTimeout and would be even more elegant, but I'm still learning and I couldn't come up with it. Anyone else?

提交回复
热议问题