Skip to content
Advertisement

How to display the item selected on the same screen after the form is Submitted by the User

I’m trying to display the item selected on the same screen after the form is submitted by the user. The problem is when I use type=”button” for the button instead of type=”submit” then the required attribute is not checked. Is there a way to display the items selected after the form is submitted and the required attribute is also checked using JavaScript?

required

Suppose when you press the submit button without checking any radio buttons, an error is displayed because of the required attribute, and when the user checks any of the options, then after pressing the submit button, the value is displayed adjacent to the inputs.

Advertisement

Answer

  • You can e.preventDefault() on your onSubmit handler to prevent the default page reload on form submission.

  • Then use the FormData object to get the value you require.

const form =  document.querySelector('#form')

form.onsubmit = (e) => {
  e.preventDefault()
  const data = new FormData(e.target);
  document.querySelector('#output').innerHTML = data.get('drone')
}
<form id='form'>

  <fieldset>
      <legend>Select a maintenance drone:</legend>

      <div>
        <input type="radio" id="huey" name="drone" value="huey"
                required>
        <label for="huey">Huey</label>
      </div>

      <div>
        <input type="radio" id="dewey" name="drone" value="dewey">
        <label for="dewey">Dewey</label>
      </div>

      <div>
        <input type="radio" id="louie" name="drone" value="louie">
        <label for="louie">Louie</label>
      </div>
  </fieldset>
  
  <button type='submit'>Submit</button>
</form>

<div id="output"/>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement