2014-01-20 91 views
0

我遇到了這個優秀的解決方案後續問題: Select checkbox when clicking in textarea (JavaScript?)我可以將一個變量textarea id傳遞給JavaScript函數嗎?

我需要將解決方案應用於多個文本框中。是否有可能以任何方式修改密碼弄成這個樣子(不工作):

<html> 
<body> 
<textarea id="iamtextarea" rows="4" cols="10" onfocus="onFocusTextArea('iamtextarea');" onblur="onBlurTextArea('iamtextarea');">Enter some text in textbox</textarea> 
<input type="checkbox" name="iamcheckbox" id="iamcheckbox" checked="checked"> I am checkbox<br> 
<input type="hidden" name="hiddenString" id="hiddenString" value="Enter some text in textbox"> 
</body> 
</html> 

<script type="text/javascript"> 

function onFocusTextArea(variableName) { 
    document.getElementById("iamcheckbox").checked = false; 
} 
function onBlurTextArea(variableName) { 
    if(document.getElementById(variableName).value==document.getElementById("hiddenString").value) { 
    document.getElementById("iamcheckbox").checked = true; 
    } 
} 
</script> 

我想要做的是對的textarea的變量ID傳遞給javascript函數,這樣我可以使用相同的功能爲多個文本區域。那可能嗎?

+0

爲什麼不分配您的不同文本區域不同的ID,只是引用它們通過DOM? document.getElementById('yourTextAreaID).value? (編輯,然後將ID傳遞給你的功能..?) –

+0

是的,這是可能的,你有什麼看起來是正確的。至少它對我「起作用」:http://jsfiddle.net/4n3ux/。到底什麼是「不適合你」? –

+0

對每個textarea都不需要一個函數嗎? –

回答

0

請參閱jsfiddle這裏。這需要的元素與checkboxid

function onFocusTextArea(checkboxId) { 
    document.getElementById(checkboxId).checked = false; 
} 

function onBlurTextArea(element, checkboxId) { 
    if (element.value === "") { 
     document.getElementById(checkboxId).checked = true; 
    } 
} 

一些樣本HTML

<textarea id="iamtextareaone" onfocus="onFocusTextArea('checkboxone');" onblur="onBlurTextArea(this, 'checkboxone');"></textarea> 
<textarea id="iamtextareatwo" onfocus="onFocusTextArea('checkboxtwo');" onblur="onBlurTextArea(this, 'checkboxtwo');"></textarea> 

<input type="checkbox" id="checkboxone" checked="checked">Checkbox One<br> 
<input type="checkbox" id="checkboxtwo" checked="checked">Checkbox Two<br> 
+0

非常感謝! –

相關問題