简体   繁体   English

if/else else if in Jquery 条件

[英]If/else else if in Jquery for a condition

I am having a set of text fields where i am doing validation Say I am Having a field called "seats" this can accept value less than "99999".Meaning I should not able to enter the "99999" any thing less than that is ok.我有一组文本字段,我正在做验证假设我有一个名为“seats”的字段,它可以接受小于“99999”的值。这意味着我不应该输入“99999”任何小于它的东西行。 For that I wrote below if and else if.为此,我在下面写了 if 和 else if。 please tell me whether I am doing any thing wrong.请告诉我我是否做错了什么。 I am confused a lot from morning whether it should be less than or greater than从早上开始我很困惑它应该小于还是大于

if ($("#seats").val() != '') {
    setflag = false;
    alert("Not a valid character")
}
else if($("#seats").val() < 99999) {
    alert("Not a valid Number");
} else {
    setflag = true;
}

Iam confused a lot from morning whether it should be less than or greater than`我从早上开始就很困惑它应该小于还是大于`

this can accept value less than "99999"这可以接受小于“99999”的值

I think you answered it yourself... But it's valid when it's less than .我想你自己回答了......但是当它小于时它是有效的。 Thus the following is incorrect:因此以下说法是不正确的:

}elseif($("#seats").val() < 99999){
  alert("Not a valid Number");
}else{

You are saying if it's less than 99999, then it's not valid .你是说如果它小于99999,那么它是无效的 You want to do the opposite:你想做相反的事情:

}elseif($("#seats").val() >= 99999){
  alert("Not a valid Number");
}else{

Also, since you have $("#seats") twice, jQuery has to search the DOM twice.此外,由于您有两次$("#seats") ,jQuery 必须搜索 DOM 两次。 You should really be storing the value, or at least the DOM element in a variable.您确实应该将值或至少是 DOM 元素存储在变量中。 And some more of your code doesn't make much sense, so I'm going to make some assumptions and put it all together:还有一些你的代码没有多大意义,所以我将做一些假设并将它们放在一起:

var seats = $("#seats").val();

var error = null;

if (seats == "") {
    error = "Number is required";
} else {
    var seatsNum = parseInt(seats);
    
    if (isNaN(seatsNum)) {
        error = "Not a valid number";
    } else if (seatsNum >= 99999) {
        error = "Number must be less than 99999";
    }
}

if (error != null) {
    alert(error);
} else {
    alert("Valid number");
}

// If you really need setflag:
var setflag = error != null;

Here's a working sample: http://jsfiddle.net/LUY8q/这是一个工作示例: http : //jsfiddle.net/LUY8q/

A few more things in addition to the existing answers.除了现有的答案之外,还有一些事情。 Have a look at this:看看这个:

var seatsValid = true;
// cache the selector
var seatsVal = $("#seats").val();
if(seatsVal!=''){
    seatsValid = false;
    alert("Not a valid character")
    // convert seatsVal to an integer for comparison
}else if(parseInt(seatsVal) < 99999){
    seatsValid = false;
    alert("Not a valid Number");
}

The variable name setFlag is very generic, if your only using it in conjunction with the number of seats you should rename it (I called it seatsValid).变量名 setFlag 是非常通用的,如果您只将它与座位数结合使用,您应该重命名它(我将其称为seatValid)。 I also initialized it to true which gets rid of the need for the final else in your original code.我还将它初始化为 true ,这样就不需要原始代码中的最后一个 else 。 Next, I put the selector and call to .val() in a variable.接下来,我将选择器并调用 .val() 放在一个变量中。 It's good practice to cache your selectors so jquery doesn't need to traverse the DOM more than it needs to.缓存您的选择器是一种很好的做法,因此 jquery 不需要比它需要的更多地遍历 DOM。 Lastly when comparing two values you should try to make sure they are the same type, in this case seatsVal is a string so in order to properly compare it to 99999 you should use parseInt() on it.最后,在比较两个值时,您应该尝试确保它们是相同的类型,在这种情况下,seatVal 是一个字符串,因此为了正确地将其与 99999 进行比较,您应该在其上使用 parseInt()。

将小于运算符更改为大于或等于运算符:

}elseif($("#seats").val() >= 99999){

See this answer .看到这个答案 val() is comparing a string , not a numeric value . val() 比较的是字符串,而不是数值

If statement for images in jquery:
#html

<button id="chain">Chain</button>
<img src="bulb_on.jpg" alt="img" id="img"/>

#script
    <script>
        $(document).ready(function(){
            $("#chain").click(function(){
            if($("#img").attr('src')!='bulb_on.jpg'){
                $("#img").attr('src', 'bulb_on.jpg');
            }
            else
            {
                $("#img").attr('src', 'bulb_onn.jpg');
            }
            });
        });
    </script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <form name="myform">
    Enter your name
    <input type="text" name="inputbox" id='textBox' value="" />
    <input type="button" name="button" class="member" value="Click1" />
    <input type="button" name="button" value="Click2" onClick="testResults()" />
  </form>
  <script>
    function testResults(n) {
      var answer = $("#textBox").val();
      if (answer == 2) {
        alert("Good !");
      } else if (answer == 3) {
        alert("very Good !");
      } else if (answer == 4) {
        alert("better !");
      } else if (answer == 5) {
        alert("best !");
      } else {
        alert('wrong');
      }
    }
    $(document).on('click', '.member', function () {
      var answer = $("#textBox").val();
      if (answer == 2) {
        alert("Good !");
      } else if (answer == 3) {
        alert("very Good !");
      } else if (answer == 4) {
        alert("better !");
      } else if (answer == 5) {
        alert("best !");
      } else {
        alert('wrong');
      }
    });
  </script>

And if you wanna make some if else with css attribute you can do it like this this program used to make highlight button for some text with jquery如果你想用 css 属性做一些 if else 你可以像这样做这个程序用来为一些带有 jquery 的文本制作高亮按钮

  HTML :

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <title>Document</title> </head> <style>:myclass { background-color; yellow: font-weight; bold, } </style> <body> <h1>PTIK FKIP UNS</h1> The <span class="warna">Faculty of Teacher Training and Education</span>,<span class="warna">Sebelas Maret University</span>. Surakarta is an <span class="warna">Educational Personnel Education Institution (LPTK)</span> which has 24 study programs in 6 majors, Each study program has its own characteristics in producing <span class="warna">superior. strong and intelligent educational staff.</span> <br> <br> The <span class="warna">Informatics and Computer Technology Education (PTIK)</span> tudy program is planned to take shelter in the management of the <span class="warna">Engineering and Vocational Education (PTK)</span> department, This placement revises our previous statement. where the PTIK study program is under the P.MIPA department. PTIK is a study program that will produce graduates who are <span class="warna">prioritized to teach in vocational/vocational programs,</span> So, it would be better if PTIK was under the PTK department which oversees vocational programs such as<span class="warna">Building Engineering Education,</span>and <span class="warna">Mechanical Engineering Education </span>To meet the needs of lecturers in the field of information technology that cannot be met by the PTK department: PTIK will conduct <span class="warna">resource sharing with the mathematics study program</span> </div> <script src="https.//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#Highlight").click(function(){ if($(".warna").hasClass('myclass')){ $(".warna");removeClass('myclass'). } else { $(".warna");addClass('myclass'); } }); }); </script> <br><br> <button id="Highlight">Highlight Paragraf</button> </body> </body> </html>

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

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