DjH
DjH

Reputation: 1498

Jquery if statement based on input values

I'm making a simple form and I'm having trouble getting it to do what I want. On form submission I need it to detect if multiple inputs of a certain category have values greater than 0 (because only one should be selected). Here's the html of the form

      <form onsubmit="calcTime();">

  <table>
    <tr>
      <p>How long does the task take to perform?  (Choose one)</p></tr>
    <tr>
      <p>
        <input type="text" style="width: 3em;" id="seconds">&nbsp;  Seconds (Enter an integer 1-60)
        <input type="text" style="width: 3em;" id="minutes">&nbsp;  Minutes (Enter an integer 1-60)
      </p>
    </tr>
    <br>
    <tr>
      <p>How often do you perform the task? (Choose one)</p></tr>
    <tr>
      <p><input type="text" style="width: 3em;" id="day">&nbsp;x Per day&nbsp;
        <input type="text" style="width: 3em;" id="week">&nbsp;x Per week&nbsp;
        <input type="text" style="width: 3em;" id="month">&nbsp;x Per month&nbsp;
        <input type="text" style="width: 3em;" id="year">&nbsp;x Per year&nbsp;
      </p>
    </tr>
    <br>
    <tr>
      <p><input type="submit" value="Submit" id="submitButton"></p>
    </tr>

    <br>
    <tr>
      <p id="result"></p>
    </tr>
  </table>
</form>

The jQuery function that isn't working so far is this...

function calcTime() {
var seconds = $('#seconds');
var minutes = $('#minutes');
var perDay = $('#day');
var perWeek = $('#week');
var perMonth = $('#month');
var perYear = $('#year');
if ((seconds.value > 0) && (minutes.value > 0)) {
alert('Please only choose either seconds or minutes!');
return false;
  }
}

Thanks

Upvotes: 0

Views: 100

Answers (2)

pedrotp
pedrotp

Reputation: 308

Using jQuery you can change your 'if' statement to:

if (seconds.val() > 0 && minutes.val() > 0)

More info about the .val() method: http://api.jquery.com/val/

Upvotes: 1

Viktor Kukurba
Viktor Kukurba

Reputation: 1370

Use jquery method val to retrieve elements value.

seconds.val()

If you do not use jquery to select element, but pure Javascript

var seconds = document.getElementById('seconds')

you will be able use value property seconds.value.

Jquery select returns 'it's own' object not native HTMLElement.

Upvotes: 1

Related Questions