Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of an attribute in Javascript

I have this input line which I am trying to extract the text of the value attribute:

    <input type="text" class="card-input small-font" 
ng-value="paymentVia.typeDisplay" readonly="" value="Credit card">

The function getAttribute("class") works fine and it returns card-input small-font but the function getAttribute("value") returns null. I tried .value as well but this returns an empty string.

Does anyone know why this is happening?

This is my JS:

function() {
   var x = document.getElementsByClassName("card-input small-font");
   var payment =x[18].value;

   return payment;
}
like image 537
Tamara Caligari Avatar asked Jun 17 '16 11:06

Tamara Caligari


People also ask

What is value attribute in JavaScript?

The value attribute specifies the value of an <input> element. The value attribute is used differently for different input types: For "button", "reset", and "submit" - it defines the text on the button. For "text", "password", and "hidden" - it defines the initial (default) value of the input field.

How get data attribute from Element?

Approach: First, select the element which is having data attributes. We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.

Which property returns the value of an attribute?

The value property sets or returns the value of an attribute.

How get data attribute value in jQuery?

You can use this jquery attr() syntax for get data-id attribute value. $("selector"). data("data-textval"); You can use this jquery attr() syntax for get data-textval attribute value.


1 Answers

Node values and Element Attributes are different parts of an html tag. So, you have to use element.value instead.

This is a an example, to show you how you can fetch value, data, attribute from an input field.

The HTML input field.

<input type="text" id="profile" data-nationality="Eritrean" value="Simon">

and the javascript.

var el = document.getElementById("profile"); 

console.log(el.value) // Simon
console.log(el.getAttribute("id")) // profile
console.log(el.dataset.nationality) // Eritrean
like image 153
samayo Avatar answered Sep 21 '22 05:09

samayo