Home > Software engineering >  check if radio button is checked in ejs
check if radio button is checked in ejs

Time:12-20

As the title says,I'm trying to check if radio button is checked,but since document isn't available,how am I supposed to do it? I want to achieve

<%if(radio1.checked){%>
 <%-include('./someHtml')%>
<%}%>

CodePudding user response:

Assuming you care only about the state at the time the document loads:

There's no document, but there's no radio button either.

What you have is some data and an EJS program.

The EJS program must already have some logic to examine that data and determine if it should output a checked attribute (or not) for each radio button.

Use that same logic to determine if the include should be used.


If, on the other hand, you want to change what is displayed, live, as the user clicks on radio buttons then you can't do that in EJS.

By the time the HTML is delivered to the browser, turned into a DOM, and rendered where the user can click on it: the EJS has finished.

You can either:

  • Use client-side JS to change what content is shown or
  • Replace the radio buttons with links or submit buttons and load a whole new page from the server based on the submitted data

Related reading:

CodePudding user response:

You can either send an Ajax request when clicking the radio button and handle it's state in the backend or show/hide 'someHtml' using Javascript:

<input
  type="radio"
  name="toggleHtml"
  onclick="document.getElementById('someHtml').style.display = 'block';" checked
/> Show

<input
  type="radio"
  name="toggleHtml"
  onclick="document.getElementById('someHtml').style.display = 'none';"   
/> Hide

<div id="someHtml">Some HTML ...</div>
  • Related