Issue
I have multiple buttons that all do something very similar. How do I use a <select>
box with one <button>
to do the same thing with less javascript?
These are the buttons I want to turn into a <select>
box with just one button:
<button onclick="SaveAsHTML()">Save As HTML</button>
<button onclick="SaveAsJS()">Save As JS</button>
<button onclick="SaveAsCSS()">Save As CSS</button>
<button onclick="SaveAsTXT()">Save As TXT</button>
Here is my javascript right now:
function SaveAsHTML()
{
var filename = document.getElementById("txtFilename").value;
var filename = filename + ".html";
}
function SaveAsCSS()
{
var filename = document.getElementById("txtFilename").value;
var filename = filename + ".css";
}
function SaveAsJS()
{
var filename = document.getElementById("txtFilename").value;
var filename = filename + ".JS";
}
function SaveAsTXT()
{
var filename = document.getElementById("txtFilename").value;
var filename = filename + ".txt";
}
Solution
Here's a snippet, I don't think it needs much explanation.
I have created an array of file types and used jquery to populate the <select>
with <option>
s. Then I just look up which one is chosen when you click the save
button...
var types = [
{"extension": "html", "name": "HTML"},
{"extension": "txt", "name": "Plain Text"},
{"extension": "js", "name": "Javascript"},
{"extension": "css", "name": "CSS"},
]
types.forEach(function(type) {
$opt = $("<option>").attr("value", type.extension).text(type.name)
$("#saveas").append($opt)
})
function SaveAsType()
{
console.log($("#saveas").val())
/**
* Put your code here and replace:
document.getElementById("inputFileNameToSaveAs").value + ".html";
* with
document.getElementById("inputFileNameToSaveAs").value + "." + $("#saveas").val();
*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Save as <select id="saveas">
</select><button onclick="SaveAsType()">save</button>
Answered By - jcuenod
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.