I want to add a select field when clicking a button. The values of options are $all_cs, created by Yii Framework (about 7k items).
<div class="cos-input">
<div id="cos_container"></div>
<span class='add-input cs_name' href="#" name="cs_name" onclick='addFields_cos()' style="border: solid 1px; padding: 3px;">Add COURSES</span>
</div>
The option element content:
$all_cs = $form->dropDownList($model, 'cos[n]', $allCourses, array('prompt'=>''));
$pos = strpos($all_cs, "<option");
$rpos = strrpos($all_cs, "</option>");
$all_cs = substr($all_cs, 0, $rpos+9);
$all_cs = substr($all_cs, $pos, strlen($all_cs) - $pos);
$all_cs = str_replace("\n", "", $all_cs);
I used 2 ways:
1 - Using JS:
function addFields_cos(){
var cos_container_parent = document.getElementById('cos_container');
var div = document.createElement("div");
div.name = "div_rm";
cos_container_parent.appendChild(div);
var new_cos = document.createElement("select");
new_cos.name = 'new_courses[]';
div.appendChild(new_cos);
new_cos.innerHTML = '<?php echo $all_cs; ?>';
div.innerHTML += "<span class='delete_div' href='#'> delete </span>";
div.appendChild(document.createElement("br"));
div.appendChild(document.createElement("br"));
}
2 - Using Jquery:
$(document).ready(function(){
$(".cs_name").click(function(){
$("#cos_container").append("<div><select name='new_courses[]'>");
$("#cos_container").append("</select></div><br>");
$("#cos_container select").append("<?php echo $all_cs; ?>");
});
});
When using JS, the field was added very fast and the time is constant when adding multiple fields.
But when using JQuery, the field was added slower, and as many fields as slower. When the number of fields is over 10, that need a few second to completed.
I the answers for:
1 - Why is using JQuery slower and not constant when adding multiple fields?
2 - How to change my JQuery function to make it is faster? Should do we use JQuery in this case?
(Sorry, my English is bad)