I have a list as shown below.
Now I want to get the values of each radio button when clicking on it. However, I get always the first value since the IDs (list-name) will be the same when rendered out the list.
Is there a simple way to do so? Maybe with onclick=function(this)
<form id="form-1">
{% for u in user %}
<li>
<div>
<input id="list-name" type="radio" value="{{ u.name }}" name="list-radio">
<label for="list-name">{{ u }}, {{ u.name }}</label>
</div>
</li>
{% endfor %}
</form>
<script>
$(document).on('change', '#form-1', function (e){
console.log($('#list-name').val())
}
</script>
2
Answers
The attribute
id
is unique in a document. Useclass
instead. Also usethis
keyword to refer the currently clicked element.Updated Code:
Demo:
Now that these are radio buttons that at grouped by their name you can get the current value of the radioNodeList by its name on the form (
form.list_radio.value
).Don’t use hyphens in id or name values. If you feel like it, use underscore instead.