Skip to content Skip to sidebar Skip to footer

Jquery Select Box (dropdown), Load First Value

I have a dropdown select boy with a few images. I can get the images to load when the user changes value, but I want the View All to load right when the page is viewed.. I know I c

Solution 1:

The change event fires when the select element value changes of course you can fire it yourself if you wanted.

$(document).ready(function() {
   $("#image").change(function() {
     $("#imagePreview").empty();
        $("#imagePreview").append("<img src=\"" + $("#image").val()  + "\" />");
   }).change();
 });

http://jsfiddle.net/28UwU/1/

Solution 2:

@Musa has posted an interesting answer of triggering the .change() event on load, but it might be complicated if you have other functions bound to the .change() event that you wouldn't want to trigger, should you modify or update your code.

My approach would be calling a function instead. The function takes advantage of chaining available in jQuery, as well as construct the <img /> element as an object.

$(document).ready(function() {
    var imgPrev = function(imgSrc) {
        $('#imagePreview')
        .empty()
        .append($('<img />', {
            src: imgSrc,
            alt: ''
        }));
    };

    // Update image preview when <select> is updated
    $('#image').change(function() {
        imgPrev($(this).val());
    });

    // Update image preview on loadimgPrev($('#image').find('option[selected]').val());
});

http://jsfiddle.net/teddyrised/28UwU/5/

Solution 3:

You can try handling the load for your div tag in the document.ready function.

$('#image').load('@Url.Action("GetAllImages","ImageController")');

Post a Comment for "Jquery Select Box (dropdown), Load First Value"