4

I have a search textbox in asp. And I want it to send request to the server each time the text is changed there. I have a javascript function which sends request but it is not being called each time when I type something in the text box. How can I call javascript function from ASP textbox?

That is my textbox:

<asp:TextBox ID="search" name="Search" runat="server" onchange="javascript:text_changed();"></asp:TextBox>

That is my js function:

function text_changed() {
     searchedword = document.getElementById("ContentPlaceHolder1_search").value;
     SendRequest();
}
1
  • Paste your code for SendRequest - How is this accessing the search term? Commented Jul 17, 2014 at 7:50

5 Answers 5

8

You should use onKeyPress event to call the function.

<asp:TextBox ID="search" name="Search" runat="server" onKeyPress="javascript:text_changed();"></asp:TextBox>
Sign up to request clarification or add additional context in comments.

1 Comment

onKeyPress and onKeyUp - it seems the value is one behind what you typed in the key press but matches exactly in the key up.
3

Shivam's answer is right. You can use KeyPress event to get users key strokes with that event.

But i want to inform you, you should not use ASP.NET control ids like that :

document.getElementById("ContentPlaceHolder1_search").value;

Because you'll get errors if you put your textbox somewhere else in html hierarchy, ASP.NET regenerates it's id.

Try that one, instead :

function text_changed(textObj) {
     searchedword = textObj.value;
     SendRequest();
}

<asp:TextBox ID="search" name="Search" runat="server" 
  onKeyPress="javascript:text_changed(this);"></asp:TextBox>

Comments

1

The functionality you asking can achieve by

Use onkeyup or onkeydown instead.

This will then run the function when you type or click on the textbox. You can also then detect the keycode of the event, and prevent the function if you dont want it to run for certain keys.

Use the below code

    $("#search").keydown(function(){
    text_changed();
  });
  $("#search").keyup(function(){
    text_changed();
  });

Demo Here

Comments

0

give it a try :)

$("#search").change(function(){
      //your ajax codes
});

2 Comments

The user didn't state that they were using jQuery, so this won't help him (unless he/she does).
how would i know that :)
-1
<script>
function multy(val)
{
alert(val.value+"--"+val.id);
}
</script>
<input id="txtdemo" type="text" onchange="multy(this);"></br>
<input id="txtdemo" type="text" onchange="multy(this);">
</input>

Click to see out put screen

Thanks... :)

1 Comment

he is expecting to be done with asp.net textbox control, because he might have some events already written with the control

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.