问题
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" />
回答1:
Here is an option, first the HTML:
<select id="fnivel">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<input id="fnivel2" hidden="hidden" />
The JavaScript:
$("#fnivel").change(function () {
var selected_option = $('#fnivel').val();
if (selected_option === '2') {
$('#fnivel2').attr('pk','1').show();
}
if (selected_option != '2') {
$("#fnivel2").removeAttr('pk').hide();
}
})
Here's a JsFiddle example.
Another approach, depending on your requirements is to create the input control programmatically, e.g.
$('#fnivel2').append('<input id="fnivel2" pk="1"/>').show();
回答2:
This is a solution as well:
$(document).ready(function() {
$("#fnivel").change(function() {
var selected_option = $('#fnivel').val();
if (selected_option == '2' && $("#fnivel2").length == 0) {
$("#fnivel").after("<input id='fnivel2' pk='1'/>")
}
if (selected_option != '2') {
$("#fnivel2").remove()
}
})
});
fiddle:
http://fiddle.jshell.net/prollygeek/4kPk3/
yours is only useful, if you want to keep the input value.
回答3:
You might want to add the input element by using
$("#fnivel").after($('input', {id: 'fnivel2', pk: '1'}));
来源:https://stackoverflow.com/questions/23450695/jquery-hide-show-input-when-selected-option-is-equal-to