I have a form which has three inputs when the page loads — 2 select boxes and 1 text box.
I have created an AJAX call which will populate the second select box depending on what the user picked in the first select box. I also have a button which will append the very same input fields with unique names and ids to the form.
The problem I am having is trying to figure out which select box has been changed. As of now when the page loads I can select an option and populate the second select box but when I append another set of input fields and choose from the second select box it does not populate the corresponding select box.
If I select from the select box which is displayed when the page loads instead of populating its corresponding select box, it populates the newly appended select box.
Here is the code:
$(document).ready(function() {
var i = $('.clonedInput').length;
var count = 2;
$('#prescriptions'+i).change(function() {
alert(i);
var value = $(this).val();
var dataString = 'prescription='+value;
$.ajax ({
type: 'POST',
url: '<?php echo base_url(); ?>index.php/patients/dynamic_ddl',
data: dataString,
cache: false,
success: function(html) { $('#dosage'+i).html(html); }
});
});
$(function(){
$('#btnAdd').click(function(){
$('#page_properties').append('<tr id="input'+count+'" class="clonedInput">'+
'<td><label for="prescriptions'+count+'">Prescription</label></td>'+
'<td><select id="prescriptions'+count+'" class="prescriptions" name="prescriptions'+count+'">'+
'<option selected="selected">--Select Prescription--</option>'+
'<?php foreach ($prescriptions_sel as $option):?>'+
'<option value="<?php echo $option['prescription']; ?>"><?php echo $option['prescription'];?></option>'+
'<?php endforeach ?></select></td>'+
'<td>Dosage: <select id="dosage'+count+'" name="dosage'+count+'" class="dosage">'+
'<option selected="selected">--Select Dosage--</option>'+
'</select>'+
'Add Dosage: <input type="text" name="new_dosage'+count+'" value="" /></td></tr>');
$('#btnDel').removeAttr('disabled');
count++;
i++;
});
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').removeAttr('disabled');
// if only one element remains, disable the "remove" button
if (num-1 == 1) $('#btnDel').attr('disabled','disabled');
count--;
i--;
});
$('#btnDel').attr('disabled','disabled');
});
I have been at this for hours, trying this with if statements, for statements, foreach statements (you name it).
Not quite sure if I’m following what you mean, but it sounds like your events only fire on items that exist when the document is ready, and not those items added dynamically.
If so, and your problem is on your change function, the you need to use the live function to bind your events rather than the change function. i.e.
needs to be