Run Validation if

Hi everyone,

I am trying to run the following script to validate if textbox ‘vSurveyAnswer[1].answer’ is empty ONLY if the ‘groupid’ equals 542. I can’t seem to get this to work, it validates regardless. Any help would be great. I also need to be able to validate other text boxes when the groupID is a different number (groupID comes from a querystring parameter)


$(document).ready(function(){
  $('#continueResBtn').click(function() {
  if($("#groupid").val() === "542"){
	if ($("input[name='vSurveyAnswer[1].answer']").val().length === 0){
      alert('Please Enter Start Date');
       return(false);
  }
  else return(true)
}
});
});


Thanks!!

If your #groupid is a plain input field then the above code should work fine.

This code in isolation:

Seems to work just fine.

Do you perhaps have a sample page online somewhere to look at?

Thanks AussieJohn looks like it is working on JSFiddle, I made a couple changes to my local and it seems to be working now.

Quick question, I would like to include the ability to make the groupID variable, example: if groupid = 542 or 543 or 544 and vSurveyAnswer is blank then fire the alert, do you know of a quick way of doing this?

Thanks for your help!!!

If your groupId comes from a query string, it is pretty trivial to retrieve it with a simple JavaScript helper function https://snipt.net/geekyjohn/get-url-param/

You could then call getUrlParam(“groupId”) and it would return the value of the parameter (or undefined)

The purpose is that not all groupid values will be used to validate against, I have specify which ones. I am actually pulling the querystring param from the URL via a jSP call ont eh page and placing it into a hidden field. I am then using the validation script to check the groupID which validates the survey fields. Does that make sense? I am not a big JS guy so I am not sure if I can use the link you supplied.

Makes sense. If you have a list of the group IDs that would require the validation you could put them in an array,
e.g.


var groupIDs = [1, 2, 3, 4, 234, 542];

You could then perform your validation if the current group ID falls is found in that array (using jQuery’s inArray method)


if ( $.inArray(groupID, groupIDs) ) { 
  //perform validation
}

Hi AussieJohn, not sure what’s happening, but it doesn’t seem to work. Here is an example…

Whoops yes, the .inArray() function returns an index or -1 if not found (and not a boolean).

I’ve updated the fiddle: http://jsfiddle.net/CX6Ba/21/

Basically made inArray check for equality against “-1” and making sure that the group ID is actually retrieved from the field and parsed as a number.

That’s the ticket, thanks AussieJohn!!