I have a table like below-
the code of this table in my view is as following-
<table class="table table-bordered"> <tr> <td>Course Name</td> <td>Class</td> <td>Subject Name</td> <td>Month</td> <td>View</td> </tr> <?php if(!empty($data)) { $i=1; foreach($data as $key => $value) { ?> <tr> <td><?php echo $value->course_name; ?></td> <td><?php echo $value->class_name; ?></td> <td><?php echo $value->subjectName; ?></td> <td><select class="form-control" id="month" data-parsley-required="true" data-parsley-error-message="Please Select Class"> <option value="" hidden="hidden">Select Month</option> <option value="1">January</option> <option value="2">Febuary</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> </td> <td> <button id="<?php echo $i;?>" class="form-control" data-eid="<?php echo $this->session->userdata('e_id');?>" data-subjectid="<?php echo $value->subjectId;?>" data-courseid="<?php echo $value->course_id;?>" data-classid="<?php echo $value->class_id;?>"> View</button></td> </tr> <?php $i++; } } ?> </table>
//javascript
<script type="text/javascript"> $('button').on('click',function(){ var eid = $(this).data('eid'); var subId = $(this).data('subjectid'); var courseId = $(this).data('courseid'); var classId = $(this).data('classid'); var month = $('#month').val(); if(month == '') alert("Select Month"); else { alert("okay"); } </script>
Whenever I select month
and click the view
button the page is redirected correctly, but when I select month
in the second row and click the view
button again it gives alert select month
.
I don’t know how to differentiate all the dropdowns based on a name.
Advertisement
Answer
The issue is because you’re repeating the same id
attributes in the elements you create in the loop. These need to be unique within the DOM.
To fix the issue you need to change the id
to class
. Then you can use jQuery’s DOM traversal methods to find the month select
which is in the same row as the button which was clicked. To do that use closest()
to get the parent tr
, then find()
:
<select class="form-control month" data-parsley-required="true" ... >
$('button').on('click', function() { var eid = $(this).data('eid'); var subId = $(this).data('subjectid'); var courseId = $(this).data('courseid'); var classId = $(this).data('classid'); var month = $(this).closest('tr').find('.month').val(); if (month == '') alert("Select Month"); else alert("okay"); });