Using jquery in an element inserted from php with ajax

2

I have inserted a select of a php with ajax in another php that is the index. This is the index of where I take the data.

<?php 
include 'conexion.php';
$msg ="";
$tipo= $_POST['tipo']??"";
$sql = "SELECT marca.idmarca as id,marca.marca as marca
from marca, producto, modelo
where producto.modelo = modelo.idmodelo
and modelo.marca = marca.idmarca
and producto.tipo = '$tipo'";
$consulta = $conn->query($sql);
$msg .= "<select id=\"marc\">";
$msg .= "<option value=\"\">Selecciona una marca</option>";

while($fila = $consulta->fetch()){
$msg .= "<option value=\"".$fila['id']."\">".$fila['marca']."</option>";

}
$msg .= "</select>";
echo $msg;
?>

And picking up the id of the select in the jquery does not do anything to me. The jquery link is in the index.php.

//Codigo jquery

$("#marc").change(function(){
 var tipo = $(this).val();
 alert(tipo);

});
    
asked by Borja Sanchez 13.03.2017 в 16:53
source

2 answers

-2

When dealing with dynamic elements you have to use the on , whether for clik, change, etc.

Try using:

$("#marc").on('change', function(){
  var tipo = $(this).val();
  alert(tipo);
});
    
answered by 13.03.2017 / 16:57
source
1

The problem is that the id marc is not loaded in DOM when you want to use your function:

// No sabe la id #marc
$('#marc').on('change', function(){
  
  var tipo = $(this).val();
  alert(tipo);  
});

function ajaxSelect(){
  
  $('body').append('<select id="marc"><option value="">Selecciona</option><option value="1">1</option><option value="2">2</option></select>');
}

$('button').click(ajaxSelect);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Crear Ajax Select</button>

What you can do is what @GustavoGarcia has told you in the commentary or you can also delegar the event:

// Delegamos el evento
$(document).on('change', '#marc', function(){
  
  var tipo = $(this).val();
  console.log(tipo);
  
});

function ajaxSelect(){
  
  $('body').append('<select id="marc"><option value="">Selecciona</option><option value="1">1</option><option value="2">2</option></select>');
}

$('button').click(ajaxSelect);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Crear Ajax Select</button>
    
answered by 13.03.2017 в 17:33