Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struts2 JQuery how to do onchange ajax

Let's say I have sj:autocompleter like this :

<sj:autocompleter  id="idDistributor" 
name="idDistributor" 
list="%{idDistributorList}"  label="ID
Distributor"  indicator="indicator" />

when the value is changed, I'd like to pass the detail value to other text field like this :

<sj:textfield label="Nama Distributor" id="namaDistributor" name="namaDistributor" required="true"/>

where its value will be retrieved from struts back bean (FormAction).

How I could do this?

Really thanks in advance.

Mr.K

like image 494
Mr.K Avatar asked Aug 03 '10 17:08

Mr.K


2 Answers

The following will send the autocompleter value to your action and set the value of #namaDistributor with the returned string:

$('#idDistributor').change(function(){
    // Make the ajax request
    $.ajax({
        url: 'path/to/back-bean.action',
        data: "autocompleterValue=" + $(this).val(),
        dataType: "json",
        success: function(data) {    
            // Set the inputs from the json object            
            $('#namaDistributor').val(data.distributor);
            $('#namaPrice').val(data.price);
        }
    });
});

You can read more about the $.ajax() method here. The above json example assumes that your Action is creating a json object with the following format:

{"price": "123.40", "distributor": "XYZ Inc."} 

You can read more about using json with Struts2 in this article.

like image 172
Pat Avatar answered Nov 12 '22 14:11

Pat


you can do this with onSelectTopics.

Subscribe a topic like this:

<script>
$.subscribe('autocompleteSelect', function(event, data) {
  var ui = event.originalEvent.ui;
  $('#namaDistributor').val(ui.item.value);
});
</script>

and at it to your autocompleter

<sj:autocompleter  id="idDistributor" 
name="idDistributor" onSelectTopics="autocompleteSelect"
list="%{idDistributorList}"  label="ID
Distributor"  indicator="indicator" />

you can find an example for this in the Struts2 jQuery Plugin Showcase

like image 26
Johannes Avatar answered Nov 12 '22 13:11

Johannes