简体   繁体   中英

jQuery inArray function not grabbing value on change select

I'm trying to show an element if a specific value in a select is selected:

    $(function () {
        $("#add_category3").change(function() {

            var id = $(this).val();

            if (jQuery.inArray(id, vehicles) !== -1)
                $("#vehicle-fields").show();
             else
                $("#vehicle-fields").hide();

            console.log(id);

        });
    });

It works fine if I change the variable id for the actual value in the inArray() function (hardcoring the value), but it doesn't when I use the variable id .

The console.log(id) gives back the actual value that makes que element show up, so I don't know why it's not working.

Sounds like you're having a type issue to me. You have to remember that inArray is type sensitive. So your val() is coming through as a string (most likely), but the array has int arrays you'll always get a -1 return on inArray. Cast this.val() call to an int

parseInt($(this).val(), 10);
function inArray(arrays,id){
  var inarray = false;
    for (var i = 0, l = arrays.length; i < l; i++) {
      if (arrays[i] == id) {
        inarray = true;
        break;
      }
    }
  return inarray;
}

use your own custom inArray. Because inarray doesn't compare string values to integers.

$(function () {
    $("#add_category3").change(function() {

        var id = $(this).val();

        if (inArray(vehicles,id))
            $("#vehicle-fields").show();
         else
            $("#vehicle-fields").hide();

        console.log(id);

    });
});

尝试使用trim(id),可能有一些白色间距

This is not work because of you use !== in if condition. Try != in if condition and it will work. Use below code which I improved your code.

$(function () {
    $("#add_category3").change(function() {

        var id = $(this).val();

        if (jQuery.inArray(id, vehicles) != -1)
            $("#vehicle-fields").show();
         else
            $("#vehicle-fields").hide();

        console.log(id);

    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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