0

I created dynamic add and remove drop-down list. It works fine until the php code that passed by Javascript is commented out.

View.php

<div class="form-group">
    <label>Cara Pengolahan</label>
    <select class="form-control" id="pengolahan" required>
        <option value="">No Selected</option>
        <?php foreach($pengolahan as $row):?>
           <option value="<?php echo $row->id_pengolahan;?>"><?php echo $row->cara_pengolahan;?></option>
        <?php endforeach;?>
    </select>
</div>
<div class="input_fields_wrap">
    <input type="button" class="btn btn-info add_field_button" value="Tambah Cara Pengolahan"/> <br/><br/>
</div>

Javascript.js

$(document).ready(function() {
var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
        $(wrapper).append('<div class="form-group">' +
                            '<select class="form-control" style="width:95%; display:inline-block; margin-right:10px;" id="pengolahan[]" name="pengolahan[]" required>' +
                                '<option value="">No Selected</option>' +
                                '<?php foreach($pengolahan as $row):?>' +
                                    '<option value="<?php echo $row->id_pengolahan;?>"><?php echo $row->cara_pengolahan;?></option>' +
                                '<?php endforeach;?>' +
                            '</select>' +
                            '<button class="btn btn-danger closebtn remove_field"><b>&times</b></button>' +
                          '</div>'); //add input box
    }
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
})
});

When I run the page and I view the source code it shows : Result Debug

Why is it being commented out?

1 Answers1

0

Perhaps more helpful is a solution:

add this to your view.php file:

<div class="form-group">
  <select class="form-control" style="width:95%; display:inline-block; margin-right:10px;" id="pengolahan[]" name="pengolahan[]" required>
    <option value="">No Selected</option>
    <?php foreach($pengolahan as $row):?>
    <option value="<?php echo $row->id_pengolahan;?>"><?php echo $row->cara_pengolahan;?></option>
    <?php endforeach;?>
    </select>
    <button class="btn btn-danger closebtn remove_field"><b>&times</b></button></div>

then in your css set display=none and finally, you can turn it back on in your js

DCR
  • 14,737
  • 12
  • 52
  • 115