If selected option is equal to 2, I want to add the following line to the body:
<input id="fnivel2" pk="1"/>
I did it using a hide class. It works but I'm not sure if it is a correct solution:
<script>
$(document).ready(function (){
$("#fnivel").change(function(){
var selected_option = $('#fnivel').val();
if(selected_option == '2'){
$("#fnivel2").removeClass("hide");
$("#fnivel2").attr('pk','1');
}
if(selected_option != '2'){
$("#fnivel2").addClass("hide");
$("#fnivel2").removeAttr('pk');
}
})
});
</script>
<select id="fnivel">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<input id="fnivel2" class="hide" />
Here is an option, first the HTML:
The JavaScript:
Here's a JsFiddle example.
Another approach, depending on your requirements is to create the input control programmatically, e.g.
You might want to add the input element by using
$("#fnivel").after($('input', {id: 'fnivel2', pk: '1'}));
This is a solution as well:
fiddle:
http://fiddle.jshell.net/prollygeek/4kPk3/
yours is only useful, if you want to keep the input value.