2014-11-23 4 views
0

때 선택 요소의 변화를 확인하는 방법 :요소 이름 난 달성하기 위해 노력하고 무엇 배열

  • 내 양식을 사 개 #item 분야, #unit, #price#total 구성은.

  • 사용자는 #item#unit의 여러 줄을 입력 할 수 있습니다. 이 경우 사용자가 "새 줄 추가"를 클릭하면 항목 및 단위 (수량)에 대한 사용자 입력을받는 새 줄이 나타납니다. 사용자가 이미 존재하는 줄에서 "-"를 클릭하면 줄이 표시됩니다 자바 스크립트 change()를 이용하여 실시간에서 식별되는 선택 항목 제거.

  • .

    동적 Ajax와 가격 데이터를 이용하여 검색되고 선택된 아이템의 가격이 #price 요소 #total 요소에 첨부된다

  • 또한 #unit x #price을 계산하여 채워진다.

이것을 달성하기 위해 내가 한 일은 다음과 같습니다.

먼저 내 HTML 양식 아래와 같이 작성하십시오./동적 추가를 구현 입력으로 제거하는 자바 스크립트 코드

<form id="form"> 

    <input type="submit" name="create" value="Create" /> 


    <!-- dynamically add more lines --> 
    <div class="form-group table-row hide" id="template">  

     <!-- remove button--> 
     <div class="table-cell" style="width: 45px;"> 
      <a class="btn btn-default removeButton"> 
       <span class="glyphicon glyphicon-minus"> 
       </span> 
      </a> 
     </div> 

     <!-- user input: item --> 
     <div class="table-cell"> 
      <select id="item" class="form-control"> 
       <option value=""></option> 
       <option value="item-1">Item 1</option> 
       <option value="item-2">Item 2</option> 
       <option value="item-3">Item 3</option> 
      </select> 
     </div> 

     <!-- user input: quantity --> 
     <div class="table-cell"> 
      <input id="unit" min="1" step="1" value="1" type="number" class="form-control" /> 
     </div>  

     <!-- price is dynamically filled up using ajax --> 
     <div class="table-cell"> 
      <input id="price" type="text" class="form-control" /> 
     </div> 

     <!-- total is dynamically calculated --> 
     <div class="table-cell"> 
      <input id="total" type="text" class="form-control" /> 
     </div> 

    </div> 

    <button type="button" class="btn btn-default addButton">Add new line</button> 

</form> 

그리고 을 형성한다.

<script> 
jQuery(document).ready(function($) { 

    var  idx = new Number(0); 

    $('#form') 

     // Add button click handler 
     .on('click', '.addButton', function() { 
      var $template = $('#template'), 
       $clone = $template 
           .clone() 
           .removeClass('hide') 
           .removeAttr('id') 
           .insertBefore($template); 
      // assign name attributes with proper array name and index 
      $clone.find('#item').attr('name', 'lines[' + idx + '][item]').attr('required', 'required').val(''); 
      $clone.find('#unit').attr('name', 'lines[' + idx + '][unit]').attr('required', 'required').val(''); 
      $clone.find('#price').attr('name', 'lines[' + idx + '][price]').attr('required', 'required').val(''); 
      $clone.find('#total').attr('name', 'lines[' + idx + '][total]').val(''); 

      idx = idx + 1; 

     }) 

     // Remove button click handler 
     .on('click', '.removeButton', function() { 
      if (confirm("<?php _e('Are you sure you wish to remove this line? This cannot be undone.', 'doumi'); ?>")) { 
       var $row = $(this).parents('.form-group'); 

       // Remove element containing the option 
       $row.remove(); 
       idx = idx - 1; 
      } 
     });  

}); 
</script> 

마지막으로, jQuery를 아약스를 호출합니다.

<script> 

    /* Get Item Price */ 
    jQuery('#item').change(function(){ 
     var $item_id=$('#item').val(); 

     var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; 

     // call ajax 
     jQuery("#price").empty(); 
     jQuery.ajax({ 
      url: ajaxurl, 
      /* ******************************************************************** */ 
      /* ajax_get_item_price is a function that returns the price of the item */ 
      /* ******************************************************************** */ 
      data:' action=ajax_get_item_price&item_id='+$item_id, 
      type:'GET', 
      success:function(results) { 
       jQuery("#price").append(results); 
      } 
     }); 
    }); 

</script> 

입력 양식의 행을 동적으로 추가하고 제거하는 데 문제가 없습니다.

문제는 각 줄의 양식 요소에는 아래와 같이 배열 이름이 지정됩니다.

<select id="item" name="lines[0][item]"></select> 
<input id="unit" name="lines[0][unit]" /> 
<input id="price" name="lines[0][price]" /> 
<input id="total" name="lines[0][total]" /> 

<select id="item" name="lines[1][item]"></select> 
<input id="unit" name="lines[1][unit]" /> 
<input id="price" name="lines[1][price]" /> 
<input id="total" name="lines[1][total]" /> 

<select id="item" name="lines[2][item]"></select> 
<input id="unit" name="lines[2][unit]" /> 
<input id="price" name="lines[2][price]" /> 
<input id="total" name="lines[2][total]" /> 

... 
... 
... 

<select id="item" name="lines[n][item]"></select> 
<input id="unit" name="lines[n][unit]" /> 
<input id="price" name="lines[n][price]" /> 
<input id="total" name="lines[n][total]" /> 

나는 여러 #item s이 (가) 다양한 이름으로 존재하기 때문에,이 코드에서는 jQuery에 관심을 지불 할 필요가있는 #item 알고하지 않는 것 같아요. 그러나, 나는 잘 모르겠다 중 하나를 적절하게 아약스를 호출하는 방법에 관한 우려 # 항목.

모든 조언을 매우 높이 평가합니다.

+0

IDS는 고유해야하고,'class'를 사용 대신. 'change' 액션이나'next()'와 같이'context'를 사용하십시오. –

+0

u_mulder, 의견 주셔서 감사합니다. 그러나, 나는 코드에 아주 익숙하고, 당신은 나에게 좀 더 정교하게 주시겠습니까? – Dongsan

답변

1

좋아, 나는 비슷한 항목이 클래스를 이용해야하므로, IDS는, 페이지에 대한 고유해야합니다 말했듯 :

jQuery('.item').change(function(){ 
    // to narrow the items, use this 
    var this$ = $(this); 
    // this$ contain exactly one item, which is currently changing 
    // do stuff 
}); 

없음 같은 것을 사용 change 이벤트, 그래서

.... 
<select class="item" name="lines[2][item]"></select> 
<input class="unit" name="lines[2][unit]" /> 
<input class="price" name="lines[2][price]" /> 
<input class="total" name="lines[2][total]" /> 
.... 

을 꽤 무슨 일이 일어나고 있는지 정확히 알기는하지만 price이 너무 많아서 문제가 생겼다고 생각합니다. 그러면이 줄은 다음을 수행합니다. 모두 #price 요소를 가져 와서 각 요소에 결과를 추가합니다.

success:function(results) { 
    jQuery("#price").append(results); 
} 

정확한 #price 항목을 분명히해야합니다. 먼저, 이미 언급 한 것처럼 여러 개의 유사한 필드에 클래스를 사용합니다. jQuery(".price") 둘째로 어떤 필드를 정확히 업데이트해야하는지에 대한 설명을 추가하십시오. 여러 가지 방법이있을 수있다 , 나는 두

한 가지 방법, next 기능을 사용하는 방법을 보여줍니다.

success:function(results) { 
    this$.next('.price').eq(0).append(results); 
    // here we refer to this$ - we try to find all `.price` element 
    // which come after our `select` 
    // as there can be a lot of them we take only the first one 
} 

당신의 요소를 그룹화되어있는 범위에서 또 다른 방법, context의 사용 종류, 즉 어떤 DIV. 나는 그래서이

<div class="item-wrapper"> 
    <select class="item" name="lines[2][item]"></select> 
    <input class="unit" name="lines[2][unit]" /> 
    <input class="price" name="lines[2][price]" /> 
    <input class="total" name="lines[2][total]" /> 
</div> 

처럼 HTML을 변경 제안, 당신의 필드의 모든 블록은 DIV에 싸여됩니다. 그 후 우리는 그래서

success:function(results) { 
    var parent$ = this$.parent(); 
    // again we refer to this$ getting its parent which is div 
    parent$.find('.price').append(results); 
    // here we try to find `.price` element located in a parent$ div. 
    // As it is definitely only one, we don't need to use any other code. 
} 

에 위치해 있습니다 select을 변경하는 사업부에 .price 요소를 찾기 위해 jQuery를 알 수 , 이것은 내가 말할 수있는 모든)

+0

좋아요. 단계 조언에 의하여 좋고 상세한 단계. 나는 너의 충고를 곧 시도 할 것이다, 고마워! – Dongsan

+0

음 ... 수동으로 작성된 양식 요소에서 작동하지만 동적으로 추가 된 양식 요소에는 작동하지 않습니다. 예,'lines [0] []'은 수동으로 작성된 양식 요소로서 페이지로드시 기본으로 표시됩니다. 그리고 사용자가 "Add new line"버튼을 클릭하면'lines [1] []','lines [2] []', ...,'lines [n] [] 'jQuery ('. item '). change (function()'은 [lines] [0] [...]에 대해서만 작동합니다 ... – Dongsan

+0

jquery에 대한'on' 바인딩에 대해 읽었습니다. http : // api .jquery.com/on / –

관련 문제