0

In the snippet below, $modal is undefined because there are multiple form instances.

<script type="text/javascript">
  $(document).ready(function() {
    var $modals = $(".update-form");
    var $form = $("#program-update-form-{{ form.instance.uuid }}");

    $modals.on("hide.bs.modal", function() {
      $form.trigger("reset");
    });

  });
</script>


<html>
  {% for id in form.instance.uuid %}
    <div id="program-update-modal-{{ form.instance.uuid }}" class="update-form">
  {% endfor %}
</html>

I think what I'm wanting to do is here is gather all program-update-modals and trigger a reset on the hide.bs.modal action. The number of form instances is going to be dynamic and obviously the uuid's will be dynamic so I need to know how in jQuery to just grab all the div id's beginning with 'program-update-modal-'. Open to other suggestions as well.

6
  • When/how is "hide.bs.modal" triggered? This isn't a standard event Commented Nov 20, 2020 at 18:57
  • This is precisely what classes are for. Add a class name to the elements you'd like to group. Commented Nov 20, 2020 at 18:58
  • @Dropout if I use the class name, will $modal.on() line still work? Commented Nov 20, 2020 at 19:06
  • @BenjaminDonnaloia it should IMO.. $modal.on(...) binds the event handler onto the element. If you change the selector to a class selector, i.e. $(".some-class") it should bind the event to each of the elements. Commented Nov 20, 2020 at 19:09
  • @Dropout, I have updated the OP with your suggestion, does this look like what you are saying? Commented Nov 20, 2020 at 19:12

3 Answers 3

1

Use the built in starts with selector. https://api.jquery.com/attribute-starts-with-selector/

var divs = $("div[id^='program-udpate-modal']");
Sign up to request clarification or add additional context in comments.

Comments

0

For collecting all the divs with the common ID pattern, just query for all DIVs and then filter, then iterate over them all and put them namewise into a Javascript object

var PUMDivs = {}

var divs = $("DIV").filter(function(elem) {
  return elem.id.indexOf("program-update-modal-") == 0;
}).each(function(idx, elem) {
  PUMDivs[this.id.substring("program-update-model-".length)] = elem;
});

Comments

0
var $form = $("[id^=program-update-form-]");

$modals.on("hide.bs.modal", function() {
  $form.trigger("reset");
});

To get all the elements starting with "program-update-form-" you should use:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.