简体   繁体   中英

Onchange in Struts2 textfield

I want to get all records from DB to JSP based on a string what I enters in S2 textfiled. While typing in textfiled only I want to get those all records as a table in JSP.

Ex:

In textfiled, while I typing 'a' then I want to display all records which are matched with typing character 'a'. Suppose in my DB, I've some values with column 'name' as 'abc','def','bac','dea',etc. Then I want to get all the rows with column value 'abc','bac', and 'dea' from DB. It's exacly like onchange event in HTML. Here I can query like ' select name from tablename where name like%a% '.

So in JSP,

   No     Name     Address
  -------------------------
   1      abc      addrs1
   2      bac      addr2
   3      dea      addr3

while I tried with

<s:textfield label="Search" name="keyword" id="keyword" onchange="search()"/>

It didn't work.

While I tried with

<s:textfield label="Search" name="keyword" id="keyword" onkeypress="search()"/>

Its also exactly not working. Here onkeypress event mechanism working. After typing 'ab' only value 'a' will be send to action class. Ok. Is there any other way to do this.

$.getJSON('/test/giveMeJsonData.action ',{cartId: cartId},function(json){
    itemsHtml = "<table>";
    for (i in json.items) {
        itemsHtml += "<tr>";
        itemsHtml += "<td>" + json.items[i].id + "</td>";
        itemsHtml += "<td>" + json.items[i].name + "</td>";
        itemsHtml += "<td>" + json.items[i].address + "</td>";
        itemsHtml += "</tr>";
    }
    itemsHtml += "</table>";
    $('#cartItems').html(itemsHtml);
});

Try onkeyup , it will call JavaScript when key up is performed:

<s:textfield label="Search" name="keyword" id="keyword" onkeyup="search()"/>

JS Bin demo


 function myFunction() { var x = document.getElementById("searchText").value; alert(x); } 
 <input type="text" id="searchText" onkeyup="myFunction()"> 

The widget you are talking about is called autocompleter (that is, guess what, a textfield with autocompletion fired by keyboard events).

You can easily achieve this with javascript widgets (eg. jQuery autocompleter ), and in Struts2 you can also opt for the struts2-jquery-plugin's Autompleter .

In Action, return a List or an array:

public String[] getMyList() {
    return myList;
}

In JSP, use it like this:

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
  <head>
    <sj:head jqueryui="true"/>
  </head>
  <body>
   <sj:autocompleter list="%{myList}"/>
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM