Reputation: 37
Only the first row is updating.. I was able to create a dynamically created select tags and button but every time I were to choose to the drop down, only the first row is being updated and the other rows will alert only "choose first" even though i already selected an option.
jquery func'
$('input').each(function(){
if($(this).attr("type")=="button"){
$(this).click(function{
var empid=$('#emp').val();
var job=$('#jobselect').val();
if(job !== "NULL"){
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>userskills/update",
data:{'Emp_ID':empid,'Job':job},
cache: false;
success:
function(data){
alert("Updated!");
}
});
}else{
alert("Choose first");
}
});
}
});
this is my tbody in the table
<tbody>
<?php foreach($job as $temp): ?>
<tr>
<td><?php echo $temp->Name?></td>
<td><?php echo $temp->Group?></td>
<td><?php echo $temp->Section?></td>
<td>
<select id="jobselect">
<?php foreach($roles as $role): ?>
<option value="<?php echo $role->RoleID">"><?php echo $role->RoleName?></option>
<?php endforeach; ?>
</select>
<input type="hidden" id="emp" value="<?php echo $temp->JobID?>" />
<input type="button" id="update"/>
</td>
</tr>
<?php endforeach; ?>
</tbody>
Upvotes: 2
Views: 710
Reputation: 150040
The id
attribute is supposed to be unique within the document, so your current code creates invalid HTML. The browser won't be too bothered by it and will display your elements anyway, but then in JS if you select by element ID (like '#jobselect'
) you only get back the first element with that ID.
You should switch to use a common class
instead, and then in your JS use DOM navigation to get from the clicked button (referenced by this
) to its related controls using .closest()
to get the containing td
element and then .find()
to get the items within that td
:
$('input[type="button"]').click(function(){ // no need for .each()
var container = $(this).closest('td'); // 1. get common parent element
var empid = container.find('.emp').val(); // 2. note the use of .find() with
var job = container.find('.jobselect').val(); // class selectors here
if (job !== "NULL") {
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>userskills/update",
cache: false;
success:
function(data){
alert("Updated!");
}
});
} else {
alert("Choose first");
}
});
<tbody>
<?php foreach($job as $temp): ?>
<tr>
<td><?php echo $temp->Name?></td>
<td><?php echo $temp->Group?></td>
<td><?php echo $temp->Section?></td>
<td>
<select class="jobselect">
<?php foreach($roles as $role): ?>
<option value="<?php echo $role->RoleID">"><?php echo $role->RoleName?></option>
<?php endforeach; ?>
</select>
<input type="hidden" class="emp" value="<?php echo $temp->JobID?>"
<input type="button" class="update"/>
</td>
</tr>
<?php endforeach; ?>
</tbody>
Note that you don't need the .each()
loop at all if you change your selector to just get the input elements that are buttons.
Upvotes: 0