Zhi V Zhi V - 8 days ago 6
HTML Question

How to get data from button attributes?

There are several buttons (they creates dynamically)

<button class="common" id="1.1" status="sale" oncontextmenu="rightButton('1.1'); return false" onclick="addOptions('1.1')" number="1">1</button>


I need to get attributes (class, id, status, number) and insert them into object array. Then input to database.

function saveScheme()
{
var table = document.getElementById('schemeTable');
var elements = table.getElementsByTagName('button');
var arrayIdButtons = {};
for(var i = 0; i<elements.length; i++)
{
arrayIdButtons[i] = {};
for(var j = 0; j<4; j++)
{
arrayIdButtons[i]["coord"] = elements.item([i]).id;
arrayIdButtons[i]["status"] = elements.item([i]).status;
arrayIdButtons[i]["type"] = elements.item([i]).class;
arrayIdButtons[i]["number"] = elements.item([i]).number;
}
}
console.log(arrayIdButtons);
var data='data=' + JSON.stringify(arrayIdButtons,"", 2);
$.ajax({
type: 'POST',
url: "handler.php",
data: data,
cache: false,
data: data,
success: function(data) {
alert(data)
}
});
}


result of this code(
console.log(arrayIdButtons);
):

enter image description here

Answer

Since you're already using jQuery, you can access the attributes of an element using .attr(). For example:

$('.common').attr('number');

Or, without jQuery,

elements[i].getAttribute('number');
Comments