2017-10-14 89 views
0

但我不是很熟悉JavaScript但是,我想將輸入類型的hidden字段中的性別特定圖像URL作爲值顯示。我希望最終用戶選擇他們的性別,並根據返回到輸入值字段的相應圖像位置的URL。以下是我迄今爲止:JavaScript - 如何更改基於選擇選項中的性別選擇的輸入文本值

function myFunction(e) { 
    var gender; 
    if (gender == 'male') { 
    document.getElementById("printGender").html(value = "http://example.com/male.svg"); 
    } else if (gender == 'female') { 
    document.getElementById("printGender").html(value = "http://example.com/female.svg"); 
    } 
}; 

和HTML代碼:

<label for="name">Gender</label> 
<select onchange="myFunction(event)" name="gendr" class="nofocus" id=gender required> 
    <option value="other">Other</option> 
    <option value="female">Female</option> 
    <option value="male">Male</option> 
</select> 
<input type="hidden" id="printGender" style="color:#000"> 
+0

當你定義'gender'變量? – nmnsud

回答

0
<html> 
<head> 
<title>Sample</title> 
<script type="text/javascript" language="javascript"> 

function myFunction(listElem) 
{ 
    var gender = null; 
    var printGenderElem = null; 

    try 
    { 
    printGenderElem = document.getElementById("printGender"); 
    gender = listElem.options[listElem.selectedIndex].value; 

    if(gender=="male") printGenderElem.value="http://example.com/male.svg"; 
    else if(gender=="female") printGenderElem.value="http://example.com/female.svg"; 
    else printGenderElem.value="" 

    // Debugging purposes only, remove after verified 
    alert(printGenderElem.value); 
    } 
    catch(e) 
    { 
    alert("myFunction Error: " + e.Message); 
    } 
    finally 
    { 

    } 
} 

</script> 
</head> 
<body> 

<label for="name">Gender</label> 
<select onchange="myFunction(this)" name="gendr" class="nofocus" id=gender required> 
    <option value="other">Other</option> 
    <option value="female">Female</option> 
    <option value="male">Male</option> 
</select> 
<input type="hidden" id="printGender" style="color:#000"> 

</body> 
</html> 
+0

我建議使用'this'對象引用作爲'onchange'事件調用的函數的參數(這是指調用該函數的元素,即 - 在您的情況下,即元素