Home > OS >  Correct way to trigger radio button handler with jQuery
Correct way to trigger radio button handler with jQuery

Time:10-15

I have two radio buttons. Depending on which one is checked, I want to show or hide a <div> on the page. So I created this handler.

$(function () {
    $('input[name="Search.LatestOnly"]').on('change', function () {
        if ($(this).val() == 'true')
            $('#date-section').hide(400);
        else
            $('#date-section').show(400);
    });
});

This works fine. But I want to set the <div> visibility to the correct state when the page loads, so I added this line:

$('input[name="Search.LatestOnly"]:checked').trigger();

This produces run-time errors that aren't meaningful to me.

jQuery.Deferred exception: Cannot convert undefined or null to object TypeError: Cannot convert undefined or null to object at hasOwnProperty () at Object.trigger (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:70619) at HTMLInputElement. (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:72108) at Function.each (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:2976) at S.fn.init.each (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:1454) at S.fn.init.trigger (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:72084) at HTMLDocument. (https://localhost:44377/Data/Search:206:58) at e (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:30005) at t (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:30307) undefined S.Deferred.exceptionHook @ jquery.min.js:2 t @ jquery.min.js:2 setTimeout (async) (anonymous) @ jquery.min.js:2 c @ jquery.min.js:2 fireWith @ jquery.min.js:2 fire @ jquery.min.js:2 c @ jquery.min.js:2 fireWith @ jquery.min.js:2 ready @ jquery.min.js:2 B @ jquery.min.js:2 jquery.min.js:2

Uncaught TypeError: Cannot convert undefined or null to object at hasOwnProperty () at Object.trigger (jquery.min.js:2) at HTMLInputElement. (jquery.min.js:2) at Function.each (jquery.min.js:2) at S.fn.init.each (jquery.min.js:2) at S.fn.init.trigger (jquery.min.js:2) at HTMLDocument. (Search:206) at e (jquery.min.js:2) at t (jquery.min.js:2)

Can anyone tell me how to initialize my HTML so that the <div> is hidden or displayed once the page is loaded?

CodePudding user response:

Here is a working example of show / hide connected to a radio input, that checks the current checked value and runs immediately, as well as adds the event listener. Hopefully this adds some perspective to your own project. Unfortunately without being able to recreate the error it will be difficult to give more specific advice. I would always be happy to look over your project separately from this answer.

I did a cheeky little thing where I made the value of the radio the desired method just to cut down on steps where I would usually have to write a conditional to handle understanding the value.

$(() => {
  const content = $("div");
  const shown = $("input[name='test']:checked").val();
  const handleShow = (method, t = 200) => content[method](t);
  handleShow(shown, 0);
  $("input").on("change", function () {
    const shown = $(this).val();
    handleShow(shown);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  conditional content
</div>
<label> Show
  <input type="radio" name="test" value="show" checked>
</label>
<label> Hide
  <input type="radio" name="test" value="hide">
</label>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I thought I would include an example of accomplishing this goal in vanilla javascript as well, as a resource for anyone else that stumbles across the question.

Two things to keep in mind with this answer, the max-height of 1rem in css will not work for all containers. You could dynamically set the max-height, or use something impossibly high (which would affect animations)

This does not check the state of "checkedness" upon initial launch, it assumes it will always have the same state upon launch.

(() => {
  const $ = str => [...document.querySelectorAll(str)];
  const content = $("div")[0];
  const radios = $("input[name='test']");
  radios.forEach(radio => {
    radio.addEventListener("input", e => {
      const val = e.target.value;
      if (val === "show") content.classList.remove("hidden");
        else content.classList.add("hidden");
    });
  });
})();
div {
  max-height: 1rem;
  transition: max-height .2s;
  overflow: hidden;
}

.hidden {
  max-height: 0;
}
<div>
  conditional content
</div>
<label> Show
  <input type="radio" name="test" value="show" checked>
</label>
<label> Hide
  <input type="radio" name="test" value="hide">
</label>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related