2016-12-15 13 views
0

私はテーブルのリストを持っています。divのキーでdivを取得し、その値を変更するJavascriptまたはJquery

var tables = ""; 
for (var i = 0; i <= data.length - 1; i++) { 
    if (data[i].current_order == null) { 
     tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>'; 
    } else { 
     tables += '<button class="table_selected" key="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>'; 
    } 

テーブルには、ビジー状態またはビジー状態の2つの色があります。テーブルにcurrent_orderがある場合は、ビジー状態を示します。私は何をしたいユーザーは、空のテーブルをクリックしたときに、それはtable_btnからtable_selectedにクラスを変更し、current_orderであるdiv要素のkeyを追加し、table_idを取得していることです。

私は、ユーザーが空のテーブルをクリックしたときに、それは順序を作成し、クリックしたtable_idの値を渡し、order_idを作成し、私のバックエンド用phoenix-frameworkを使用しています。しかし、私はどのようにテーブルdivのvalueでテーブルを取得し、divにkeyを置くことができるか分からない...

誰も私にこのアドバイスを与えることができますか?

+1

'、これは簡単なものですが、我々は上記のコードでは、より良い答え – Bindrid

+0

を得るために忙しいとunbusy、生産HTMLのいくつかを確認する必要がありますtable_btn'は不安定なテーブル、 'table_selected'はビジーテーブルです。だから、ユーザーがボタンをクリックしてクラスを変更してキーを入力したときのようにしたいのです。 –

答えて

0

あなたはjQueryのタグ付きとしてだから、私はこのポストつもりです。 IDのキーを変更すると、次のことができます。私はその後、テーブルを追加して、あなたがdata[i].current_orderを渡して使用する関数でテーブルを取り除きます。ユーザーfeebackに基づいて

編集、テストされていない

/*If you are not comfortable using the variable 'This', 
    you can just pass in the id of target table and 
    change the syntax to $("#"+targetTable)*/ 

var tables = ""; 
for (var i = 0; i <= data.length - 1; i++) { 
    if (data[i].current_order == null) { 
     tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>'; 
    } else { 
     tables += '<button class="table_selected" id="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>'; 
    } 

// On Click set table to busy 
$(".table_btn").click(function(){ 
    addTable($(this).val(), $(this)); 
}); 

// Add table function 
function addTable(tableId, targetTable){ 
    $.ajax({ 
    url: "YourBackEndHere", 
    data: tableID 
    cache: false, 
    success: function(html){ 
     $(targetTable).removeClass("table_btn"); 
     $(targetTable).addClass("table_selected"); 
     $(targetTable).attr("id", data[i].current_order); 
    } 
}); 
} 

// On click set table to empty 
$(".table_selected").click(function(){ 
    removeTable($(this).val(), $(this)); 
}); 

// Remove table function 
function removeTable(tableId, targetTable){ 
    $.ajax({ 
    data: tableId 
    url: "YourBackEndHere", 
    cache: false, 
    success: function(html){ 
     $(targetTable).removeClass("table_selected"); 
     $(targetTable).addClass("table_btn"); 
     $(targetTable).attr("id", ""); 
    }); 
    } 
}); 
} 
+0

素早く答えてくれてありがとう、btw、私は 'table_btn'のボタンがたくさんあります。私はあなたの答えで、 'table_btn'を' table_selected'に変更するにはどうすればいいですか? 'value'を使って、特定のボタンを' table_selected'に変更したいのですが? –

+0

変数$(this)はクリックされたテーブルのみを変更します。その他 – Paddy

+0

サーバーにデータを送信するためにクリックしてサーバーからデータ( 'current_order')を取得する必要があるため、このアプローチを使用できません。 'table_btn'の特定の値(' table_id')を取得するにはどうすればよいでしょうか? –

関連する問題