Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change a Div content when selecting a value from a select with a jQuery?

Hi I’m new to jQuery and I’m trying to solve this:

When selecting a value from the dropdown (<select>), you need to change the content of the div tag (in red) with the selected value. Please use jQuery to solve this test, and please don’t add any id/class to the above HTML code!

I already wrote a script but it does not work, can you help please

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var content = $( "div:gt(5)" );
$( "select" ).on( "click", function( event ) {
  content.html('6 products');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toolbar-wrapper">
              <div>
                <div>
                  <label>Product Count</label>
                  <div class="select-group">
                    <select>
                      <option value="4 products" selected="selected">4 products</option>
                      <option value="6 products">6 products</option>
                      <option value="8 products">8 products</option>
                    </select>
                  </div>
                </div>

                <div>4 products</div>
              </div>
            </div>

>Solution :

Use this.value in the event handler to get the value that was selected in the dropdown.

When you select something from the dropdown, the change event is triggered, not click.

div:gt(5) is not the correct selector for the div where the result should be displayed. Numbering starts from 0, so it’s DIV number 4. You can use .eq(4) to select that.

var content = $("div").eq(4);
$("select").on("change", function(event) {
  content.html(this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toolbar-wrapper">
  <div>
    <div>
      <label>Product Count</label>
      <div class="select-group">
        <select>
          <option value="4 products" selected="selected">4 products</option>
          <option value="6 products">6 products</option>
          <option value="8 products">8 products</option>
        </select>
      </div>
    </div>

    <div>4 products</div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading