BaronGrivet BaronGrivet - 16 days ago 8
jQuery Question

How to make jQuery changes to <select> dropdown register in the HTML

I'm working on a project with a large dynamic form. The form can be manipulated by jQuery and saved as HTML (to be outputted to a PDF).

When changes are made to

<select>
dropdowns the change isn't reflected in the HTML, so when the form is saved the wrong option is displayed.

Code Example: http://jsfiddle.net/BaronGrivet/n4bxzr49/1

<p>Original Form</p>
<form id="form">
<select id="select">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="carrot">Carrot</option>
</select>
</form>
<p>Form Saved then Loaded via jQuery</p>
<div id="output"></div>


Javascript:

$('#select').val('carrot');
var formHTML = $('#form').html();
$('#output').html(formHTML);


Returns:

enter image description here

Is this expected behaviour? What is the best alternative for setting the value of a
<select>
dropdown in jQuery so it also shows in the HTML?

Answer

You need to manually set selected attribute. It will not be reflected in the html when you change the selected property in the dom

Can do something like:

$('option:selected').attr('selected',true);

Note that you will have the same issue with any <input> whereby the attribute value will not reflect user changes. There is a difference between attribute value and value property

For text inputs you could do something like:

$('input:text').attr('value',function(){
   return this.value;
});

For checked radios and checkbox you need to set checked attribute something like:

$('input:checked').attr('checked',true)

In other words, to answer your question, the behavior you are seeing is as expected

DEMO

Comments