validate <input type="radio">

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Zayn
    New Member
    • Sep 2019
    • 17

    validate <input type="radio">

    I'm working on an assignment for school where we're working with JavaScript (I'm only allowed to use JavaScript) to validate a form for a payment page. It's my first time working with JavaScript so and I feel a bit lost..i need to link htmp radio buttons and javascript with a Calculate button


    thml code

    Code:
    <td><input type="text" id="text7" name="fexpirydate" placeholder="22/08/2030" maxlength="30">
    		<tr/>
    		<tr>
    		<td><input type="radio" name="gender" value="Cash" checked><strong>Cash</strong></td>
    		</tr>
    		<tr>
    		<td><input type="radio" name="gender" value="Ecocash" checked><strong>Ecocash</strong></td>
    		</tr>
    		<tr>
    		<td><input type="radio" name="gender" value="Swipe" checked><strong>Swipe</strong></td>
    		</tr><br><br><br>
    Last edited by gits; Sep 10 '19, 09:08 AM. Reason: use code tags!
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5388

    #2
    what exactly should happen in the program here and what have you done so far to solve it?

    Comment

    • parth123
      New Member
      • Sep 2019
      • 4

      #3
      Code:
      <form name="form1" action="#" onsubmit="return validateForm()" method="post"> 
          First time visitor?:<br/>
                  <label for="s1">Yes</label>
                  <input type="radio" id="radio1" name="yesno" value="1"/>
                  <br/>
                  <label for="s2">No</label>
                  <input type="radio" id="radio2" name="yesno" value="2"/>
      
                  <br/>       
      
          <input type="submit" value="Submit"><br/>
          </form>


      Code:
      function validateForm() {
          var radios = document.getElementsByName("yesno");
          var formValid = false;
      
          var i = 0;
          while (!formValid && i < radios.length) {
              if (radios[i].checked) formValid = true;
              i++;        
          }
      
          if (!formValid) alert("Must check some option!");
          return formValid;
      }
      Last edited by gits; Sep 16 '19, 06:52 AM. Reason: use code tags!

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5388

        #4
        throwing out some code without knowing what the exact problem is is plain guesswork. While the OP is already asking because he/she is lost - with no further elaboration of that shown code it probably even wont help much - the answer could even be 42.

        Besides that its pretty sub-optimal to do validations like that - since it requires DOM operations. its much more optimal when using events to update a state - you will see that when you have pages with lots of elements that you are validating the way you propose here.

        Comment

        Working...