1

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>

2 Answers2

1

This should do it:

...
$('#course_catalog').html(content);

$('#course_catalog').find('[id^=coursename_]').on('change', function(){ 
    var $this = $(this); 
    if($this.val() == 3){ 
        $('input[id^=new_course_]').each(function(index){
           var start = parseInt($('#course_increment_num').val(), 10);
           $(this).val(start+index);
       })
    }
});

You will also need to run that .each loop in your ajax success callback to ensure that the id is up to date

Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • Rob, `#course_increment_num` holds the initial value from the ajax call. When choosing option `Others-Not listed` will display a once hidden `
    ` with input `Course ID
    –  Dec 10 '13 at 23:35
  • Great! Its now almost coming together. Yes, now if the `#course_increment_num` changes it only updates the first. So you mentioned the `.each` loop. Do I need to add `$this.find('[id^="new_course_"]').next().val((num+i)+1);` to update all fields if `#course_increment_num` changes? –  Dec 11 '13 at 03:08
  • Just run the each exactly how it is in my answer right after $cloned.each in your Ajax success callback – Rob M. Dec 11 '13 at 03:38
  • Now one more issue sorry to be a hassle. if I choose `Other- Not listed` in select fields 1 and 2. Then go back and change the option for first select, the value for `#new_course_2` in second select field does not update. Do I need to clear the value? –  Dec 11 '13 at 03:58
  • Yeah, that should be an else statement in the if val == 3 portion – Rob M. Dec 11 '13 at 04:33
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/42910/discussion-between-techaddict82-and-rob-m) –  Dec 11 '13 at 05:17
  • Rob it has been a while but I am now running into different problem with a similar example. Please check question: http://stackoverflow.com/questions/21489518/cloning-removing-input-fields-keeping-element-id-unique#21489518 –  Jan 31 '14 at 21:36
0

You can store the value in a global variable in javascript and increment it every time Other - Not Listed is selected. Like this:

var globalValue = 0;
$(document).on('change', "[id^=coursename_]", function () {
    var $this = $(this);
    if ($this.val() == "3") {
        globalValue++;
        $(this).closest('div').find(".hideNewCourse").show();
    } else {
        $(this).closest('div').find(".hideNewCourse").hide();
    }
});
Ganesh Jadhav
  • 2,830
  • 1
  • 20
  • 32