答案 0 :(得分:0)
选择元素有<option>
个孩子。 MDN's example:
<!-- The second value will be selected initially --> <select name="text"> <!--Supplement an id here instead of using 'text'--> <option value="value1">Value 1</option> <option value="value2" selected>Value 2</option> <option value="value3">Value 3</option> </select>
因此,您var myOptions = document.GetElementByName("text")
然后将myOptions
.push
每个值(或任何您想要的)迭代到数组中。然后将该数组写入您的文本文件。
答案 1 :(得分:0)
我看到你的html中没有标签。我认为和标签中必须有标签。我改进了你的代码如下:
<body>
<label for="mySelect">Form input without an associated label </label>
<select id="mySelect" style="width: 581px; height:300px;" rows="10" multiple="multiple">
<option id="id1" value="value1">id1</option>
<option id="id2" value="value2">id2</option>
<option id="id3" value="value3">id3</option>
<option id="id4" value="value4">id4</option>
<option id="id5" value="value5">id5</option>
</select>
<button id="save">save</button>
<script>
function saveTextAsFile() {
var textToWrite = document.getElementById('mySelect').value;
var textFileAsBlob = new Blob([textToWrite], {type: 'text/plain'});
var fileNameToSaveAs = "directive.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
console.log("innerHTML -> " + downloadLink.innerHTML);
// if ($('#sel1').val() == '') {
// alert('Please select ACCOUNT NAME, SCHEDULE and TASK first.');
// }
// else {
window.webkitURL != null;
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
// }
downloadLink.click();
}
var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);
</script>
</body>
答案 2 :(得分:0)
如果您有以下HTML选择元素,
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
我测试了以下代码正在运行。基本上如上面Ron所建议的那样,您需要迭代选项并将它们添加到字符串中以将其打印在文本文件中。
function saveTextAsFile() {
var textToWrite = "";
$('#mySelect>option').each(function () {
textToWrite += this.value + " ";
});
var textFileAsBlob = new Blob([textToWrite], {
type: 'text/plain'
});
var fileNameToSaveAs = "directive.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if ($('#sel1').val() == '') {
alert('Please select ACCOUNT NAME, SCHEDULE and TASK first.');
} else {
window.webkitURL != null;
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
downloadLink.click();
}
var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);