Skip to content Skip to sidebar Skip to footer

Giving An Element Multiple Names/id's

I have come across a few posts emphasizing that an ID is only used once. However I need to pass 2 php variables to my javascript. I intended to use the document.getElementById but

Solution 1:

You can use custom html attributes like data-pres-id and data-prod-id

data-pres-id="<?phpecho$selectPresForJs->valueof('pres_id'); ?>"

You can access these variables in javascript by targetting the a element.

var ele = document.getElementById("yourelementID");
var pressID = ele.attributes["data-pres-id"].value;

Solution 2:

Since Leopard's answer, from a technical point of view, isn't completely correct, I'll throw my own two cents in:

On the HTML side, you use custom data attributes like so:

<aclass="image_modal"data-toggle="modal"data-id="prodModal"data-pres-id="<?phpecho$selectPresForJs->valueof('pres_id'); ?>"data-prod-id="<?phpecho$prod->prod_id; ?>"data-target="#prodModal"><imgclass="image-modal"style="width: 192px; height:192px;"src="<?phpecho$prod->prod_icon; ?>"><span><h2style='color:#2468A6'><b><?phpecho$prod->prod_name ?></b></h2></span></a>

Now, using JavaScript, you'd access it like this:

var product = document.getElementById('prodModal');
product.dataset.presId// contains value of 'pres_id'
product.dataset.prodId// contains value of 'prod_id'

Please note the difference here: HTMl specifies custom data attributes by separating words with dashes which get automatically "translated" into camel case variables and properties, e. g. data-foo-id is accessed via dataset.fooId.

For more in-depth information, please see the W3C's specification on dataset.

Additionally, please obey HTML and JavaScript naming guidelines by using fooId instead of fooID.

In case you want to use jQuery, you'd use this:

$('#prodModal').data('presId'); // contains value of 'pres_id'$('#prodModal').data('presId'); // contains value of 'prod_id'

Please have a look that access via data(), too.

Post a Comment for "Giving An Element Multiple Names/id's"