samedi 28 août 2021

How can I use conditional logic with JavaScript form validation?

I have the following JavaScript function which is triggered by an onclickevent and is working fine.

<script>
  function validateForm() {
    let xgame_name = document.forms['myForm']['game_name'].value;
    if (xgame_name == '') {
      alert('Game Name must be filled out');
      return false;
    }
    let xdev_name = document.forms['myForm']['developer_name'].value;
    if (xdev_name == '') {
      alert('Developer Name must be filled out');
      return false;
    }
    let xdev_email = document.forms['myForm']['email'].value;
    if (xdev_email == '') {
      alert('Developer Email must be filled out');
      return false;
    }
    let xdemo_rom = document.forms['myForm']['demo_rom'].value;
    if (xdemo_rom == '') {
      alert('Demo Rom must be uploaded');
      return false;
    }

    let xpromo_image = document.forms['myForm']['promo_image'].value;
    if (xpromo_image == '') {
      alert('Promo must be uploaded');
      return false;
    }
  }
</script>

I am trying to add this so if one of the radio buttons with a value of 1 is selected on the form it will check an additional field to see if there is a value and show an alert.

let xcartridge = document.forms['myForm']['cartridge'].value;
if (xcartridge == '1') {
  let xcover_art = document.forms['myForm']['cover_art'].value;
  if (xcover_art == '') {
    alert('If Cartridge is selected you must proved Cover Art');
    return false;
  }
}

This follows the same syntax of the above code example that is working but this does not send an alert but rather the form validation does not work at all. How can I get the alert to show when one fields condition is met, where it is 1 and that prompts an alert on an additional field?

Aucun commentaire:

Enregistrer un commentaire