Marcelo Camisa
Marcelo Camisa

Reputation: 11

Only trigger AJAX if two characters or more are entered

I have the following code:

<script>
    function pesquisa_cid_01() {
        var oHTTPRequest = createXMLHTTP(); 
        oHTTPRequest.open("post", "bd_ajax_ciat_cid.asp", true);
        oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        oHTTPRequest.onreadystatechange=function() {
            if (oHTTPRequest.readyState == 4) {
                document.all.div_pesquisa_cid_01.innerHTML = oHTTPRequest.responseText;
            }
        }
        oHTTPRequest.send("busca_cid_01=" + encodeURIComponent(form_ciat_new.pesquisa_cid_01_form.value));
    }
</script>

How can I force the code start work only with 2 plus characters typed in form input?

The form code is:

<input type="text" name="pesquisa_cid_01_form" id="pesquisa_cid_01_form" class="form-control" onkeyup="pesquisa_cid_01();">

Upvotes: 1

Views: 85

Answers (1)

Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18929

just check the length of the value and exit if not correct.

function pesquisa_cid_01(e) {
   if (e.currentTarget.value.length < 2) {
     return;
   }

   ...
}

Upvotes: 2

Related Questions