Daniel352 Daniel352 - 11 days ago 5
Javascript Question

javascript json jquery cant get custom attribute value

I cant figure out where am I wrong I've been trying so many possibilities and answers found on SO but it just doesn't give me the value of the custom attribute "attr-pid"

<div class="prod-col et_pb_column et_pb_column_4_4" style="">

<div attr-pid="2" class="bbb_prov product_select et_pb_column et_pb_column_2_4 model_container">
<div class="icon" attr-pid="2"><img src=" " style=" max-width: 100px;"</div></div>

<div attr-pid="4" class="bbb_prov product_select et_pb_column et_pb_column_2_4 model_container">
<div class="icon" attr-pid="4"><img src=" " style=" max-width: 100px;"></div></div>

</div>


I have this

aProvider = $(".bbb_prov");

if ( me.savedJSON.providersToVisit == undefined )
{
me.savedJSON.providersToVisit = [];
}

for( var y = 0 ; y < aProvider.length ; y++ )
{
me.savedJSON.providersToVisit.push("&bxb_provider_id="+$(aProvider[y]).attr('attr-pid'));
}

CEF_SaveDataJSON( me.savedJSON );

console.log(JSON.stringify(me.savedJSON, null, 2));


This works on my other div where i have only one class but here where its multiple, console.log just shows me:

"providersToVisit": []

Answer

The code works as provided (see this fiddle: https://jsfiddle.net/ta3sgh8e/)

HTML

<div class="prod-col et_pb_column et_pb_column_4_4" style="">
<div attr-pid="2" class="bbb_prov product_select et_pb_column et_pb_column_2_4 model_container">
<div class="icon" attr-pid="2"><img src=" " style=" max-width: 100px;"></div></div>
<div attr-pid="4" class="bbb_prov product_select et_pb_column et_pb_column_2_4 model_container">
<div class="icon" attr-pid="4"><img src=" " style=" max-width: 100px;"></div></div>
</div>

JS

function CEF_SaveDataJSON(data){
  //What happens in this function?
    //data.providersToVisit = [];
}
me = {savedJSON:{}};
aProvider = $(".bbb_prov");
if ( me.savedJSON.providersToVisit == undefined ) 
{
    me.savedJSON.providersToVisit = [];
}
for( var y = 0 ; y < aProvider.length ; y++ ) 
{
  me.savedJSON.providersToVisit.push("&bxb_provider_id="+$(aProvider[y]).attr('attr-pid'));   
}
CEF_SaveDataJSON(me.savedJSON);
console.log(JSON.stringify(me.savedJSON, null, 2));

My suspicion is that data is modified inside the CEF_SaveDataJSON function prior to your console log, unless there are other shenanigans we can't see which you've excluded from your example.

Comments