简体   繁体   English

jQuery if语句基于输入值

[英]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). 在提交表单时,我需要它来检测某个类别的多个输入是否具有大于0的值(因为仅应选择一个)。 Here's the html of the form 这是表格的html

      <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... 到目前为止无法使用的jQuery函数是...

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 谢谢

Use jquery method val to retrieve elements value. 使用jquery 方法val检索元素值。

seconds.val()

If you do not use jquery to select element, but pure Javascript 如果不使用jquery选择元素,而是使用纯Javascript

var seconds = document.getElementById('seconds')

you will be able use value property seconds.value . 您将可以使用value属性seconds.value

Jquery select returns 'it's own' object not native HTMLElement . jQuery select返回“本身”对象而不是本地HTMLElement

Using jQuery you can change your 'if' statement to: 使用jQuery,您可以将'if'语句更改为:

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

More info about the .val() method: http://api.jquery.com/val/ 有关.val()方法的更多信息: http ://api.jquery.com/val/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM