How to create a loop in an onClick event?

I want to write an event onClickthat submits a form several times, iterating over the selected elements in a multiple-choice field, sending once for each.

How to encode a loop?

I work in Ruby on Rails and using remote_function()JavaScript to generate ajax call.

+3
source share
3 answers

My quick answer (since I haven't encoded it yet) was to create another function that creates a POST using XMLHTTPRequest and specific parameters for one call. Then inside the onClick () handler, you call this function when passing through the elements you have selected.

, " ", HTML- javascript, , RoR.

, , RoR?

+4

javascript. Rails - .

Prototype.js . : (UNTESTED)

<%= javascript_include_tag 'prototype' %>

<form id="my-form">
  <input type="text" name="username" />

  <select multiple="true" id="select-box">
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
    <option value="4">Fourth</option>
  </select>
</form>

<script type="text/javascript" language="javascript">
submitFormMultipleTimes = function() {
  $F('select-box').each(function(selectedItemValue){
    new Ajax.Request('/somewhere?val='+selectedItemValue, 
      {method: 'POST', postBody: Form.serialize('my-form')});
  });
}
</script>

<a href="#" onclick="submitFormMultipleTimes(); return false;">Clicky Clicky</a>

:

  • Prototype $F() .

  • Ajax.Request POST.
    ,

  • Form.serialize, .
    , ,

+2

DOM , , . (, , , =)

( ) POST.

, rails , ( !), javascript, .

, , DOM RJS : , .

You will also have the (large) advantage of only one round trip server instead of the few rides you will need using multiple POSTS.

+1
source

Source: https://habr.com/ru/post/1696851/


All Articles