puranjan
puranjan

Reputation: 373

My Select tag's 1st option is not working but my other options works nicely

I created a Select Field, so that when user clicks the options , it will send it to its respective page using location.href in js.

<select onchange="filter_category(this)" id="category">

   <option value="0">All</option>

       {% for cat in catg  %}
          <option  value={{cat.id}}>{{cat.name}} </option>
       {% endfor %}
                    
</select>

Javascript:

<script>
    function filter_category(elem){
        alert(elem)
        location.href="/market?id="+elem.selectedIndex + "&category=" + elem.selectedOptions[0].innerText
    }
</script>

The problem here is , that only my 1st option is not working according to my filter_category() function. When I click on 1st option in select field, it does nothing. But all my other options are working properly and transfer me to their respective page. I cant find why this is happening.

The alert function I added in the filter_category() function is also not working when I click my 1st option.

Upvotes: 0

Views: 877

Answers (2)

puranjan
puranjan

Reputation: 373

Changing HTML did the trick as suggested by @Ezani.The first option was selected by default on every page refresh , so onchange function wasn't working on it.

Here is the code:

<select onchange="filter_category(this)" id="category">
<option value="none" selected disabled hidden> Select an Option </option>

<option value="0">All</option>

{% for cat in catg  %}
<option  value={{cat.id}}>{{cat.name}} </option>
{% endfor %}
                        
</select>

Upvotes: 0

Ezani
Ezani

Reputation: 557

This is the offending line:

 <option value="0">All</option>

You've made this the first selection in your list of option selection and so it does not give you a valid Cat ID or Cat Name. You can perhaps exclude it from your options list.

Upvotes: 1

Related Questions