Skip to content Skip to sidebar Skip to footer

Onkeyup Function Only Firing Once

I need the onkeyup to fire more than once, but it seems to be only firing once! When I enter something into the input box, it searches, but then whenever I backspace and search som

Solution 1:

Still not sure about your issue with the keyup only firing once per page-load. That's very hard to speculate reasonably on without seeing more code. Never-the-less, here's an example I just threw together of how you can present the returned data in a more useful way.

The code requires that you download the AjaxRequest library I mentioned in an earlier comment. (http://ajaxtoolbox.com/request/)

Here, I demo a few principles.

  1. Arranging the data into a php class
  2. constructing an array of instances of this class
  3. returning this array as JSON
  4. catching the JSON text and turning it back into an object in JS
  5. Processing the data

I've given 2 very simple example - the first simply loads all filenames in the current directory (that holds jsonDir.php) into a select element. Choosing a filename results in it being copied into a text input next to the button.

The second, only retrieves names of png files. It chucks them all into a select element too. This time however, when an item is selected it is used as the src for an image. In each case the filenames are only grabbed if/when the corresponding button is pressed. There's a bit of redundant/otherwise crappy code I could have done better, but after 20 hours awake, I'm ready for bed!

code preview image

Hope it's useful for you. Any questions, just ask. :)

1. jsonDir.php

<?phpclassmFile{
    public$name, $time, $size;
}

if (!isset($_GET['wildcard']))
    $wildCard = "*.*";
else$wildCard = $_GET['wildcard'];

foreach (glob($wildCard) as$curFilename)
{
    $curFileObj = new mFile;
    $curFileObj->name = $curFilename;
    $curFileObj->time = date("d/m/Y - H:i", filectime($curFilename));
    $curFileObj->size = filesize($curFilename);
    $fileArray[] = $curFileObj;
}
printf("%s", json_encode($fileArray));
?>

2. readDir.html

<!DOCTYPE html><html><head><scripttype='text/javascript'src='script/ajaxRequestCompressed.js'></script><script>functionbyId(e){returndocument.getElementById(e);}
functionnewEl(tag){returndocument.createElement(tag);}

functionmyGetAjaxResponseWithCallback(url, target, callbackFunc)
{
  AjaxRequest.get(
    {
      'url':url,
      'onSuccess':function(req){ callbackFunc(req.responseText, target); }
    }
  );
}

functiongetResults1()
{
    var url = "jsonDir.php";
    var target = byId('resultsDiv');
    myGetAjaxResponseWithCallback(url, target, jsonDataReceived1);
}

functiongetResults2()
{
    var url = "jsonDir.php?wildcard=*.png";
    var target = byId('resultsDiv2');
    myGetAjaxResponseWithCallback(url, target, jsonDataReceived2);
}

functionjsonDataReceived1(responseText, targetContainer)
{
    var resultObject = JSON.parse(responseText);
    targetContainer.innerHTML = "";

    var mStr = "There were " + resultObject.length + " records returned" + "<br>";
    var mSel = newEl("select");

    mSel.addEventListener('change', doAutofill, false);

    var i, n = resultObject.length;
    for (i=0; i<n; i++)
    {
        var curRecordOption = newOption(resultObject[i].name, i);
        mSel.appendChild(curRecordOption);
    }
    targetContainer.innerHTML = mStr;
    targetContainer.appendChild(mSel);
}

functionjsonDataReceived2(responseText, targetContainer)
{
    var resultObject = JSON.parse(responseText);
    targetContainer.innerHTML = "";

    var mSel = newEl("select");
    mSel.addEventListener('change', showSelectedImg, false);

    var i, n = resultObject.length;
    for (i=0; i<n; i++)
    {
        var curRecordOption = newOption(resultObject[i].name, i);
        mSel.appendChild(curRecordOption);
    }
    targetContainer.innerHTML = '';
    targetContainer.appendChild(mSel);
}


functiondoAutofill(e)
{
    var curSelIndex = this.value;
    var curText = this.options[curSelIndex].label;
    byId('autofillMe').value = curText;
}

functionshowSelectedImg(e)
{
    byId('previewImg').src = this.options[this.value].label;
}

</script><style>img
{
    border: solid 2px#333;
}
</style></head><body><buttononclick='getResults1()'>Get *.* dir listing</button><inputid='autofillMe'/><divid='resultsDiv'></div><hr><buttononclick='getResults2()'>Get *.png dir listing</button><imgid='previewImg'width='100'height='100'/><divid='resultsDiv2'></div></body></html>

Solution 2:

Found out my problem. The query wasn't correctly being processed!

I had the variable $dam_text as the LIKE statement, when it should have been $dam:

<?php//connect to db stuff hereif (isset($_GET['dam_text'])) {
    $dam = $_GET['dam_text'];
    getSuggest($text);
}

functiongetSuggest($text) {

    $sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";

    $query = mysql_query($sqlCommand);

    $result_count = mysql_num_rows($query);

    while ($row = mysql_fetch_assoc($query)) {
        echo$row['name'].'<br />';
    }

}
?>

Also, the variable $dam wasn't being submitted inide the function, so I moved it from the 'if' statement, into the function:

<?php//connect to db stuff hereif (isset($_GET['dam_text'])) {
    getSuggest($text);
}

functiongetSuggest($text) {

    $dam = $_GET['dam_text'];

    $sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam%'";

    $query = mysql_query($sqlCommand);

    $result_count = mysql_num_rows($query);

    while ($row = mysql_fetch_assoc($query)) {
        echo$row['name'].'<br />';
    }

}
?>

The above code works perfectly! Turns out it wasn't onkeyup after all! Thanks for all your help!

Solution 3:

OnKeyUp will only fire once per event. pressing 'A' 'B' and 'C' will result in three calls to suggest1();

To make sure your browser is working correctly try this

<scripttype="text/javascript">functionsuggest1() {
     document.getElementById('myDiv').innerHTML = document.getElementById('dam').value;
 }
 </script><inputtype="text"name="dam"id="dam"onkeyup="suggest1();"><br /><divid="myDiv"></div>

You should see the div change for every keystroke that occurs in the input.

There is two many unknowns for me to directly point at your actual issue. Your PHP will output nothing for a zero entry query, and will only output 1 item if you query LIKE only matches one thing. I think your problem lies elsewhere, an not with onkeyup

T test to onkeyup on your system/browser: Try adding some debug header like echo strlen($text).'<br />'; to your PHP file. You should see the number change with out relying on your SQL query for every key press that adds or deletes text (that includes the backspace key).

Your code looks fine. And runs fine for me using the public HTTP GET echo service at http://ivanzuzak.info/urlecho/

Swapping out your PHP for the echo service works fine (with a bit of a typing delay)

<scripttype="text/javascript">functionsuggest1() {
    var dam_text = document.getElementById('dam').value;

    if (window.XMLHttpRequest) {
        xmlhttp = newXMLHttpRequest();
    } else {
        xmlhttp = newActiveXObject('MicrosoftXMLHTTP');
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
        }
    }
    var target = 'http://urlecho.appspot.com/echo?body=' + dam_text;
    xmlhttp.open('GET', target, true);
    xmlhttp.send();
}
</script><inputtype="text"name="dam"id="dam"onkeyup="suggest1();"><br /><divid="myDiv"></div>

Post a Comment for "Onkeyup Function Only Firing Once"