سؤال

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:

<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(); 

نصائح أخرى

Here is a way more clean solution for doing this:

   $("#fnivel").change(function () {
      if ($(this).val() == '2') {
        $('#fnivel2').attr('pk','1').show();
      } else {
        $("#fnivel2").removeAttr('pk').hide();
      }
    })

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.

You might want to add the input element by using $("#fnivel").after($('input', {id: 'fnivel2', pk: '1'}));

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top