NeXuS NeXuS - 9 months ago 31
jQuery Question

Getting value for dynamic input of different types

I'm loading different types of input fields (textareas, radiobuttons, checkboxes) with ajax in my document.

var SugesstionValue = $('#EditModalAddSuggestionValue').val();
if(SugesstionValue === null || typeof SugesstionValue === 'undefined')
{SugesstionValue = $('#EditModalAddSuggestionRadioValue input:checked').val();}
alert(SugesstionValue);


I'm getting every time
undefined

Sometimes it works and sometimes not... I'm not sure what to do..

Answer Source

It's difficult to tell exactly what's going on without more code. But based on your description, it sounds like you have a race condition because the code you provided is not being run after you load your fields via ajax. That's why SuggestionValue is sometimes undefined and sometimes not.

When you select something from the DOM, it has to actually be in the DOM at the time you try to select it. That means you have to select ajax-loaded elements after you load them. You could do that in your success callback, provided you add the fields to the DOM before doing anything else.