falnyr falnyr - 3 years ago 216
HTML Question

How to access HTML element attribute in jQuery JSON

I am trying to access the specific HTML element attribute and assign it to JSON property.

At first I get the JSON object from file and load it into settings. Then I go through the rows and create text inputs with various attributes.

Since I am using iris plugin, I am firing that right after. You can see that I am using changeElements function, where iris-id is being used (which works).

So the question is... why the color property in iris part is empty?

function startCorr(jsonFile) {
request = new XMLHttpRequest();
request.open('GET', jsonFile, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
settings = JSON.parse(request.responseText);
$.each(settings, function(key, jsonRow) {
$(sidePanel).append(createInput(key, jsonRow));
});
// iris
$('.iris').iris({
color: $(this).attr("iris-color"), // doesn't work
width: 200,
border: false,
hide: false,
change: function(event, ui) {
changeElements($(this).attr("iris-id"), ui);
}
});
} else {
console.log("Error getting JSON file");
}
};
request.send();
}

function createInput(key, jsonRow) {
input = "<label>" + jsonRow.name + "<input type='text' class='iris' id='" + jsonRow.section + "' ";
input += "iris-color='" + getColor(jsonRow.selectors[0]) + "' iris-id='" + key + "'>";
input += "</label>"

return input;
}

function getColor(selectorObject) {
return $(selectorObject.selector).css(selectorObject.style);
}


JSON

[
{
"name": "Global text",
"section": "text-global",
"input": "color",
"selectors": [
{
"selector": ".button.special",
"style": "background-color"
},
{
"selector": ".button.notSoSpecial",
"style": "color"
}
],
"areas": ["homepage", "detail", "category", "basket"]
},
{
"name": "Text on hover",
"section": "text-hover",
"input": "color",
"selectors": [
{
"selector": "#banner p",
"style": "color"
}
],
"areas": ["homepage", "detail", "category", "basket"]
}
]

Answer Source

When you need to access data specific to an element to pass into the options of a plugin one very common approach is to initialize the plugin within a $.each loop. Within the loop this is the current element

$('.iris').each(function() {
  var $el = $(this);
  $el.iris({
    color: $el.attr("iris-color"), 
    width: 200,
    border: false,
    hide: false,
    change: function(event, ui) {
      changeElements($el.attr("iris-id"), ui);
    }
  });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download