2017-11-24 10 views
-1

一般的なフォームチェッカーを持っていて、フォームを処理するためにコールバック関数に渡す必要があることが検証されたら、必要なフォームフィールドをコールバック関数に渡します。Javascript:未知のパラメータをコールバック関数に渡す

要件: - checkFormは ジェネリックにする必要がある - フォームフィールドは、コールバック関数に渡される必要がある(updateSection()このケースでは)

任意のアイデア?

以下の現在のコード...

HTML Forrm:

<form onsubmit="javascript:checkForm(0,updateSection(), event); return false;"> 
    <h2>Update Section</h2> 
    <p><?php echo $partsAvailable; ?></p> 
    <p><input type="text" id="sectionTitle" placeholder="Title" /></p> 
    <p><textarea id="sectionContent" placeholder="Content"></textarea></p> 
    <p><button type="submit">Update</button></p> 
</form> 

JavaScriptのコード:

var allGood = false; 

// General form checker 
function checkForm(which, callback, evt) { 
    evt.preventDefault(); 
    // We need to check a form to make sure nothing is missed 
    var t = document.getElementsByTagName('form')[which]; 
    var rows = t.getElementsByTagName('p'); 
    var allGood = false; 

    for(var i = 0; i < rows.length-1; i++) { 

     if(!getVal(rows[i].childNodes[0].id)) { 
      allGood = false; 
     }else{ 
      allGood = true; 
     } 
    } 

    if(allGood == true) callback(); 

    return false; 
} 

// Getting values from inputs 
function getVal(el) { 
    val = ''; 

    switch(el.type) { 
     case 'text': 
      val = document.getElementById(el).value; 
      break; 

     case 'select': 
      val = document.getElementById(el).options[document.getElementById(el).selectedIndex].value; 
      break; 

     default: 
      val = document.getElementById(el).innerHTML; 
    } 

    return val; 
} 

function updateSection(part, title, content) { 
    alert('Function called'); 

    return false; 
} 

答えて

0

あなたはcheckForm()callback関数を渡す方法は、次のようにする必要があります。

<form onsubmit="javascript:checkForm(0,updateSection, event); return false;"> 

ストアreturnローカル変数でgetVal()から。コールバック関数を呼び出す場所から値をupdateSection()に渡します。

var temp = []; 
for(var i = 0; i < rows.length-1; i++) { 
    if(!getVal(rows[i].childNodes[0].id)) { 
     allGood = false; 
    }else{ 
     temp.push(getVal(rows[i].childNodes[0].id); 
     allGood = true; 
    } 
} 

if(allGood == true) callback(temp); // passing all form value as temp array. 
関連する問題