user1647234 user1647234 - 2 months ago 9
JSON Question

Script for populating html elements with content from a .json file not working on mobile

On THIS page I have a bunch of "placeholders" for phone numbers in the form: 07xxxxxxxx. Upon clicking the green button "VEZI TELEFON", the placeholder in each green box is replaced with a real phone number from a JSON file, via $.ajax.

The script works well on desktops and laptops, but, on mobile phones the first placeholder is not replaced. The same happens on the details page, where there is only one placeholder.

The json file has the content:

{
"telefoane": [{
"id": 1,
"tel": "0743127315"
}, {
"id": 2,
"tel": "072245875"
}, {
"id": 3,
"tel": "0756129458"
}, {
"id": 4,
"tel": "0756129668"
}, {
"id": 5,
"tel": "0724153333"
}]
}


The JS code:

function showTel() {
$(".telefon").on('click', function(){
var index = $(this).closest(".imobil").index();
var $element = $(this);
$.ajax({
url: 'telefoane.json',
dataType: 'json',
type : 'get',
cache : 'false',
success: function(data){
var tel = data.telefoane[index].tel;
console.log(index + ": " + tel);
$element.parent().find('.telefon .tel').text(tel);
}
});
});
}
showTel();

// Arata telefon
$('.telefon').on('click', function(){
$(this).children('.vezi').hide();
$(this).children('.tel').show();
});


The console strangely shows 2 different things on desktop and mobile. The value of index is different it seams...
Desktop:

0: 0743127315
1: 072245875
3: 0756129668
4: 0724153333
Uncaught TypeError: Cannot read property 'tel' of undefined


Mobile:

1: 072245875
2: 0756129458
4: 0724153333
Uncaught TypeError: Cannot read property 'tel' of undefined


What is wrong with this code? Thank you!

Answer

How about not relying on index(), but id instead?

function showTel() {
    $(".telefon").on('click', function(){
        var index = $(this).closest(".imobil").data("id");
        var $element = $(this);
        $.ajax({
            url: 'telefoane.json',
            dataType: 'json',
            type : 'get',
            cache : 'false',
            success: function(data){
                var tel = data.telefoane[index].tel;
                console.log(index + ": " + tel);
                $element.parent().find('.telefon .tel').text(tel);
            }
        });
    });
}
showTel();