George-Valentin Pele
George-Valentin Pele

Reputation: 65

Form disappears on function call

I have the following button inside a form and a javascript method SizeGuide

var four="4OZ"
function SizeGuide(){
  if(document.getElementById("training").checked)
    document.getElementById("show").innerHTML = four;
}
 <button id="hello" onclick="SizeGuide()">Size:</button><p id="show"></p>

When clicking on the button, I just want to display the variable. My problem is that the variable is showing for a second or so then it crashes and the form disappears. "training" is a simple input radio button. Thank you very much!

Upvotes: 1

Views: 120

Answers (2)

MrCode
MrCode

Reputation: 64526

As you haven't declared a type for the button, it defaults to a submit button. Add a type="button" attribute and it will no longer submit the form.

<button type="button" id="hello" onclick="SizeGuide()">Size:</button><p id="show"></p>
        ^^^^ set the type

Upvotes: 1

Richard Muvirimi
Richard Muvirimi

Reputation: 844

Not sure what your checked method does but you have to stop the default form action by calling preventDefault()

var four="4OZ"
function SizeGuide(e){
  e.preventDefault(); //prevent default form action

  if(document.getElementById("training").checked){
    document.getElementById("show").innerHTML = four;
  }
}
 <button id="hello" onclick="SizeGuide(event)">Size:</button><p id="show"></p>

Upvotes: 1

Related Questions