2017-09-05 92 views
0

我有使用javascript和jQuery克隆以下表单部分的动态表单。克隆部分适合我。但是我想在不同的div的同一页面中添加一个动态的表单预览,作为正在选择的选项列表。如何在jQuery中为动态表单创建动态预览

如果有人选择Option 1将预览

1. Option 1. 

那么如果一个部分是从克隆的部分添加并选择Option 2,它会预览

1. Option 1 
2. Option 2 

如果一个节已被除去,说第一节,那么预览会自动更新并显示

1. Option 2. 

任何建议我该如何实现?

这是我的形式:

<form id="form"> 
    <div id="sections"> 
     <div class="section"> 
      <select name="form"> 
       <option value="option 1">Option 1</option> 
       <option value="option 2">Option 2</option> 
       <option value="option 3">Option 3</option> 
      </select> 
      <p><a href="#" class='remove'>Remove Section</a></p> 
     </div> 
    </div> 
    <p><a href="#" class='addsection'>Add Section</a></p> 
</form> 

和JavaScript:

var template = $('#sections .section:first').clone(); 
var sectionsCount = 1; 
$('body').on('click', '.addsection', function() { 

    sectionsCount++; 
    var section = template.clone().find(':input').each(function(){ 
     var newId = this.id + sectionsCount; 
     $(this).prev().attr('for', newId); 
     this.id = newId; 

    }).end() 

    .appendTo('#sections'); 
    return false; 
}); 

$('#sections').on('click', '.remove', function() { 
    $(this).parent().fadeOut(300, function(){ 
     $(this).parent().parent().empty(); 
     return false; 
    }); 
    return false; 
}); 

更新:将真正体会到工作的小提琴例子。

回答

0

您要预览

<form id="form"> 
    <div id="sections"> 
     <div class="section"> 
      <select name="form" id="MySelect"> 
       <option value="option 1">Option 1</option> 
       <option value="option 2">Option 2</option> 
       <option value="option 3">Option 3</option> 
      </select> 
      <p><a href="#" class='remove'>Remove Section</a></p> 
     </div> 
    </div> 
    <p><a href="#" class='addsection'>Add Section</a></p> 

    <div class="MyPreview"> 

    </div> 

</form> 

克隆部分工作正常,我添加<div>到表单中。

,而克隆的克隆部分追加到div

$(".MyPreview").append("<p>1. Option 1. </p>"); 

尝试这样的事情,我没有检查这个呢,

var i = 1; 
$('body').on('click', '.addsection', function() { 

    sectionsCount++; 
    var section = template.clone().find(':input').each(function(){ 
     var newId = this.id + sectionsCount; 
     $(this).prev().attr('for', newId); 
     this.id = newId; 

    }).end() 

    .appendTo('#sections'); 

    var e = document.getElementById("MySelect"); 
    var MyValue = e.options[e.selectedIndex].value; 
    var MyOption = e.options[e.selectedIndex].text; 

    $(".MyPreview").append("<div class='"+ MyValue +"'>" + i + "." + MyOption +". </p>"); 
    i++; 

    return false; 
}); 

为类添加选项的值div等删除使用类去除div。

$(".MyValue").remove(); 


$('#sections').on('click', '.remove', function() { 
    $(this).parent().fadeOut(300, function(){ 
     $(this).parent().parent().empty(); 
     return false; 
    }); 

    var e = document.getElementById("MySelect"); 
    var MyValue = e.options[e.selectedIndex].value; 

    $(".MyValue").remove(); 

    return false; 
}); 

希望它为你工作

+0

感谢您的努力,但它不工作。如果你可以分享一个工作示例,可能会非常有用,可能会在jsfiddle.net中 – Ashonko