Rich2233
Rich2233

Reputation: 185

Checking empty form elements in javascript

I'm making a simple client-side, self-grading quiz.

I ask 6 questions and I want to alert the user with their score (keeping things simple). If they leave an answer blank, an alert will appear.

I'm new to javascript and don't really know how to check individual form elements to see if they're empty. I'm also having problems with getting my code to run.

JS

EDIT

function grade() {
    var score = 0;
    var elt = document.quiz;

    // Check to see if no questions were left unanswered.
    if elt.question1.value.length == 0 || elt.question2.value.length == 0 ||   
       elt.question3.value.length == 0 || elt.question4.value.length == 0 ||
       elt.question5.value.length == 0 || elt.question6.value.length == 0
      {
        alert ("Whoops, you're missing an answer!")
    }

    if (elt.question1[1].checked) {
        score += 1;
    }
    if (elt.question2[0].checked) {
        score += 1;
    }
    if (elt.question3[0].checked == false && elt.question3[1].checked &&  
        elt.question3[2].checked == false && elt.question3[3].checked == false) {
        score += 1;
    }
    if (elt.question4[0].checked == false && elt.question4[1].checked == false &&
        elt.question4[2].checked == false && elt.question4[3].checked) {
        score += 1;
    }
    elt.question5 = elt.question5.toLowerCase()
    if (elt.question5.value != '' && elt.question5.value.indexOf('galaxy') != -1) {
        score += 1;
    }
    elt.question6 = elt.question6.toLowerCase()
    if (elt.question5.value != '' && elt.question6.value.indexOf('age') != -1) {
        score += 1;
    }

    score = score / 6 * 100;
    score = score.toFixed(2);
    alert("You scored " + score + "%");

    return false; // Return true if you want the form to submit on validation/grade
}

Upvotes: 0

Views: 1078

Answers (3)

Jared Farrish
Jared Farrish

Reputation: 49238

You have a some significant errors in your markup:

  1. Do not wrap a form element around each question. These should all be in one form element. (Also, each question be in a OL to number the question in series.)
  2. You're not properly closing all of your label's, so they're selecting other elements when you click them (try question 3, first checkbox).
  3. You need the grade() function on the form's submit handler, and it needs to be onsubmit="return grade()", with grade() returning false when it doesn't "pass" to prevent form submission*.

* Note, I set the grade() function to always return false in the example. You would need to add the logic for when it would allow the form to submit.

As far as the Javascript...

You need the elt variable to be equal to your document.quiz (note, I changed the main form to have a name="quiz" in your markup). You can use indexOf() instead of a regex if you just want to have a simple check (regex could check for age as a word, though).

If you just want to make sure a text input is not empty, you can use el.value.length != 0 or el.value != ''.

Also, looking at your grading code, if you want only one to be selected, you could use a radio, unless you want the person taking the quiz to not know if one or more were valid answers. But radio's only allow you to select a single value.

HTML

<h3> Self-Grading Astronomy Quiz </h3>
<form action="" name="quiz" onsubmit="return grade();">
 <p>1. According to Kepler the orbit of the earth is a circle with the sun at the center.</p>
 <p>
  <label><input type="radio" name="question1" value="true" /> True </label>
  <label><input type="radio" name="question1" value="false" /> False </label>
 </p>
 <p>2. Ancient astronomers did consider the heliocentric model of the solar system but rejected it because they could not detect parallax.</p>
 <p>
  <label><input type="radio" name="question2" value="true" /> True </label>
  <label><input type="radio" name="question2" value="false" /> False </label>
 </p>
 <p>3. The total amount of energy that a star emits is directly related to its:</p>
 <p>
  <label><input type="checkbox" name="question3" value="1" /> a) surface gravity and magnetic field </label><br/>
  <label><input type="checkbox" name="question3" value="2" /> b) radius and temperature </label><br/>
  <label><input type="checkbox" name="question3" value="3" /> c) pressure and volume </label><br/>
  <label><input type="checkbox" name="question3" value="4" /> d) location and velocity </label>
 </p>
 <p>4. Stars that live the longest have:</p>
 <p>
  <label><input type="checkbox" name="question4" value="1" /> a) high mass </label><br/>
  <label><input type="checkbox" name="question4" value="2" /> b) high temperature </label><br/>
  <label><input type="checkbox" name="question4" value="3" /> c) lots of hydrogen </label><br/>
  <label><input type="checkbox" name="question4" value="4" /> d) small mass </label>
 </p>
 <p>5. A collection of a hundred billion stars, gas, and dust is called a __________.</p>
 <p>
  <input type='text' id='question5' />
 </p>
 <p>6. The inverse of the Hubble's constant is a measure of the __________ of the universe.</p>
 <p>
  <input type='text' id='question6' />
 </p>
 <p>
  <input type='button' onclick='grade()' value='Grade' />
 </p>
</form>

Javascript

function grade() {
    //**Would I do something like this?
    //if(elem.value.length == 0){
    // alert("Whoops, looks like you didn't answer a question.")}
    var score = 0;
    var elt = document.quiz;

    if (elt.question1[1].checked) {
        score += 1;
    }
    if (elt.question2[0].checked) {
        score += 1;
    }
    if (elt.question3[0].checked == false && elt.question3[1].checked && elt.question3[2].checked == false && elt.question3[3].checked == false) {
        score += 1;
    }
    if (elt.question4[0].checked == false && elt.question4[1].checked == false && elt.question4[2].checked == false && elt.question4[3].checked) {
        score += 1;
    }
    if (elt.question5.value != '' && elt.question5.value.indexOf('galaxy') != -1) {
        score += 1;
    }
    if (elt.question5.value != '' && elt.question6.value.indexOf('age') != -1) {
        score += 1;
    }

    score = score / 6 * 100;
    score = score.toFixed(2);
    alert("You scored " + score + "%");

    return false; // Return true if you want the form to submit on validation/grade
}

http://jsfiddle.net/BeD3Z/10/

Upvotes: 1

Keith.Abramo
Keith.Abramo

Reputation: 6965

You can use jquerys built in validation http://docs.jquery.com/Plugins/validation. It has built in functionality to check for required and to display an error message below the field which is blank.

Upvotes: 1

Jack
Jack

Reputation: 9548

check individual form elements to see if they're empty

You just compare the value to an empty string:

if(elt.question6.value == '') {
  alert('Unanswered');
}

Upvotes: 1

Related Questions