How to get the value of an attribute in Javascript

旧街凉风 提交于 2019-12-07 23:12:23

问题


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;
}

回答1:


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="foo" data-something="something" value="bar">

and the javascript.

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

console.log(el.value) // bar
console.log(el.getAttribute("id")) // foo
console.log(el.dataset.something) //something



回答2:


element.getAttribute("value") returns value which was set in the markup, which is not necessarily same as element.value.

Also, value attribute of an element is only synchronized one way - from markup to the object and vice versa doesn't happen.

So, if you want to get the value that is set programmatically, you need to write

element.value

else, if you need to get the value which was defined in the markup as

<input value="abc">

you need to do element.getAttribute("value")




回答3:


OR with jQuery you can get value from textbox like

var val1 = $(".class name").val();//to get value by class name
var val1 = $("#id").val();//to get value by id

Both will do same.

Regards



来源:https://stackoverflow.com/questions/37880165/how-to-get-the-value-of-an-attribute-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!