1

So I have a script that appends strings to the url when (1) the page is loading and (2) when onchange is invoked. The problem is the browser keeps on triggering the change event nonstop. How do I make it to trigger once when the page is loaded?

  <script>
    $(document).ready(function() {
      $("#staff-list").on('change', function() {
        location.href = "?account=" + $(this).val();
      }).triggerHandler('change');
    });
  </script>

  <div class="input-group mb-3">
    <span class="input-group-addon gi data-gi-size gi-user-add"></span>
    <select id="staff-list" name="staff-list">
       <Option>1</Option>
       <Option>2</Option>
    </select>
  </div>
ubuntujavy
  • 55
  • 6

2 Answers2

0

Please remove the triggerHandler('change')

 <script>
    $(document).ready(function() {
      $("#staff-list").on('change', function() {
        location.href = "?account=" + $(this).val();
      });
    });
  </script>

This is causing the infinite looping.

Update You can put some recursion exit condition. That is passing an extra parameter to the location.href and don't fire triggerHandler if the parameter is there.

Amr ElAdawy
  • 3,663
  • 5
  • 31
  • 48
0

You need to make a condition in if statement to stop the infinite redirect loop.. try this

<script type="text/javascript">
  $(document).ready(function () {
     $("#staff-list").on('change', function() {
      var AddToUrl = "?account="+ $(this).val();
      if(window.location.href.indexOf(AddToUrl) == -1) {
       window.location.href = AddToUrl;
      }
     }).change();
  });
</script>

<div class="input-group mb-3">
    <span class="input-group-addon gi data-gi-size gi-user-add"></span>
    <select id="staff-list" name="staff-list">
       <Option>1</Option>
       <Option>2</Option>
    </select>
</div>
Mohamed-Yousef
  • 22,772
  • 3
  • 17
  • 27
  • Cool..it works. Thanks, Mohamed. I'll accept your answer. I also noticed that the page is refreshing/reloading. How do we make it without page reloading? – ubuntujavy May 17 '17 at 06:20
  • @ubuntujavy Without page reloading .. you will need to work with history API .. to `pushState` / `replaceState` you can read about it here https://developer.mozilla.org/en-US/docs/Web/API/History_API .. and you can take a look at http://stackoverflow.com/a/4843248/3385827 – Mohamed-Yousef May 17 '17 at 06:24