ajax - get value from dynamic dropdown jquery -
i trying option value dropbox created dynamically throught ajax jquery, depending of selection of dropbox, till no success.
the structure have this:
html dropbox 1:
<select id="slt1"> <option value="" selected>select</option> <?php foreach($prozess $p): ?> <option value="<?php echo $p->id; ?>"><?php echo $p->name; ?></option> <?php endforeach; ?> </select>
dropbox 2:
<select id="slt2"></select>
in relation selection of dropbox 1 result of dropbox 2
ajax jquery looks this:
$.ajax({ data: { id_prozess : $(#slt1).val() }, url: 'page.php', type: 'post', datatype: 'json', success: function (r) { $(#slt1).prop('disabled', false); $(#slt2).find('option').remove(); $(r).each(function(i, v){ // indice, valor $(#slt2).append('<option value="' + v.id + '">' + v.name + '</option>'); }) }, error: function(){ alert('ocurrio un error en el servidor ..'); } });
in moment when try values of selected item in dropbox 2 start headache. how tried:
$(#slt2).on( "change", function() { alert( $("#slt2").val() ); });
but till same answer: undefined
can me headache?
as other answers have pointed out, have typo in jquery selection, $(#slt2)
since aren't wrapped in ''
or ""
, might cause trouble.
neither telling run code bind change
event, might of interest.
in case running before dropdown has been created, referencing element @ moment not yet exists. can bind events binding object exists @ time code runs, link desired object. see fiddle below create , append dropdown after 3 seconds, , binding run before.
$('body').on('change', '#slt2', myfunction); settimeout(function() { var optionlist = ["volvo", "saab", "bmw"]; var dropdown = $("<select></select>").attr("id", "slt2"); $.each(optionlist, function(i, el) { dropdown.append("<option>" + el + "</option>"); }); $("#dropdown-container").append(dropdown); }, 3000); function myfunction() { alert($(this).val()); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="dropdown-container"> </div>
Comments
Post a Comment