3

I'm trying to push number attribute of the element to the array onclick with a simple function, but array contains only empty values separated with commas. Here's html code.

<button type="button" class="btn btn-success btn-lg" number="12" onclick="basket.push(this.number)">toBakset</button>

<button type="button" class="btn btn-success btn-lg" number="15" onclick="basket.push(this.number)">toBakset</button>

<button type="button" class="btn btn-success btn-lg" number="18" onclick="basket.push(this.number)">toBakset</button>

from the start "basket" array is empty. Seems this question is so dumb but I can't find a solution :(

1
  • Be aware that using standard Javascript without libraries, IE8 (and 9, I think) can't access custom attributes. I use jQuery for custom attributes. This is in addition to changing the name of it to "data-numbers" and using one of the methods below to access the data. Or just onclick="basket.push(12)" Commented Oct 30, 2013 at 21:59

3 Answers 3

5

number isn't a valid attribute for the button element. In order to retrieve it you would have to use a different function from the API

onclick="basket.push(this.getAttribute('number'))"

Better yet, store your number attribute inside of the data- markup like this:

<button data-number="5" ...

So that it conforms to standards. Then you would use

onclick="basket.push(this.getAttribute('data-number'))"

to retrieve it.

Sign up to request clarification or add additional context in comments.

Comments

0

it's because number isn't a standard attribute, so this.number isn't anything. you have to do it another way, such as give an id to each button and keep an array containing which ids have which numbers

Comments

0
  • button type="button" ?
  • number attribute ?

Use data-* attributes!

LIVE DEMO

<button onclick="basketPush(this)" data-number="12" class="btn btn-success btn-lg">toBakset</button>

var basket = [];

function basketPush( that ){
  basket.push( that.dataset.number );
}

DOCS: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#data-*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.