Clear all fields without page reload

Hi, I’d like to clear fields to default using the reset button, without having to refresh the whole page.

Pullo already showed me this way of clearing the fields in the below code.


<script>
     /*global $:false */
  function clearAnswerImages(){
        $("img").remove();
}


      function mark(el, status){
        var images = {
          correct: "http://www.littletherese.com/tick.jpg",
          incorrect: "http://www.littletherese.com/x.jpg",
          unanswered: "",
        },
        img = new Image();
        img.src = images[status];
        img.className = status;
        el.append(img);
      }

      function displayScore(){
        var numQuestions = $(".question").length,
            questionsCorrect = $("img.correct").length;

     $("#score").html("You got " + questionsCorrect + " out of " + numQuestions);
      }

      $("form").on("submit", function(e){
        e.preventDefault();
        clearAnswerImages();

       var $questions = $(".question");
        $questions.each(function(){
          var answer = $(this).find("input:checked"),
              key = answer.attr("name"),
              val = answer.attr("value");

          if(answer.length === 0){
            mark($(this).find("p"), "unanswered");
          } else if (answers[key] !== val){
            mark(answer.parent(), "incorrect");   // I  changed this line
          } else {
            mark(answer.parent(), "correct");
          }
        });

        displayScore();
      });

     $("input[type=reset]").on("click", function(){
  $("input:checked").prop("checked", false);
  $('#score').empty(); //I inserted this line
  clearAnswerImages();
});

       var answers = {
        "one": "b",
        "two": "c",
        "three": "a",
        "four": "c",
        "five": "b",
        "six": "c",
        "seven": "a",
        "eight": "a",
        "nine": "b",
        "ten": "c",

      };

    </script>


But, try as I might, I haven’t managed to adapt this code, starting:

$("input[type=reset]").on("click", function().. 

for another page using dropdown menus:

The page I would like to change is this:


<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Quiz with radio buttons</title>
    <style>
      label{ display: block; }
      input[type=submit]{ margin-top: 15px; }
    </style>
  </head>

  <body>
    <form>
      <div class="question">
        <p><strong>Q1</strong>: Mary is English. She was born in London</p>

        <label><input type="radio" name="one" value="a">Mary was born in England</label>
        <label><input type="radio" name="one" value="b">Mary, who is English, was born in London</label>
        <label><input type="radio" name="one" value="c">English Mary was born in London</label>
        <label><input type="radio" name="one" value="d">London Mary is English born</label>
      </div>

      <div class="question">
        <p><strong>Q2</strong>: Mary is English. She was born in London</p>

        <label><input type="radio" name="two" value="a">Mary was born in England</label>
        <label><input type="radio" name="two" value="b">Mary, who is English, was born in London</label>
        <label><input type="radio" name="two" value="c">English Mary was born in London</label>
        <label><input type="radio" name="two" value="d">London Mary is English born</label>
      </div>

      <input type="submit" />
      <input type="reset"  onClick="window.location.reload()"  value="Start again" />
    </form>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      function clearAnswers(){
        $("img").each(function(){
          $(this).remove();
        })
      }

      function markIncorrect(el){
        var img = new Image();
        img.src = 'http://www.littletherese.com/x.jpg';
        el.append(img);
      }

      function markCorrect(el){
        var img = new Image();
        img.src = 'http://www.littletherese.com/tick.jpg';
        el.append(img);
      }
        function markQ(el){
        var img = new Image(); // Finally I decided to omit the image "Q.jpg"
        img.src = '';
        el.append(img);
      }
      $("form").on("submit", function(e){
        e.preventDefault();
        clearAnswers();

        $questions = $(".question");
        $questions.each(function(){
          var answer = $(this).find("input:checked"),
              key = answer.attr("name"),
              val = answer.attr("value");

          if(answer.length === 0){
            markQ($(this).find("p"));
          } else if (answers[key] !== val){
            markIncorrect(answer.parent());   // I  changed this line
          } else {
            markCorrect(answer.parent());
          }
        });
      });

      var answers = {
        "one": "b",
        "two": "b"
      }
$("input[type=reset]").on("click", function(){
  window.location.reload()
}
    </script>
  </body>
</html>

Thanks for any help.

Hi for the last lot of code, when you run it and look in your browsers console (instructions), you see the following error.

Uncaught SyntaxError: Unexpected end of input j.html:87

What do you think might be causing that?

If you get rid of the onclick on the reset button does that fix the problem? The reset button is supposed to change all of the values in the form back to their initial values as its default action.

Ok, I see that there was a missing “)” in these lines:

     $("input[type=reset]").on("click", function(){ 
  window.location.reload()
}  

So, this code is clean in the console:

 
<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Quiz with radio buttons</title>
    <style>
      label{ display: block; }
      input[type=submit]{ margin-top: 15px; }
    </style>
  </head>

  <body>
    <form> 
      <div class="question">
        <p><strong>Q1</strong>: Mary is English. She was born in London</p>

        <label><input type="radio" name="one" value="a">Mary was born in England</label>
        <label><input type="radio" name="one" value="b">Mary, who is English, was born in London</label>
        <label><input type="radio" name="one" value="c">English Mary was born in London</label>
        <label><input type="radio" name="one" value="d">London Mary is English born</label>
      </div>

      <div class="question"> 
        <p><strong>Q2</strong>: Mary is English. She was born in London</p>

        <label><input type="radio" name="two" value="a">Mary was born in England</label>
        <label><input type="radio" name="two" value="b">Mary, who is English, was born in London</label>
        <label><input type="radio" name="two" value="c">English Mary was born in London</label>
        <label><input type="radio" name="two" value="d">London Mary is English born</label>
      </div>

      <input type="submit" />
      <input type="reset"  onClick="window.location.reload()"  value="Start again" /> 
    </form>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      function clearAnswers(){
        $("img").each(function(){
          $(this).remove();
        })
      }

      function markIncorrect(el){
        var img = new Image();
        img.src = 'http://www.littletherese.com/x.jpg';
        el.append(img);
      }

      function markCorrect(el){
        var img = new Image();
        img.src = 'http://www.littletherese.com/tick.jpg';
        el.append(img);
      } 
        function markQ(el){
        var img = new Image(); // Finally I decided to omit the image "Q.jpg"
        img.src = '';
        el.append(img);
      } 
      $("form").on("submit", function(e){
        e.preventDefault();
        clearAnswers();

        $questions = $(".question");
        $questions.each(function(){
          var answer = $(this).find("input:checked"),
              key = answer.attr("name"),
              val = answer.attr("value");

          if(answer.length === 0){ 
            markQ($(this).find("p"));
          } else if (answers[key] !== val){
            markIncorrect(answer.parent());   // I  changed this line
          } else {
            markCorrect(answer.parent());
          } 
        });
      });
      
      var answers = {
        "one": "b",
        "two": "b",
      }
$("input[type=reset]").on ("click"), function(){ 
  window.location.reload()
}
    </script>
  </body>
</html>

But, I still don’t see how to clear the fields with reset (without having to reload the page). (I think I already tried the basic html reset button without the javascript).

Have you tried deleting the JavaScript so that it no longer triggers a page reload. The reset button default action wit no JavaScript added is to reset all the fields in the form to their original values without reloading the page.

yea, I tried just this code without javascript added - doesn’t work. Thanks anyway.


 <input type="reset"  value="Start again" />

This should do it for you.
I updated the code to incorporate poes’ $("img").remove() suggestion.

I would ask that you look at what I changed and try to understand it.

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Quiz with radio buttons</title>
    <style>
      label{ display: block; }
      input[type=submit]{ margin-top: 15px; }
    </style>
  </head>

  <body>
    <form> 
      <div class="question">
        <p><strong>Q1</strong>: Mary is English. She was born in London</p>

        <label><input type="radio" name="one" value="a">Mary was born in England</label>
        <label><input type="radio" name="one" value="b">Mary, who is English, was born in London</label>
        <label><input type="radio" name="one" value="c">English Mary was born in London</label>
        <label><input type="radio" name="one" value="d">London Mary is English born</label>
      </div>

      <div class="question"> 
        <p><strong>Q2</strong>: Mary is English. She was born in London</p>

        <label><input type="radio" name="two" value="a">Mary was born in England</label>
        <label><input type="radio" name="two" value="b">Mary, who is English, was born in London</label>
        <label><input type="radio" name="two" value="c">English Mary was born in London</label>
        <label><input type="radio" name="two" value="d">London Mary is English born</label>
      </div>

      <input type="submit" />
      <input type="reset"  onClick="window.location.reload()"  value="Start again" /> 
    </form>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      function clearAnswers(){
        $("img").remove();
      }

      function markIncorrect(el){
        var img = new Image();
        img.src = 'http://www.littletherese.com/x.jpg';
        el.append(img);
      }

      function markCorrect(el){
        var img = new Image();
        img.src = 'http://www.littletherese.com/tick.jpg';
        el.append(img);
      } 
        function markQ(el){
        var img = new Image(); // Finally I decided to omit the image "Q.jpg"
        img.src = '';
        el.append(img);
      } 
      $("form").on("submit", function(e){
        e.preventDefault();
        clearAnswers();

        $questions = $(".question");
        $questions.each(function(){
          var answer = $(this).find("input:checked"),
              key = answer.attr("name"),
              val = answer.attr("value");

          if(answer.length === 0){ 
            markQ($(this).find("p"));
          } else if (answers[key] !== val){
            markIncorrect(answer.parent());   // I  changed this line
          } else {
            markCorrect(answer.parent());
          } 
        });
      });
      
      var answers = {
        "one": "b",
        "two": "b",
      }

      $("input[type=reset]").on ("click"), function(){ 
        clearAnswers();
        $(":radio").prop("checked", false);
      }
    </script>
  </body>
</html>

Maaaadre mia…Sorry, I must have got my codes mixed up. My original intention was about clearing the form in this page (without having to reload):


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
  
       
 
   <title>English</title>
   
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  	<meta name="robots" content="index, follow"/>
   <meta name="description" content=""/>
<meta name="author" content="johnk" />

<meta name="keywords" content=""/>


    
    
    <style>
      ol li {
        background-image: none;
        padding:10px;
      }
    </style>

  </head>
  <body>
    <div id="pagewrap"> 
      <div id="container">
        <div id="content">
           
    
       
	  				

          <h4>For, since or ago?</h4>
          <div class="scroll">
            <form method="post" id="myForm" name="f">
              <ol>
                <li>
               It's been raining 
                  <select name="question1">
                    <option value="na">&nbsp;</option>
                    <option value="a"> for </option>   
                    <option value="b"> since </option>
                      <option value="c"> ago </option>  
                  </select> 
                 2 hours.
                </li>
                <li>
                  They have lived here
                  <select name="question2">
                   <option value="na">&nbsp;</option>
                    <option value="a"> for </option>   
                    <option value="b"> since </option>
                      <option value="c"> ago </option>  
                  </select>
                 1990.
                </li>
                
              </ol>
            
             <input type="submit" id="submit" value="Result" />
              <input type="reset" class="reset" id="reset" name="reset" value="Start again" />
            </form>
             <div id="score"></div> 
               <div class="address">
           
            </div>
          </div> 
        </div> 
      </div> 
    </div>
    
    <script>
      Object.size = function(obj) {
        var size = 0, key;
        for (key in obj) {
          if (obj.hasOwnProperty(key)) size++;
        }
        return size;
      };
      
      (function(){
        "use strict";
        window.checkAnswers = function(opts){
          
          function validateInput(){
            var question,
                answer;
                
            for (question in opts) {
              if(opts.hasOwnProperty(question)) {
                answer = f.elements[question].options[f.elements[question].selectedIndex].value;
                if(answer === "na"){
                  opts[question].state = "not-filled-in";
                } else if(answer === opts[question].answer){
                  opts[question].state = "correct";
                } else {
                  opts[question].state = "error";
                }
              }
            }
          }
          
          function markCorrectOrIncorrect(){
            var question, 
                li;
            
            for (question in opts) {
              if(opts.hasOwnProperty(question)) {
                var img = new Image(),
                li = f.elements[question].parentElement,
                feedbackImg = li.getElementsByTagName('img')[0];

                if (feedbackImg){
                  li.removeChild(feedbackImg);
                }
                
                if(opts[question].state === "correct"){
                  img.src = "http://www.littletherese.com/tick.jpg";
                  li.appendChild(img)
                } else if(opts[question].state === "error"){
                  img.src = "http://www.littletherese.com/x.jpg";
                  li.appendChild(img)
                }
              }
            }
          }
          
          function displayScore(){
            var correct = 0,
                error = 0,
                score = document.getElementById("score"),
                totalQuestions = Object.size(opts),
                question;

            for (question in opts) {
              if(opts.hasOwnProperty(question)) {
                if(opts[question].state === "correct"){
                  correct ++
                } else if(opts[question].state === "error"){
                  error ++
                }
              }
            }
            score.innerHTML = "You got " + correct + " out of " + totalQuestions;
          }
          
          function init(){
            validateInput();
            markCorrectOrIncorrect();
            displayScore();
          }
          
          init();
        }
      }());

      f.onsubmit = function(){
        checkAnswers({
          question1: {answer: "a"},
          question2: {answer: "b"},
       
        })
        return false;
      }
      
       f.reset.onclick = function(){
        location.reload();
      }
      
    </script> 
  </body>
</html>    

My other page with radio buttons is already working fine; sorry for the confusion.

Oh dear!

Ok, well change this:

f.reset.onclick = function(){
  location.reload();
}

to this:

f.reset.onclick = function(){
  var imgs = document.querySelectorAll('img');
  for(var i=0; i<imgs.length; i++){
    imgs[i].parentNode.removeChild(imgs[i]);
  }

  document.getElementById("score").innerHTML = "";
}

and all will be well :slight_smile:

BTW, where did you get the code you posted?
Did I write that?

Yea, that was code you posted (I mean the javascript) from a previous thread: http://www.sitepoint.com/forums/showthread.php?1188783-radio-buttons-to-replace-dropdown-menu.

Yea, I did try different ways of adapting that code (without any success), for example:



   f.reset.onclick = function(){
  }
document.getElementById("score").empty();
}

But anyway, I’ll really try to peruse the code you sent me to see if I can make head or tail of it! Thanks, it works great now!

Hi there,

empty() is a jQueryism, so won’t work without the jQuery library :slight_smile: