I am trying to add values to a select field dynamically if there not listed. I have dynamic fields generated through jquery. I am populating these select field values through mysql fetch query from table courses_selection_list
. Each select field generated has three options. I have a hidden div show only if option Other – Not listed
is selected. The input in the hidden div shows a unique id number value I pull from an ajax call. I am now having difficulties trying to increment the value by one every time Other – Not listed
is selected in different select fields. How can I increment this intial value by one? DEMO or Fiddle
<script">
$(document).ready(function () {
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
var $increment_num = $('#course_increment_num');
var interval = 1000; //3000 = 3 seconds
function getCourseId() {
$.ajax({
type: 'POST',
url: 'courseAutoIncrement.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
var $cloned = $('#course_catalog');
var num = parseInt(data);
$increment_num.val(num);
$cloned.each(function(i){
var $this = $(this);
$this.find('[name^="new_course_"]').first().val(num+i);
})
},
complete: function (data) {
// Schedule the next
setTimeout(getCourseId, interval);
}
});
}
setTimeout(getCourseId, interval);
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list"><option value="" >--- Select ---</option>"'
<?php
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list ");
$course_query->execute();
$data = $course_query->fetchAll();
foreach ($data as $row){
//dropdown values pulled from database
echo 'content += \'<option value="' . $row['course_id'] .'">' . $row['course_name'] . '</option>\';';
}
?>
'"';
content += '</select><div class="hideNewCourse" style="display:none;">Course ID<input type="text" id="new_course_'+i+'" name="new_course_'+i+'"/><label for="newCourse_'+i+'">Add Course Name to List:</label><input type="text" id="newCourse_'+i+'" name="newCourse_'+i+'"/></div></div>';
}
$(document).on('change', "[id^=coursename_]", function () {
var $this = $(this);
if ($this.val() == "3") {
$(this).closest('div').find(".hideNewCourse").show();
} else {
$(this).closest('div').find(".hideNewCourse").hide();
}
});
$('#course_catalog').html(content);
}
});
</script>
HTML
Increment By: <input type="text" id="course_increment_num" value="" readonly></br>
<strong>How many courses offered?</strong>
<select name="courses_offered" id="courses_offered">
<option value="default">---Select---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="course_catalog"></div>