Search code examples
javascriptinputquotes

Value from input in quotes javascript


If I have an code like this, with quotes and authors, how can I get two input type="text" boxes where I can write for example two names and then display the name into the quotes in place of "(random user)"?

//store the quotations in arrays
quotes = [];

authors = [];

quotes[0] = "(randomuser) example (randomuser) example?";

authors[0] = "Authors!";

quotes[1] = "(random user) example (random user) example?";

authors[1] = "Authors!";

//calculate a random index
index = Math.floor(Math.random() * quotes.length);

//display the quotation

document.write("<DL>\n");

document.write("<DT>" + "\"" + quotes[index] + "\"\n");

document.write("<DD>" + " " + authors[index] + "\n");

document.write("</DL>\n");

//done

Solution

  • I think you want to replace the (randomuser) in the quotes array with strings that you get from a couple of <input> tags. In that case, you could get the contents of those inputs like so:

    var user1 = document.getElementById("input1").value;
    var user2 = document.getElementById("input2").value;
    

    Now, you could substitute "(randomuser1)" and "(randomuser2)" for those inputted values using String.replace(), like so:

    //Sub in the usernames
    var newquote = quotes[0].replace("(randomuser1)", user1); //quotes[0] can of course be any index
    newquote = newquote.replace("(randomuser2)", user2);
    

    And then you can display newquote. Keep in mind that you should avoid document.write(). Instead, you could make a display div on your page and then put the quote into that, like this:

    var quotediv = document.getElementById("quoteDiv"); //get the div (or any other element) that you want to display the quote in
    quotediv.innerHTML = newquote; //display your quote in the div.
    

    JsFiddle example

    EDIT:

    To select a quote randomly from a larger list, you would change quotes[0] to something like quotes[Math.floor(Math.random() * quotes.length)]. To add more users, you would add more inputs and more replace statements. Example:

    //Sub in the usernames
    var ind = Math.floor(Math.random() * quotes.length); //select random quote
    var newquote = quotes[ind].replace("(randomuser1)", user1);
    newquote = newquote.replace("(randomuser2)", user2);
    newquote = newquote.replace("(randomuser3)", user3);
    newquote = newquote.replace("(randomuser4)", user4);
    newquote = newquote.replace("(randomuser5)", user5);
    

    That could be simplified into a for loop for a larger number of users, but I will leave you to figure that out.