我有一些简单的代码可以将附加的选择字段附加到表单,并且用户可以根据需要添加更多字段。但是,我希望能够定义可以追加的最大输入元素数。我目前的代码是:
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#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>
非常感谢任何帮助。
答案 0 :(得分:1)
<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>
答案 1 :(得分:0)
试试这个
<script type="text/javascript">
var count = 0;
var limit = 5;
$(function () {
$('p#add_field').click(function () {
count += 1;
if ($('#container2 select').length <= limit) {
$('#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 />')
}
else {
alert('Limit Exceed');
}
});
});
</script>