Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't use jQuery to change select value to option dynamically populated by ajax
    text
    copied!<p>Changing the value of a select option just like this, <a href="http://jsfiddle.net/ueDTd/" rel="nofollow">http://jsfiddle.net/ueDTd/</a>, doesn't work if the options are populated by AJAX.</p> <p>This is supposed to change the option back to what it was after the page reloads because the form is found invalid (missing required fields, etc)</p> <p>The result is that it always changes to the first dynamically populated result which also happens to have a value of "1".</p> <p>Here is the code in its entirety including the AJAX call:</p> <pre><code>$(document).ready( function() { var dh_json; var url = base_url+'doc_headings/get_json_doc_headings'; $.ajax({ url: url, dataType: 'json', success: function(encoded_json){ dh_json = encoded_json; $.each(encoded_json, function(key, index) { $('#doc_headings').append( $('&lt;option&gt;', { value : index.id } ) .text(index.content) ); }); } // End of success function of ajax form }); // End of ajax call $('#doc_headings').change(function() { var dh_el_value = $('#doc_headings').val(); $.each(dh_json, function(key, index) { if (index.id == dh_el_value) { $('#body').attr("placeholder", index.directions); } }); }); $('select#doc_headings').val(doc_headings_selected); </code></pre> <p>});</p> <p>and here is the HTML for the select element:</p> <pre><code> &lt;select id="doc_headings" name="doc_headings"&gt; &lt;option disabled="disabled" value="no" selected="selected"&gt; - Document Type - &lt;/option&gt; &lt;/select&gt; </code></pre> <p>How can I change the value of a select field with ajax-generated options?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload