Sorry for asking the question that has been asked so many times before. But I could not find a correct solution that solves my problem. So please consider this as a followup.
I have a button (#addNewElement
) that adds an input field and a select dropdown on click. I have attached autocomplete
function for the text input field. But the problem is, whenever I change one of the inputs of any of the fields, all of them get changed too. Why are all of them changing together? What am I missing here?
$("#addNewElement").click(function() {
$('#addElement').append("<div>\n\
<label class='form-name'>Element name: </label>\n\
<input type='text' name='element_name[]' id='element_name' class='eName'>\n\
</div>\n\
<div>\n\
<select name='formulation[]' id='formulation'>\n\
<option value=''>Select Formulation</option>\n\
</select>\n\
</div>");
$(".eName").autocomplete({
source: 'search.php',
select: function(event, ui) {
$(".eName").val(ui.item.value)
}
});
});
Also, I have an on change function attached to these input fields. This on change function works fine with the static field, but when comes to the dynamically added fields, it doesn't work. (I have included this section because I think they are related to the same problem).
$('.eName').change(function() {
if ($(this).val() != '') {
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if (action == "element_name") {
result = 'formulation';
} else {
result = 'strength';
}
$.ajax({
url: "fetch.php",
method: "POST",
data: {
action: action,
query: query
},
success: function(data) {
$('#' + result).html(data);
}
})
}
Are these two problems connected? How should I overcome these? Thanks in advance for your suggestions.