o.schiff. o.schiff. - 4 months ago 17
HTML Question

Store generated sentence with button

I have a small webapp to try and figure out how things work...
Right now, the "Create New Startup" button generates a string with one input from the array 'startupX' and one from 'startupY'. I'm trying to figure out how to get the "Favorite Startup" button to store the entire string that was generated, and then to eventually be able to print out all of the strings that have been favorited with the "Print Favorites" button. Can I somehow save the string as an array with str.split()?



var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];

function chooseStartup() {
var x = startupX[Math.floor(Math.random()*startupX.length)];
var y = startupY[Math.floor(Math.random()*startupY.length)];

document.getElementById('startupX').innerHTML = x;
document.getElementById('startupY').innerHTML = y;
};

<body>

<h1 id="xForY"></h1>
<h1 id="sentence">A startup that is
<span id="startupX"></span>, but for
<span id="startupY"></span>
</h1>
<div id="inputs">
<button onclick="chooseStartup()" id="create">Create New Startup</button>
<button id="save">Favorite Startup</button>
<button id="print">Print Favorites</button>
</div>

<h2 id="favorites">

</h2>


<script src='http://code.jquery.com/jquery-latest.min.js'></script>
<script src='js/madlib-console.js'></script>

</body>




Answer

Please find below a working example. Hope this helps.

var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];
var x = y = '',
  arr = [];

function chooseStartup() {
  x = startupX[Math.floor(Math.random() * startupX.length)];
  y = startupY[Math.floor(Math.random() * startupY.length)];

  document.getElementById('startupX').innerHTML = x;
  document.getElementById('startupY').innerHTML = y;
};

$('#save').click(function() {
  if (x != '' && y != '') {
    arr.push('A startup that is ' + x + ' but for ' + y);
  }
});

$('#print').click(function() {
  $('#favorites').html(arr.toString().split(',').join('<br />'));
});
<body>

  <h1 id="xForY"></h1>
  <h1 id="sentence">A startup that is 
    <span id="startupX"></span>, but for 
    <span id="startupY"></span>
</h1>
  <div id="inputs">
    <button onclick="chooseStartup()" id="create">Create New Startup</button>
    <button id="save">Favorite Startup</button>
    <button id="print">Print Favorites</button>
  </div>

  <h2 id="favorites">

  </h2>


  <script src='http://code.jquery.com/jquery-latest.min.js'></script>
  <script src='js/madlib-console.js'></script>

</body>

Comments