Omer
Omer

Reputation: 163

Get element's value

I'm trying to check an element's value but it returns undefined though it works when I'm checking its class.

HTML:

<div class='cube' value='test' onclick='checkCube(this)'></div>

JavaScript:

function checkCube(cube) {      // - there's either one of those lines, not both)
    var check = cube.value;         //This is not working,
    var check = cube.className;     //This is.
    console.log(check);
}

Upvotes: 2

Views: 79

Answers (4)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

It will be better to use data-* attributes when you attach extra properties (not the tag global attributes) to your elements :

<div class='cube' data-value='test' onclick='checkCube(this)'></div>

Then use dataset to retrieve the attribute value like :

var check = cube.dataset.value; 

Upvotes: 2

Manikant Gautam
Manikant Gautam

Reputation: 3581

you can get by using getAttributes.The getAttribute() method returns the value of the attribute with the specified name, of an element.

function checkCube(cube) {     
    var check = cube.value;         
    var check = cube.className;     
    console.log(cube.getAttribute("value"));
}
<div class='cube' value='test' onclick='checkCube(this)'>click Over Me</div>

Upvotes: 0

Nitin Dhomse
Nitin Dhomse

Reputation: 2602

Do as following.

function checkCube(cube) {    
     var check = cube.getAttribute("value"); 
     alert(check);
   }
<div class='cube' value='test' onclick="checkCube(this)">Click me to get Value</div>

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68363

value property is only supported for input elements

Use getAttribute for non-input elements

var check = cube.getAttribute("value"); 

Upvotes: 9

Related Questions