Call for Javascript Help

Hi all, hope you might be able to help. I have just used phpFormGen v3.0 to create a multipage form. The problem is I am not very good with Javascript. I want to add a Javascript function that does not allow the form to proceed if “No” is selected in a dropdown menu. The behaviour should be that if “No” is selected the form will redirect to an exit page explaining why they can’t proceed or simply pop up an error message that will not go away until “Yes” is selected. Help will be most appreciated. The code is as follows:


<h3 class="formInfo1">Traceable References</h3>
<li class="mainForm" id="fieldBox_15">
<label class="formFieldQuestion">Do You Have More Than 5 Years Traceable References?&nbsp;*&nbsp;<a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Can you provide referees who have known you for more than 5 years? This is essential for compliance. If you do not have this you may not proceed beyond this point.</span></a></label><select class=mainForm name=field_15 id=field_15><option value=''></option><option value="No">No</option><option value="Yes">Yes</option></select></li>
<!-- end of this page -->
<!-- page validation -->
<SCRIPT type=text/javascript>
<!--
function validatePage3()
{
retVal = true;
if (validateField('field_15','fieldBox_15','menu',1) == false)
retVal=false;
if(retVal == false)
{
alert('Please correct the errors.  Fields marked with an asterisk (*) are required');
return false;
}
return retVal;
}
//-->
</SCRIPT>
<!-- end page validaton -->

Hi,

Welcome to the forums :slight_smile:

You can do it like this:

<form>
    <label for="references">Do You Have More Than 5 Years Traceable References?</label>
    <select id="references">
        <option>Please select</option>
        <option value="No">No</option>
        <option value="Yes">Yes</option>
    </select>
    <br />
    <button>Submit</button>
</form>
var form = document.forms[0], 
    r = document.getElementById("references");

form.addEventListener('submit', function(e) {
    if(r.options[r.selectedIndex].value !== "Yes"){
        alert("Please select yes");
        e.preventDefault();
    }
});

Demo

If you want to add any validation checks other than this one, then you would be better off putting them in their own function, as opposed to an anonymous one.

E.g.

function validateForm)(){
  // Validation checks here
}

form.addEventListener('submit', validateForm);