The problem I have :
I click “add”
I select 2nd option
I click “add”
Problem : my first select-list’s selected option index = 0;
This should not happen, but I can’t figure out why it does it anyway. Can anyone tell me what I did wrong?
<script type="text/javascript">
function add(){
var div =document.getElementById('ruletemplate').cloneNode(true);
document.getElementById('rules').innerHTML += div.innerHTML;
return false;
}
</script>
<div id="ruletemplate" style="display: none;">
<div >
<label for="rule">Rule</label>
<select name="rules[][option]">
<option>MAX PERS</option>
<option>MIN PERS</option>
</select>
<input name="rule[][amount]" type="text"/>
</div>
</div>
<form>
<div id="rules" >
</div>
<a id="addRule" href="" onclick="javascript: add(); return false;">add</a>
<input type="Submit" value="Save" />
</form>
The reason it is doing that is you are setting the innerHTML which means the entire thing is reparsed. You will need to append the element to container instead. Try this it should keep each select’s position.