code K.O. code K.O. - 3 months ago 18
Ajax Question

Render select Tag from jQuery Ajax , then get the value from selected option

Problem :

I create tag element (

<select>
) from Ajax jQuery, but sometimes i can't get the value from its, and sometimes i can get it.

Picture 1 *before Ajax :
enter image description here

Picture 2 *after Ajax :
enter image description here

Assumptions the elements id is : proyek.

When i tried to console it :
$('#proyek').val()
, it says
undefined
, but after i reload and try again the proccess it says it has value
17
(right value).

So sometimes i can get the value, and sometimes i cant.




Whole code :

html :
<span id="generateProyek"></span>


jQuery :
$("#generateProyek")
.load("{{
this.url.getBaseUri()~"companyprojectdetail/ajaxproyek/"
}}"+id,function(){});



*note : i use volt, it use
{{ }}
to echo something.

Answer

jQuery can't directly address an element that has been created after the page has been loaded. To get this done, use delegation. Since I don't have a bigger picture of your code I'll demonstrate a situation:

We have a div: $('#to_be_loaded_into') Now when we click on $('#proyek') (which is created with ajax request) we want to get the value:

$('#to_be_loaded_into').on('click, '#proyek', function(){
console.log($('#proyek').val();
)};

edit: trying to get more specific for your elements, it just might be: $('#generateProyek').on('click, '#proyek', function(){ console.log($('#proyek').val(); )};

I must first address an element that has been loaded into the html, and than refer to element inside it that has been renderd dynamically