bragboy
bragboy

Reputation: 35542

Having multiple buttons in a page

I am having many submit buttons one for each row in a table. Whenever I click on that button, an Ajax call should be triggered. Right now I am wrapping each button inside a form tag. Is this a good approach? If not, what is a better way to do this.
Moreover, I will be replacing the button eventually by an image.

Please advise on how to handle this situation.

http://img269.imageshack.us/img269/2077/88405759.png

Upvotes: 2

Views: 220

Answers (5)

Quentin
Quentin

Reputation: 943645

Right now I am wrapping each button inside a form tag. Is this a good approach?

Yes, this is fine.

The only problem is that the HTML is a little on the chunky side, but that issue is largely eliminated by gzip compression (since there will be a lot of duplicate tokens, which are highly compressible).

In its favour, the method is very simple to implement, very hard to go wrong, and doesn't depend on the user having JavaScript turned on.

You can then, with very little effort, enhance the forms with onsubmit events to use JavaScript to send the data using Ajax and cancel the normal submission of the form.

Moreover, I will be replacing the button eventually by an image.

I would generally try to avoid that. A button is a clear indicator that it is something clickable that will do something. If you really want to, you can substitute the submit input for an image input.

Upvotes: 3

karim79
karim79

Reputation: 342655

You can unobtrusively bind a function to a set of elements like this:

<script>
var anchors = ​document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
    anchors[i].onclick = function() {
        alert(this.id);
        // do ajax call
        return false; 
    }
}​​​
</script>

​<a id="test" href="#">Test</a>
<a id="tes2t" href="#">Test2</a>​

Upvotes: 2

Sir Hally
Sir Hally

Reputation: 2358

You should use

<input type="button" onclick="AjaxFunction()"> 

where AjaxFunction() is a function which makes ajax-request. The form tag and submit buttons is need not for Ajax requests.

And, by the way, you can use images instead of buttons. Something like this

<img src="url" alt=""  onclick="AjaxFunction()" />

Upvotes: 1

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

You should create one form and put all submit buttons into it. Buttons should have different names.

Upvotes: 0

fabrik
fabrik

Reputation: 14365

Why not create one big form then differentiate the buttons with their (or other) ids?

Upvotes: 0

Related Questions