2017-03-20 10 views
0

基本的に、私がしようとしているのは、数字入力の変更を出版物のリストに加えることです。問題は、入力を変更するたびに以前の出版物と出版物の数量が保持されることです。たとえば:出版物を複製しないリストに追加

私は、第1入力2倍をクリックして、これは私が受け取るものです:

出版1:数量:1
出版1:数量:あなたがクリックしたときに2

何起こるべきことです入力で前の数量を上書きします。そう例えば:

文献1:数量:1つの
文献1:数量2
文献2:数量1つの

注意取り消し。もう存在しないはずです。数量が更新されました。 CODEPEN

http://codepen.io/Jesders88/pen/evVrrw

HTML

<input type="number" data-name="something here" data-qty="1" data-id="1"> 
<input type="number" data-name="something else" data-qty="3" data-id="2"> 
<input type="number" data-name="something other" data-qty="5" data-id="3"> 

JAVASCRIPT

publications = new Array; 

$('input').on('change', function(e){ 
    e.preventDefault(); 

    var pid = parseInt($(this).data('id')); // id of thing 
    var name = $(this).data('name'); // name of thing 
    var qty = parseInt($(this).data('qty')); 

    console.log(pid); 
    console.log(name); 
    console.log(qty); 

    if(typeof publications[pid] == 'undefined') 
    { 
    publications[pid] = new Array; 
    publications[pid][0] = name; 
    publications[pid][1] = qty; 
    } 
    else 
    { 
    publications[pid][1] = qty; 
    } 

    console.log(publications); 

    $.each(publications, function(i, l){ 
    //console.log("Index #" + i + ": " + l); 
    console.log(l[0]+' has a qty of: '+l[1]); 
    }); 

}); 

答えて

1

AA夫婦の問題が最も重要なのは、ここにあります:あなたは$(this).data('qty')更新されていない、したがって、それは常に同じ値であります。私は個人的配列の代わりにオブジェクトを使用するだけの入力で表される実際の値から離婚されたデータ属性の代わりqty.valueで動作:

// use an object 
var publications = {}; 

$('input').on('change', function(e){ 
    e.preventDefault(); 

    var pid = parseInt($(this).data('id'), 10); // id of thing 
    var name = $(this).data('name'); // name of thing 
    var qty = parseInt($(this).val(), 10); 

    // if you must, set the new quantity into the data property 
    $(this).data('qty', qty); 

    console.log(pid); 
    console.log(name); 
    console.log(qty); 

    if(!publications[pid]) 
    { 
    publications[pid] = { 
     name: name, 
     qty: qty 
    }; 
    } 
    else 
    { 
    publications[pid].qty = qty; 
    } 

    console.log(publications); 

    $.each(publications, function(i, l){ 
    //console.log("Index #" + i + ": " + l); 
    console.log(l.name+' has a qty of: '+l.qty); 
    }); 

}); 
+0

恐ろしいです。とても簡単。私はそれを逃したと信じることができない:)。ご協力ありがとうございました。 – jesders88

関連する問題