Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking if field value exists in a string 1

Status
Not open for further replies.

rmagan

Programmer
Jun 3, 2003
35
US
I have a field that needs to be checked against a string. If the field value exists in the string it is ok. Why is the code below giving me an error?


<input type=&quot;text&quot; name=&quot;p_chg_semester&quot; onChange=&quot;IsValidSemester(this.value,'~Q1~~Q2~~Q3~~Q4~~RM~~S1~~S2~')&quot; value=S1>

function IsValidSemester(semester, semester_fld)
{
var prefix = '/~';
var suffix = '~/';
var objRE = prefix + semester.toUpperCase() + suffix;
if (objRE.test(semester_fld)) {
alert(semester);
}
else
{
alert(&quot;NOT Found&quot;);
}
}
 
Try this replacement for your function:

Code:
function IsValidSemester(semester, semester_fld)
{
  if (semester_fld.indexOf(semester)>-1)
  {
    alert(semester);
  } else {
    alert('NOT Found');
  }
}

Then you could get all complex and replace the function with:

Code:
function IsValidSemester(semester, semester_fld)
{
  alert((semester_fld.indexOf(semester)>-1) ? semester : 'Not Found');
}

Finally you can get rid of the function and put it into the input box directly:

Code:
<input type=&quot;text&quot; name=&quot;p_chg_semester&quot; onChange=&quot;alert(('~Q1~~Q2~~Q3~~Q4~~RM~~S1~~S2~'.indexOf(this.value)>-1) ? this.value : 'Not Found')&quot; value=S1>

Hope we all had fun - I did...
Jeff
 
Good solution Jeff,

I'll throw this in, in case rmagan needs later to use
variables to &quot;build&quot; a reg exp.

rmagan,

To generate a reg exp using variables use new RegExp like:
Code:
  var prefix = '~';
  var suffix = '~';
  var str = prefix + semester.toUpperCase() + suffix;
  var objRE = new RegExp(str);

And you can include the &quot;g&quot; and &quot;i&quot; switches like.
var objRE = new RegExp(str,&quot;gi&quot;);
 
Yup... that's the way to do it with regexp alright!

I wasn't going to wade through regexp stuff when such a simple solution was staring at me... but it's certainly a LOT more flexible for forward development than my trusty old &quot;indexOf&quot; :)

Cheers,
Jeff
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top