我正在创建一个网络表单,用户可以在其中设置自定义个人资料图片。我要做的是创建一个下拉框,让您可以选择上传图片或链接图片来自URL。
应该禁用未选中的选项,但我似乎无法使其正常工作。
这是我的代码:
<form>
Choose a Profile Picture:<br>
<select>
<option onselect="upload()">Upload an Image
<option onselect="link()">Load from URL
</select><br>
<input type="file" id="fileBrowse" accept="image/*"><br>
<input type="url" id="enterUrl" placeholder="Enter in a URL." disabled>
function upload() {
document.getElementById("enterUrl").disabled = true;
document.getElementById("fileBrowse").disabled = false;
}
function link() {
document.getElementById("fileBrowse").disabled = true;
document.getElementById("enterUrl").disabled = false;
}
以下是代码的JSFiddle。
答案 0 :(得分:1)
问题是onselect
不是option
元素的有效事件处理程序。您必须使用onchange
<强> HTML 强>
<form>
Choose a Profile Picture:<br>
<select id="profilePictureType" onchange="onSelectChange()">
<option value="1">Upload an Image</option>
<option value="2">Load from URL</option>
</select><br>
<input type="file" id="fileBrowse" accept="image/*"><br>
<input type="url" id="enterUrl" placeholder="Enter in a URL." disabled="disabled">
</form>
<强> JS 强>
function onSelectChange() {
var selectedValue = document.getElementById("profilePictureType").value;
selectedValue == "1" ? upload() : link();
}
function upload() {
document.getElementById("enterUrl").disabled = true;
document.getElementById("fileBrowse").disabled = false;
}
function link() {
document.getElementById("fileBrowse").disabled = true;
document.getElementById("enterUrl").disabled = false;
}
此解决方案的简短版本将是
function onSelectChange() {
var selectedValue = document.getElementById("profilePictureType").value;
var upload = selectedValue == "1";
document.getElementById("fileBrowse").disabled = upload;
document.getElementById("enterUrl").disabled = !upload;
}
答案 1 :(得分:1)
您需要将onchange放入select(而不是选项)并根据所选值禁用它
<form>
Choose a Profile Picture:<br>
<select id="choose" onchange="changed();">
<option value="upload">Upload an Image</option>
<option value="link">Load from URL</option>
</select><br>
<input type="file" id="fileBrowse" accept="image/*"><br>
<input type="url" id="enterUrl" placeholder="Enter in a URL." disabled="disabled">
</form>
<script type="text/javascript">
function changed() {
var chooser = document.getElementById("choose");
var chooseValue = chooser.options[chooser.selectedIndex].value;
if(chooseValue == "upload") {
document.getElementById("enterUrl").disabled = true;
document.getElementById("fileBrowse").disabled = false;
} else if(chooseValue == "link") {
document.getElementById("fileBrowse").disabled = true;
document.getElementById("enterUrl").disabled = false;
}
}
</script>