0

In first hover i am getting data id from thumbs and adding to #main image it is working fine and with 2nd hover on #main i am getting the data id again here from the first data id. but it is only getting the 1 data id not another ids when i am changing it on first hover.

<div class="gry">
    <img id="main" src="images/1.jpg" alt="alt" data-id="1" />
    <img id="sm001" src="images/1.jpg" alt="alt" data-id="1" />
    <img id="sm002" src="images/2.jpg" alt="alt" data-id="2" />
    <img id="sm003" src="images/3.jpg" alt="alt" data-id="3" />
    <img id="sm004" src="images/4.jpg" alt="alt" data-id="4" />
</div>
$('img[id^=sm00]').hover(function() {
  $('#main').attr({src:$(this).data('img'), alt:$(this).attr('alt'), "data-id":$(this).attr('data-id')});
});

$('#main').hover(function() {
    var form_data = new FormData();
    form_data.append('action', 'view-img');
    form_data.append('id', $(this).data('id'));
    alert($(this).data('id'));
    $.ajax({
        url: 'load.php',
        dataType: 'json',
        processData: false,
        contentType: false,
        data: form_data,
        type: 'post',
        success: function (response) {
            var code = response.code;
            $( ".gry" ).append( "<img id='vimg' />" );
            $('#vimg').attr('src', code);
        }
    });
},function () {
    $("#vimg").remove();
});
6
  • $(..).attr("data-id", val) won't be returned when you do $(..).data("id") - jquery keeps .data cached, it doesn't read the data-id attribute each time. Read and set data via matching $(..).data("id", newvalue) / $(..).data("id") Commented Aug 29, 2020 at 14:18
  • show your html structure as well Commented Aug 29, 2020 at 14:18
  • 1
    Does this answer your question? Unable to set data attribute using jQuery Data() API Commented Aug 29, 2020 at 14:19
  • thank you all for your help, can you edit full code or can explain? freedomn-m Commented Aug 29, 2020 at 14:32
  • do console.log(response.code) and see what it has ? Also try to change <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> to <script src="https://code.jquery.com/jquery-3.5.1.min.js" ></script> Commented Aug 29, 2020 at 14:46

1 Answer 1

0

I just fixed the issue i just take the data id in input value it working fine now :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.