JQuery double change double select

I have a problem with jQuery change related to select tag. It works twice, the second time returns an empty array. jQuery or JS are not included twice, are already checked.

I would really appreciate any help in this area :)

Js

$(".select-car").on("change", function(){ var cars = []; var carType = $(this).val(); $.getJSON("js/cars.json", function(data) { $.each(data, function(i, item) { // console.log(item); if(item.type === carType) { cars.push(item); } }); }); console.log(cars); }); 

HTML

 <!DOCTYPE html> <html lang="pl"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css"> <title>Wyporzyczalnia samochodów</title> </head> <body> <main class="container main-container"> <div class="row select-car"> <div class="col-md-12 header"> <h2 class="page-header">Wybierz typ samochodu</h2> <form action=""> <select name="cartype" class="form-control select-car"> <option value="" selected="true" disabled>---</option> <option value="camper">Camper</option> <option value="limuzyna">Limuzyna</option> <option value="osobowy">Osobowy</option> </select> </form> </div> </div> <!-- Select car --> <div class="row avaible-cars"> </div> </main> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/main.js"></script> </body> </html> 
+6
source share
1 answer

You have two .select-car classes

 <div class="row select-car"> 

and in

 <select name="cartype" class="form-control select-car"> 

This causes a double call. And therefore, the event of change has been tied twice.

+4
source

Source: https://habr.com/ru/post/1014047/


All Articles