0

New to jQuery/JS... A few posts on Stackoverflow were helpful, but i could not trigger the change function once the get.URL function runs.

I am trying to create a simple page with a pulldown that filters. I also want this pulldown to have the ability to preselect an option based on a value in URL watch=Cat1

Here's the code for the select:

<select name="watch" id="watch">
<option value="All">All news</option>
<option value="Cat1">Category 1</option>
<option value="Cat2">Category 2</option>
<option value="Cat3">Category 3</option>

Here are my scripts:

<script>
  //Filter News
  $('select#watch').change(function() {
    var filter = $(this).val()
    filterList(filter);
  });

  //News filter function
  function filterList(value) {
    var list = $(".news-list .news-item");
    $(list).fadeOut("fast");
    if (value == "All") {
      $(".news-list").find("article").each(function(i) {
        $(this).delay(200).slideDown("fast");
      });
    } else {
      //Notice this *=" <- This means that if the data-category contains multiple options, it will find them
      //Ex: data-category="Cat1, Cat2"
      $(".news-list").find("article[data-category*=" + value + "]").each(function(i) {
        $(this).delay(200).slideDown("fast");
      });
    }
  }

</script>
<script>
     function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
var val = getURLParameter('watch');
$('#watch').val(val);   //  assign URL param to select field
    ('select#watch').trigger("change");}
    </script>

I am able to select the correct option based on the URL parameter, however, the select box no longer updates the page according to the selection.

Thank you in advance, Udi

udis
  • 29
  • 6
  • https://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url – jtate Apr 19 '18 at 14:48
  • 1
    Assigning a new value via script does _not_ trigger the `change` event, you’ll have to explicitly do that (.trigger()) in this instance. – CBroe Apr 19 '18 at 14:51
  • @CBroe, can you please elaborate? Can you please provide me with an example? Thank you! – udis Apr 19 '18 at 15:10
  • i tried $(selector).trigger("change"); ... it's changing the selector, but the display isn't accurate. – udis Apr 19 '18 at 15:17

0 Answers0