2013-12-12 31 views
0

我有一組數字字段。無論在該領域內的任何數字,我都希望顯示相同數量的div。當您將數字添加到數字字段時,應出現另一個div。當從數字字段中減去數字時,div應該消失。添加/刪除div作爲數字字段更改的計數

這裏是我的筆記 - 變化被設置爲測試目的警報:

$(document).ready(function() { 
$('.product-quantity').on('change',function(){ 
    alert('One of these is changed ' + $(this).attr('data-size')); 

    // Using the attributes of $(this), create selector to find input fields with this 
    size, belonging to this product 
// If the count of those fields is > than the value we have of this, then we remove 
// If it's < than, we add fields 
// If it's equal, we do nothing 
// we add/remove based on this dymanic selector 

}); 
}); 
+0

在我看來,如果你有你想要的東西的筆記,你應該能夠實現這些結果。你試過什麼了? –

+0

做過這些對你有用嗎? – isJustMe

回答

0

Here是你所需要的。看一看。 注意:在您更改框中的值後。您需要在輸入之外單擊以進行更改。

爲HTML代碼:

<input class="product-quantity" /> 
<div id="small-field-set" style='width:100%;min-height:100px;border:1px solid red;'></div> 

爲你的JavaScript/jQuery的:

$(document).ready(function() { 
    $('.product-quantity').on('change', function() { 
     $('#small-field-set').html('') 
     var number = $('.product-quantity').val(); 
     for (var i = 0; i < number; i++) { 
      $('#small-field-set').append('<div style="min-height:10px;border:1px solid blue;">test' + (i + 1) + '</div>') 
     } 

    }); 
}); 

令數是插入到輸入數量/值。編輯: 編輯:我已經添加刪除線,只要值更改。

+0

看起來不錯,但這只是增加了它們,並沒有刪除它們 – anmaree

+0

在那裏,去掉舊的div並添加新的div。 – iCezz

0

由於您正在討論更改數字,每當您清除輸入時它將被視爲更改,我添加了一個按鈕,以便您可以在輸入後觸發更改。

考慮下面的html:

<input id="product-quantity" value="0" /> 
<button id="change"> Change </button> 
<div id="divParent"></div> 

此代碼將添加的div沒有刪除那些已經存在的那些,它只會cleaer股利,如果你輸入小於被alreay寫的div

$('#change').on('click', function() { 

    var input = $('#product-quantity').val() || 0; 
    var children=$('#divParent > div').size() || 0;  

    if(input < children){ 
     $('#divParent').empty(); 
     children=0; 
    } 

    for (var i = children+1; i <= input; i++) { 
     $('#divParent').append(
     $('<div/>') 
      .attr("id", "newDiv" + i) 
      .text("hello world " + i)); 
    } 


}); 

這是一個fiddle,希望你覺得這個有用。