简体   繁体   中英

Random String Selector based on user input, returned in unparsed HTML format for use in websites

I've been creating HTML buttons that return a result from a list of strings. It's rather manual work, and I'm looking for a way to automate it, especially for other people online.

Essentially, this is a short script that generates another script, however, since everything is being written and returned in HTML, I'm having some issues preventing it from executing as it's being returned .

<textarea rows="15" cols="60" id="content">
Add your d100 table here
</textarea>
<br>
<button onclick="getDetails()">Codify Me</button>
<br>
<br>
<p id="outputText"></p>

<script>

function getDetails(){
    var output = "<button onclick='selectRandom()'>Get result<button><br><p id='outputText'></p><"+"script>function selectRandom(){var randList = [";

    var list = document.getElementById("content").value.split('\n');
    list.pop();
    for (var i = 0; i < list.length; i++) {
        output += "\""+list[i]+"\",";
    }

    output += "][Math.floor(Math.random() * "+list.length-1+")]}<"+"/script>";

    document.getElementById("outputText").innerHTML = output;
}

</script>

To clarify, I want my script to produce the following output, as an unparsed string, given a user input of ABCD:

"<button onclick='selectRandom()'>Get result<button><br><p id='outputText'></p><script>function selectRandom(){var randList = ["A","B","C","D"][Math.floor(Math.random() * 3)]}</script>"

My current issues are, the tags are interfering with each other, and when output, the code returns a button like this:

Get result

Rather than:

<button>Get result<button>

along with the rest of the script, though I will likely add more information as I experiment.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Random</title>

</head>
<body>
<textarea rows="15" cols="60" id="content">
Add your d100 table here
</textarea>
<button onclick="selectRandom()">Codify Me</button>
<p id="outputText"></p>

<script>
    function selectRandom() {
        var items = document.getElementById('content').value.split('\n');
        document.getElementById("outputText").innerHTML = items[Math.floor(Math.random() * items.length)];
    }
</script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM