2017-03-13 21 views
0

JavaScriptを使用してHTMLフォームに非表示の入力フィールドを追加するには、this nifty little functionに出くわしました。HTMLフォームに入力フィールドを追加するJavaScript関数

function addHidden(theForm, key, value) { 
    // Create a hidden input element, and append it to the form: 
    var input = document.createElement('input'); 
    input.type = 'hidden'; 
    input.name = key;'name-as-seen-at-the-server'; 
    input.value = value; 
    theForm.appendChild(input); 
} 

// Form reference: 
var theForm = document.forms['detParameterForm']; 

// Add data: 
addHidden(theForm, 'key-one', 'value'); 
addHidden(theForm, 'another', 'meow'); 
addHidden(theForm, 'foobarz', 'baws'); 

// Submit the form: 
theForm.submit(); 

は、私が理解していないことinput.name = key;'name-as-seen-at-the-server';'name-as-seen-at-the-server'です:

は、ここでは、コードです。

これは正確に何が設定され、どのように使用されますか?

+1

与えられたコンテキスト(入力をDOMに追加する関数)では、何もありません。キーは、任意に決定された任意の文字列でよい。 – zer00ne

+1

私はそれをjsfiddle上で実行し、 ''名前はサーバ上で見たように ';は何もしません。次に、値os 'key'は、左側の変数に割り当てられます。 – Ayush

+1

名前をサーバー上で見た名前をコメントにするか、削除してください。これはあなたのフィールド名です。他にはありません –

答えて

3

keyの入力を説明している可能性があります。それをコメントアウトするか削除してください。すべて正常に動作するはずです。 行をinput.name = key;'name-as-seen-at-the-server';に変更するinput.name = key;//'name-as-seen-at-the-server';

+0

これは実際には 'key'という名前と' value'という値を持つ入力フィールドを作成するだけでしょうか?ありがとうございました!私はちょうどjsbinでそれを試しました、それはうまく動作します - ありがとう! – SaAtomic

関連する問題