I have an object named data2
contains multiple data that I’m rendering from views.py to my HTML template.
{% for item in data2 %}
<tr>
<td><input type="text" name="from" class="form-control input_data" value="{{item.from_age}}"></td>
<td><input type="text" name="to" class="form-control input_data" value="{{item.to_age}}"></td>
<td id ="gender_select">
<script>$(function() {$('#gender_select :input').each(function() {
$("#gender option[data-value='" + '{{item.gender}}' +"']").attr("selected","selected");
});});</script>
<select name="gender" id="gender" class="form-control input_data" >
<option data-value="select" >Select</option>
<option data-value="male" >Male</option>
<option data-value="female" >Female</option>
</select>
</td>
<td><a href='' class='remove'><span class=''></span></a></td>
</tr>
{% endfor %}
In {{item.gender}}
, on the first iteration, I have value ‘Male’ and on the second iteration, I have value "Female" so it should be automatically select the value but
after executing the above code, I’m facing an error $ is not defined
also can’t see the values.
Please let me know where i’m wrong ?
2
Answers
it seems that yours is a javascript error, make sure you import jquery in the header before any other js script
I would also recommend you move the script tag outside the for loop because you end up with the multiple scripts doing the same thing.
There is also an easier method to set value of a select tag Checkout this answer
[Edit]
This is how i would approach it
You should put your jquery code inside the following code block:
This will ensure that your code is only loaded after the initialization of jquery.
Also double check your jquery script is being called correctly.