-1

my function works perfectly fine, but i only see the result for 1 second and then the page loads on its own

i've tried

<button onclick="person.generate() return false">generate !</button>
<form>
                    <input type="text" id="roastInput" placeholder="put the roast here">
                    <input type="range" id="lvlOfRoast" min="1" max="5">
                    <select id="selector">
                        <option>select the topic</option>
                        <option value="cheap">cheap</option>
                        <option value="ugly">ugly</option>
                        <option value="fat">fat</option>
                        <option value="short">short</option>
                    </select>
                    <button onclick="person.generate()">generate !</button>
                </form>
var lvlOfRoast = document.getElementById("lvlOfRoast");

var selector = document.getElementById("selector");

var roastInput = document.getElementById("roastInput").value;

// -------------generate roast-------------

class roastGenerator {

  generate(){
    for (var i = 0; i < selector.length; i++) {
      console.log("this is the " + i + " try" );
    if(lvlOfRoast.value == 1){
      if(selector.options[i].value == "cheap"){
      document.getElementById("generatedRoast").innerHTML = "it works!!" ;
      break;
    }else {
     console.log("pls choose cheap");

    }
}else{
  window.alert("pls choose 1");
  break;
}
}
};
  randomRoast(obj){
                var keys = Object.keys(obj)
                return obj[keys[ keys.length * Math.random() << 0]];
            };
} // close bracket for the class

var person = new roastGenerator();
mhd HD
  • 15
  • 5

1 Answers1

1

Your form assumes that the button is a form submit button so whenever the button is clicked, the form attempts to send the data either to what you have specified in the action attribute or to the page itself (thus causing the reload) if no action attribute is specified or if the action attribute doesn't have a value.

Just add type="button" to your button element to tell your form that your button is not a submit invoker but just a normal button.

tldr: Adding the above attribute type="button" will prevent the button click from trying to submit the form data.

<button type="button" onclick="person.generate()">generate !</button>
AndrewL64
  • 15,794
  • 8
  • 47
  • 79