Search code examples
javascriptformsradio-button

Radio buttons with input text


I am creating a form and I have a radio button with input text next to it. After selecting the radio button and submitting the form without writing anything in the field text, how do you show an alert that the field text is left blank? Can anyone show me an example in Javascript please?

function validation(thisForm){
if(!thisForm.this.value.length)
{
  document.getElementById('this-error').innerHTML="Please select at least one option!";
  document.getElementById('this-error').style.display="inline-block";
  return false;
}
return true;
}
 input[type="submit"] {
    padding:10px;
    height:inherit;
    background-color:purple;
    width:100%;
}
<section class="form-section">
<fieldset>
  <legend>This Application is For</legend>
  <div class="input-container">
    <input type="radio" name="this" id="new" value="new">
    <label for="new">New membership</label>
  </div>
    <div class="input-container">
    <input type="radio" name="this" id="add" value="add">
    <label for="add">Addition of dependent(s) to existing policy as listed above</label>
  </div>
    <div class="input-container">
    <input type="radio" name="this" id="upgrade" value="upgrade">
    <label for="upgrade">Upgrade existing plan</label>
  </div>
    <div class="input-container">
      <input type="radio" name="this" id="other" value="other">Other:<input type="text" name="plan"/>
<span class="error-messages" id="this-error"></span>

        </div>
</fieldset>
            </section>
            
            <section class="form-section">

    <input type ="submit" value="submit"/>


  </section>


Solution

  • If you are using JS then

    function check() {
      if(document.getElementById("other").checked === true) {
        if(document.getElementById("other_reason").value === ""){
          alert('error')
        }
      }
    }
    

    And your HTML would look something like:

    <input type="radio" name="reason" id="other" value="">Other <input type="text" id="other_reason" />
    
    <button typr="submit" onclick="check()">Submit</button>
    

    Basically when you click on submit, you check if the radio button which requires a text input is checked and if true then it verifies if the value of the input text is not empty.