0

I need your help.

I need to come up with a javascript function that would simply check a string entered into a textbox that would basically determine an SQL operator

example:

var field1 = document.getElementById('field1').value

var field2 = document.getElementById('field2').value

var field3 = document.getElementById('field3').value

function validate(textbox) {

var operator

if ('%' is the first character placed before and after the value) { then operator = LIKE }

else if ('%' is the first character placed before the value) { then operator = LIKE }

else if ('%' is the last character placed after the value) { then operator = LIKE }

else { operator equals "=" } //default

alert(operator)


}

example of function in action:

validate(field1)
2
  • Can you provide some sample input strings and expected output? Commented May 8, 2013 at 15:45
  • examples would be %test, %test%, test% Commented May 8, 2013 at 17:08

2 Answers 2

1

Try the following:

function validate(value) {
  var operator = '=';

  // Check for '%' at the beginning or ending of the value.
  if (value.length > 0 && (value[0] == '%' || value[value.length - 1] == '%')) {
    operator = 'LIKE';
  }

  alert(operator);
}

That said, depending on your target users, it might be easier for them if you included a set of radio button options like "Match beginning", "Match end", and "Match anywhere", instead of requiring them to understand SQL string matching syntax.

For example:

<input id="matchBeginning" type="radio" name="matchMode" value="beginning" />
<label for="matchBeginning">Match beginning of text</label>

<input id="matchEnding" type="radio" name="matchMode" value="ending" />
<label for="matchEnding">Match ending of text</label>

<input id="matchAnywhere" type="radio" name="matchMode" value="anywhere" />
<label for="matchAnywhere">Match anywhere in text</label>

<input id="matchExact" type="radio" name="matchMode" value="exact" />
<label for="matchExact">Match entire text</label>

<input id="field1" type="text" />

You could then pass the value of matchMode (i.e. "beginning", "ending", "anywhere", or "exact") along with the search term up to your server, which would add "%" characters to the search term as dictated by matchMode.

Sign up to request clarification or add additional context in comments.

1 Comment

That would probably be due to a missing ")" in the JavaScript example; fixed.
0

You can use regular expressions for this. It looks like if the string contains %, the operator is LIKE. So you can just do this:

var operator = "=";

//If the string starts with a % or ends with a %
//the operator is "LIKE"
if(/^%/.test(str) || /%$/.test(str)) {
   operator = "LIKE";
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.