javascriptjqueryhtmlselectjquery-data

Use jQuery. data() with select


I have the code below to change dynamically an image. It work as it should but I have some questions:

1 - Why

$('#image').attr('data-picture-name', $this.val());

work but

$('#image').data('picture-name', $this.val());

don't work ? and is there any way to use data() instead of attr() ?

2 - Retrieve data from the data-parameters value in the selected option

How can I get the value from data-parameters in the selected option ?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="docs-assets/ico/favicon.png">
    <title></title>
</head>
<body>
    <img data-picture-name="popol" src="" id="image" style="width: 1200px; height: 500px; border: 1px solid red;" />
    <select name="meteo-list-cities" id="meteo-list-cities" class="triggered" data-trigger-change-call="meteo-country-change-trigger">
        <option data-parameters="1" value="assets/images/newyork.jpg">New York</option>
        <option data-parameters="2" value="assets/images/paris.jpg">Paris</option>
        <option data-parameters="3" value="assets/images/london.jpg">London</option>
    </select>

    <script src="assets/js/plugins/jquery/jquery.min.js"></script>
    <script>
        jQuery(document).ready(function($) {
            $('#meteo-list-cities').on('change', function () {
                var $this= $(this);
                $('#image').attr('data-picture-name', $this.val());
                $('#image').attr('src', $this.val());
            });
        });
    </script>
</body>
</html>

Solution

  • Yes, you can use data to store extra information. You can get and set that info, which could be a simple string or a complex object using jquery data. Unlike setting the attribute, this data object is hidden from source view.

    SET

    $('#image').data('cityImgPath', $this.val() );
    
    $('#image').data('complexColorObj', { imgPath: "http://i.dailymail.co.uk/i/pix/2012/04/24/article-2134408-12BFD96D000005DC-434_964x788.jpg", color: "blue", mood: "depressed" } );
    

    GET

    var newImagePath = $('#image').data('cityImgPath');
    
    var myMoodBeforeCoffee = $('#image').data('complexColorObj').mood;
    

    Once you have that variable, then you can apply it to your div

    $('#image').attr('src', newImagePath );
    

    api for jquery data