0

我需要你的帮助。

我需要想出一个 javascript 函数,它可以简单地检查输入到文本框中的字符串,该文本框基本上可以确定 SQL 运算符

例子:

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)


}

实际功能示例:

validate(field1)
4

2 回答 2

1

尝试以下操作:

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);
}

也就是说,根据您的目标用户,如果您包含一组单选按钮选项,例如“匹配开始”、“匹配结束”和“在任何地方匹配”,而不是要求他们理解 SQL 字符串匹配,那么对他们来说可能会更容易句法。

例如:

<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" />

然后,您可以将matchMode(即“开始”、“结束”、“任何地方”或“精确”)的值与搜索词一起传递到您的服务器,这将按照指定的方式将“%”字符添加到搜索词中matchMode.

于 2013-05-08T15:49:30.160 回答
0

您可以为此使用正则表达式。看起来如果字符串包含%,则运算符是LIKE。所以你可以这样做:

var operator = "=";

//If the string starts with a % or ends with a %
//the operator is "LIKE"
if(/^%/.test(str) || /%$/.test(str)) {
   operator = "LIKE";
} 
于 2013-05-08T17:13:26.257 回答