2016-12-28 1 views
0

동적으로 선택 입력 폼을 추가 및 제거 할 수있는 jQuery 코드가 있습니다.여러 클래스를 대상으로 jQuery 사용

$(document).ready(function() { 
    var max_fields = 20; //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 
     $(".aaaa").first().clone().appendTo(".input_fields_wrap"); 
     } 
    }); 
    $(wrapper).on("click", ".remove_field", function(e) { 
     e.preventDefault(); 
     if($(".aaaa").length > 1) { 
     $(this).parent('div').remove(); 
     } else { 
     alert('You can not delete all elements'); 
     } 
    }) 
}); 

많은 클래스 (class="input_field_wrap and etc.")에이 jQuery 코드를 사용하고 싶습니다.

내가 작동하게하는 유일한 방법은 onclick 기능으로 만드는 것입니다.

function createSelect(wrapper, add_button, a) { 
var max_fields = 20; 
var x = 1; 
$(add_button).click(function(e) { //on add input button click 
     e.preventDefault(); 
     if (x < max_fields) { //max input box allowed 
     x++; //text box increment 
     $(".aaaa").first().clone().appendTo(".input_fields_wrap"); 
     } 
    }); 
} 

이것은 작동하지 않습니다.

HTML : 당신은 그냥 신선한 DOM 당신이 .remove_field에 대한 이전의 클릭 이벤트에서와 같이 동적으로 추가 처리하는 이벤트 위임을 on()을 사용했습니다

<div class="input_fields_wrap"> 
         <a href="#" class="add_field_button" >Add Another Prescibed Medication</a> 
         <div class="aaaa"> 
          Prescibed Medication Name: 
          <select class="form-control" name="prescription[]"> 
           <option value="">Select an option</option> 
           <?php 

          foreach($prescription->result() as $row) 
          { 
           echo '<option value="'.$row->id.'">'.$row->name.'</option>'; 
          } 

          ?> 

          </select> 

          <a href="#" class="remove_field">Remove</a> 
         </div> 
        </div> 
+0

'$ (".class1, .class2, .class3")와 같이 래퍼에 여러 개의 선택기를 사용하십시오. –

+0

HTML 구조도 공유 할 수 있습니까? – Deep

+0

이 [fiddle] (https://jsfiddle.net/0gcs1byu/1/)을 살펴보고 동적으로 추가 된 요소에 대해이 [fiddle] (https://jsfiddle.net/0gcs1byu/2/) 희망을 확인할 수 있습니다. 도움이됩니다. – Curiousdev

답변

0

, 그것은 것입니다 :

$('body').on('click', '.add_field_button', function(e) { 
    e.preventDefault(); 

    if (x < max_fields) { //max input box allowed 
    x++; //text box increment 
    $(".aaaa").first().clone().appendTo(".input_fields_wrap"); 
    } 
}); 

희망이 도움이됩니다.

+0

다른 선택 폼이나 클래스에 코드를 사용하려면 어떻게해야합니까? – guwop69

+0

무슨 뜻인지 잘 모르겠지만 원하는 결과를 더 많이 묘사하는 바이올린을 만들어보십시오. –

관련 문제