开发者

Store specific value in javascript when multiple forms are present

I've got a list of 10-20 objects on each page creating these forms:

<div id="routeTable">
  {% for route in route_list %}
  <div id="routeDone">
    <form class="doneForm" action="/route/complete/" method="post">
      <input type="hidden" name="route_id" value="{{ route.route_id }}" />
      <input type="hidden" name="next" value="{{ request.get_full_path }}" />
      <input type="submit" value="Done" class="doneButton" />
    </form>
  </div>
  {% endfor %}
</div>

And I'm trying to add some jquery to the page in order to intercept the usual form submit and instead do so using ajax as below. (I already have a view that returns an html chunk which will be swapped out for the above div#routeTable. The problem is line 4 "var route_ID...":

<script>
$(document).ready(function() {
  $(".doneForm").submit(function() {
    var route_id = $(this).attr('input[name=route_id]').val()

    $.ajax({
      type: "post",
      url: "/route/complete/",
      data: route_id,
      success: function(data) {
        $("#routeTable").html(data);
      }
    });
  return false;
  });
});
</script>

Unfortunately I'm having tro开发者_如何学编程uble passing the proper route_id into the js variable named route_id. I expect it will require use of the 'this' keyword, but I haven't been able to figure out exactly how.

Any suggestions on how to fix up my javascript would be greatly appreciated.


Try to change

var route_id = $(this).attr('input[name=route_id]').val()

to

var route_id = $(this).find('input[name=route_id]').val()

The reason being that input[name=route_id] is not an attribute, but a selector that represent a tag input and an attribute on that tag [name=route_id].

You could also do

var route_id = $('input[name=route_id]',this).val()


var route_id = $(this).attr('input[name=route_id]').val()

Should be something like:

var route_id = $(this).find('input[name=route_id]').val()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜