Question

I'm using struts. My ActionForm has an ArrayList set up within it, how can I access the array from the JSP that the ActionForm is sent to by the controller in jQuery on a button click. This is so I can loop through the elements of that array. I guess its something like this, but that is a stab in the dark (which isn't working).

$('myButton').click(function(){
    var myArrayToLoopThrough = $('myForm.myArray');
    for(){
        //looping stuff
    }
}
Was it helpful?

Solution

jQuery operates on the HTML generated by your JSP.

So have a look to the generated HTML in the browser using a tool like Firebug for Firefox.

Then you can use jQuery to select and iterate over HTML elements. Here are the basic syntax of the most useful stuff:

Select an ID: $("#id")

Select by class: $(".class")

Select by HTML tag: $("p") or $("span")

Iterate over a selection

$(...something...).each(function(){
   // this is the DOM element
   // $(this) is a jQuery object containing the DOM element
});

Official jQuery documentation on selectors


EDIT

Based on your comments, you seem to be looking for a way to communicate with server objects instead of generated HTML.

Javascript (jQuery is written in Javascript) is a web browser language that can only interact with generated HTML. Your Java objects are not sent to the browser.

If you do need to retrieve data from the server, then you need a new HTTP request in order to retrieve those data. This can be done in jQuery using the AJAX methods.

OTHER TIPS

You may want to check out .serializeArray(). You can get all the data from the form into a nice object so you can do what you want with the data.

jQuery .serializeArray() Documentation

var data = $('#form-id').serializeArray();

Now you can loop through data. The keys are name and value.

Is this what you're looking for?

$('.myButton').click(function(e) {
    var data = $(this).closest('form').serializeArray();
    for( var i = 0; i < data.length; i++ ) {
        var field = data[i];
        console.log( field.name + '=>' + field.value );
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top