skip to Main Content

I want to show the elements from an external html file called h12_load.html into a selection list and if one of them gets clicked it gets shown into the div called divResult.

the first option doesn’t get added to the divResult when it is selected/clicked.

This is what i tried:

HTML & JQuery:

<select name="" id="SelectionList">
    <option value="" id="option1"></option>
    <option value="" id="option2"></option>
</select>
<div id="divResult"></div>
<script>
    $(document).ready(() => {
        let option1 = $('#option1').append().load('h12_load.html #content')
        let option2 = $('#option2').append().load('h12_load.html #meerContent')
        $('#SelectionList').on('change', function () {
            if ($('#option1').is(':selected')) {
                $('#divResult').append(option1)
            } if ($('#option2').is(':selected')) {
                $('#divResult').append(option2)
            }

        }

        )
    })
</script>

External HTML file:

<div id="content">
    <h2>Deze inhoud wordt geladen via $.load()</h2>
</div>
<div id="meerContent">
    <p>Lorem ipsum dolor sit....</p>
</div>

Please help, thanks already!

2

Answers


  1. I don’t get why you define two variables (option1 and option2), I think it would be better this way.

    $('#SelectionList').on('change', function () {
        $('#divResult').empty();
        if ($('#option1').is(':selected')) {
            $('#divResult').load('h12_load.html #content')
        } if ($('#option2').is(':selected')) {
            $('#divResult').load('h12_load.html #meerContent')
        }
    }
    

    The method load itself append to the element, I also added $('#divResult').empty(); to clean the div before adding another element again.

    I didn’t test this but try it out and let us know.

    Login or Signup to reply.
  2. the first option doesn’t get added to the divResult when it is selected/clicked.

    But the second one does? It sounds like you’re just not able to change the option to the first one. After all, the <select> only has two options. One will be selected by default. So selecting that one (the first one) doesn’t change the selection. If you select the second one, that element gets moved to the <div>, which leaves the <select> with one option, which is already selected.

    So you’ve created a <select> where the first option is always already selected and can’t be un/re-selected.

    Add an empty option as the default:

    <select name="" id="SelectionList">
      <option value=""></option>
      <option value="" id="option1"></option>
      <option value="" id="option2"></option>
    </select>
    

    Then you can select either of the other options. And when you do so and that option gets moved to the <div>, the empty option will again be the default.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search