0

I am creating an live search for my blog..i got this from w3 schools and i need to add on keyboard up,down mouse up and down event ...

<html>
<head>
<script type="text/javascript">
function showResult(str)
{
if (str.length==0)
  {
  document.getElementById("livesearch").innerHTML="";
  document.getElementById("livesearch").style.border="0px";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<input type="text" size="30" onkeyup="showResult(this.value)" />
<div id="livesearch"></div>
</form>

</body>
</html> 

3 Answers 3

1

Just add it into the element:

<input onkeyup="showResult(this.value)" onkeydown="showResult(this.value)" type="text" size="30" />
Sign up to request clarification or add additional context in comments.

Comments

0

I use <input type="text" onkeypress="doThings();" onkeydown="doThings();"/>

For handling mouse use onmousedown and onmouseup events.

Comments

0

Learn using a Javascript library (such as jQuery). Handling events manually is a pain, because half the code you will have to write will be compatibility wrappers for various browser inconsistencies. Adding a keydown handler to an element with id foo in jQuery is as simple as

$('#foo').keydown(function() {
  // do stuff
});

Edit: The same is true for AJAX. The code you pasted in the question would look something like this in jQuery:

function showResult(str) {
  if (str.length==0) {
    $('#livesearch').html('').css('border', 0);
    return;
  }
  $.get('livesearch.php', {q: str}, function(data) {
    $('#livesearch').html(data).css('border', '1px solid #A5ACB2');
  });
}

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.