FarizHuseynli
FarizHuseynli

Reputation: 109

ASP textbox calls javascript function

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

Upvotes: 4

Views: 48355

Answers (5)

Bhanu Pratap
Bhanu Pratap

Reputation: 1761

<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... :)

Upvotes: -1

Canavar
Canavar

Reputation: 48088

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>

Upvotes: 3

Shivam Gupta
Shivam Gupta

Reputation: 427

You should use onKeyPress event to call the function.

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

Upvotes: 8

DLL_Whisperer
DLL_Whisperer

Reputation: 827

give it a try :)

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

Upvotes: 0

Anto king
Anto king

Reputation: 1222

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

Upvotes: 1

Related Questions