<script type="text/javascript">
var count = 0;
var max = 5;
$(function(){
$('p#add_field').click(function(){
count += 1;
if(count >= max)
return;
$('#container2').append(
'<strong>Golf Course ' + count + '</strong>   '
+'<select id="field_' + count + '" name="fields[]">' + "<?php foreach ( $courses as $course ) { $name = $course->coursename; ?>"+"<?php echo '<option value=\''.htmlspecialchars($name).'\'>'.$name.'</option>'; ?>"+"<?php } ?>"+'</select><br />')
});
});
</script>
それでも、あなたのコードは非常に保守が難しく、PHP を JS から分離する必要があります。
編集:この解決策も検討してください:
// this way you provide a JSON serialization of your server data
<script type="application/json" id="select-data">
<?php echo json_encode($courses); ?>
</script>
// this is pure js: doesn't care where the data comes from
<script type="text/javascript">
$(function(){
// we parse the JSON string, and get a Javascript array
var selectData = $.parseJSON( $("#select-data").text() );
var count = 0;
var max = 5; // pick the number you want here
// we create a new select, based on the count parameter
function makeSelect(count){
var $select = $('<select>', { id : 'field_' + count, name : "fields[]" });
$.each(selectData, function(){
$select.append(
$('<option>', { value : this.name, text : this.name })
)
})
return $select;
}
$('p#add_field').click(function(){
count += 1;
if(count >= max)
return;
$('#container2').append($('<strong>', { text : "Golf Course " + count }));
$('#container2').append(makeSelect(count));
});
});
</script>