Ad

Append Field Without Data By Ajax

- 1 answer

Is that possible to append data in view without sending any data to back-end?

I have static select-box with static values (nothing from database), i want when i selected specific option show some more fields and for other options hide those fields. Is that possible?

Code

<select name="style" id="style" class="chosen-select">
    <option value="">-- Select --</option>
    <option value="default">Default</option>
    <option value="about-one">About Style 1</option>
    <option value="about-two">About Style 2</option>
    <option value="contact-one">Contact page without form</option>
    <option value="contact-two">Contact page with form</option>
    <option value="faq">Faq</option>
    <option value="services">Services</option>
</select>

//new fields here
<div class="col-md-12 mt-10" id="details"></div>

JavaScript

<script>
    $(document).ready(function() {
        $('select[name="style"]').on('change', function() {
            $('div#details').empty();
            var Style = 'contact-two' //when this value is selected return below
            if(Style) {
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    success:function() {
                        $('div#details').empty();
                        $('div#details').append('<p>Here will be appended inputs</p>');
                    }
                });
            } else {
                $('div#details').empty();
            }
        });
    });
</script>

PS: Not sure I need Ajax at all?! Please share your ideas with me.

Ad

Answer

I cant see the use in Ajax, perhaps you have a reason, but unless you need data from the server try this.

var Style = 'contact-two' does nothing in the if statement, the if is just checking that it is not null. Compare the string to the value of the select with this.value

$(document).ready(function() {
  $('select[name="style"]').on('change', function(f) {
    $('#details').empty();
    if (this.style == 'contact-two'){
      $('#details').empty();
      $('#details').append('<p>Here will be appended inputs</p>');
    } else {
      $('div#details').empty();
    }
  });
});
Ad
source: stackoverflow.com
Ad