CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   How to obtain the value in a button? (http://www.codingforums.com/showthread.php?t=272324)

clathrun 09-05-2012 07:52 PM

How to obtain the value in a button?
 
I am new in JS, and meet a problem, asking for some suggestions, really appreciated.

The question is I don't know how to obtain the value in a button by an independent method, the codes are below:

I:
Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
  <input type="button" id="btn1" value="A" onclick="alert(btn1.value);"/>
</body>
</html>

By using this code, I could get the value which is "A"


II:
Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function showID() {
            alert(this.id);
        }
    </script>
</head>
<body>
  <input type="button" id="btn1" value="A"  onclick="showID()"/>
</body>
</html>


III:
Code:

<head>
    <title></title>
    <script type="text/javascript">
        function showIDByTagName() {
            var btn = document.getElementsByTagName("input");
            alert(btn.id);
        }
    </script>
</head>
<body>
  <input type="button" id="btn1" value="A" onclick="showIDByTagName()"/>
</body>
</html>

However, by II and III, it alerts the value of the button is "undefined", really confused:confused:, looking for some help, thank you very much

devnull69 09-05-2012 08:01 PM

1. Why are you trying to use .id if you want to access the value? Why not use .value?
2. In II: You assigned an event handler using one of the onxxxxx attributes. In that case the context for the function does not change to be a reference to the DOM object, so "this" will be a reference to the window object instead.
3. In III: getElementsByTagName (mind the 's') will return a collection of DOM objects which is essentially an array. In order to retrieve the first object from the array, you will have to use the index [0] on it
Code:

<input type="button" id="btn1" value="A" onclick="showValue(this)"/>


function showValue(obj) {
  alert(obj.value);
}


VIPStephan 09-05-2012 08:03 PM

Code sample #1 has alert(btn1.value); and code samples #2 and 3 have alert(this.id); and alert(btn.id);, respectively. Notice any difference?


All times are GMT +1. The time now is 09:38 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.