2012-03-14 23 views
1

入力値を受け取り、ユーザーが[Add]リンクをクリックするとdivに追加する方法を教えてもらえますか?divに入力値を追加する

これは私ができる最高です。 HTML:

<div id="customUtility-container"></div> 
<a href="#" id="addUtility">Add</a> 

のjQuery:

$(function() { 
       var addDiv = $('#customUtility-container'); 
       var i = $('#customUtility-container').size() + 1; 

       $('#addUtility').live('click', function() { 
         $('#customUtility').val().appendTo(addDiv); 
         $('<p><label for="customUtility-container"><input type="text" id="customUtility" size="20" name="customUtility_' + i +'" value="" placeholder="" /></label> <a href="#" id="removeUtility">Remove</a></p>').appendTo(addDiv); 
         i++; 
         return false; 
       }); 

       $('#removeUtility').live('click', function() { 
         if(i > 2) { 
           $(this).parents('p').remove(); 
           i--; 
         } 
         return false; 
       }); 

しかし、これは別の入力フィールドを作成します。私はちょうど1つの入力ボックスを持って、ユーザーが追加をクリックして、その値を受け取り、それをリストに入れ、入力ボックスをクリアしてユーザーが何か他のものを再び追加できるようにしたい。以下のような

答えて

0

私はすべてを廃棄し、それをやり直すことになった:

$(function() { 
       var i = $('#customUtility-container').size() + 1; 
       $("#addUtility").on("click", function() { 
        $("#customUtility-container").append('<div id ="customUtility_' + i +' " name="customUtility_' + i +' ">'+ $("#customUtility").val() + '<a href="#customUtility-container" id="removeUtility">Remove</a></div>'); 
       }); 

       $('#removeUtility').live('click', function() { $(this).closest('div').remove(); 
               i--; 
       });  
     }); 
0

何か:

addDiv.html(addDiv.html() + whateveryouwanttoadd) 
4

使用jQueryのappend()機能

addDiv.append($('#customUtility').val()); 

はここa working fiddleです。


警告:

以下の意見jQueryオブジェクトを格納する変数を作成し、私はそれが$で、変数の接頭辞すると便利だと思います。このようにして、jQueryオブジェクトで作業していることがわかります。また、あなたがやっていることを認識するためにあなたの後ろにお越しの方のために、それが容易になります:

var $addDiv = $('#customUtility-container'); 
$addDiv.append($('#customUtility').val()); 
0
addDiv.append($('#customUtility').val()); 
0

変更

$('#customUtility').val().appendTo(addDiv); 

addDiv.append($('#customUtility').val()); 

val()

する方法がの値を与えます入力要素であり、エラーをスローする文字列に対してjQueryメソッドを呼び出すことはできません。

の作業のデモ - http://jsfiddle.net/t9D8R/

関連する問題