2013-01-23 65 views
0

目標:修復下面的代碼,並理解爲什麼專注於單選按鈕無法像專注於文本輸入框一樣工作。專注於單選按鈕

問:爲什麼這個不行:

function isValidRadio(elem, helperMsg) { 
    var valid = false; 
    for (var i = 0; i < elem.length; i++) { 
     if (elem[i].checked) { 
      return true; 
     } 
    } 
    alert(notice); 
    setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0); 
    return false; 
} 

...當這樣做:

function isValidText(elem, notice) { 
    var str = elem.value; 
    var re = /.+/; 
    if(!str.match(re)) { 
     alert(notice);   
     setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0); 
     return false; 
    } else { 
     return true; 
    } 
} 

示例代碼:

function focusElement(formName, elemName) { 
    var elem = document.forms[formName].elements[elemName]; 
    elem.focus(); 
    elem.select(); 
} 
function validateForm(form) { 
    if (isValidText(form.phone, "Fail.")) { 
     if (isValidRadio(form.yesNo, "Fail.")) { 
      return true; 
     } 
     return false; 
    } 
} 
<form id='myForm' action='/formPage/collectinfo/' method='post' accept-charset='UTF-8' name="myForm"> 
    <input name="phone" type="text" maxlength="14" size="14" /> 
    <input type="radio" name="yesNo" value="Yes"> Yes <input type="radio" name="yesNo" value="No" > No 
<input type="submit" value=" Submit " name="Submit" onclick="return validateForm(myForm)" /> 

詳細信息:我使用的是php/javascript/html,到目前爲止我只在Chrome中測試過這件作品。該表單工作得很好,驗證工作,直到它擊中isValidRadio。警報運行,但隨後JavaScript中斷。代碼修復會很好,但我不會介意'釣魚一輩子......'

+0

請不要評估你的setTimeout回調。 – AlienWebguy

+0

@AlienWebguy:我開始討論這些問題,因爲他們被認爲是解決這類問題的一種可能的解決方案(顯然他們沒有工作)。我很樂意將它們加入,但希望能詳細瞭解它們的問題。 (除了它們是不必要的,我認爲)。 – lostphilosopher

+1

它只是使用'setTimeout(「myfunction()」,0);''與'setTimeout(function(){myfunction();},0)的語法。 ' – AlienWebguy

回答

2

好的,我找到了解決方案,AlienWebguy把我放在思考陣列的正確軌道上。我只需要指定要關注哪個單選按鈕而不是哪個單選按鈕。這裏是工作代碼:

// Validate that the user has checked one of the radio buttons 
function isValidRadio(radio, helperMsg) { 
    var valid = false; 
    for (var i = 0; i < radio.length; i++) { 
     if (radio[i].checked) { 
      return true; 
     } 
    } 
    alert(helperMsg); 
    radio[0].focus(); 
    return false; 
} 

調用通過:isValidRadio(form.yesNo, "Error.")感謝您的協助。