-2

I have an HTML input textbox, and I'm trying to pass the value of it to a JavaScript function. The code for the textbox is as follows;

<input type="text" id="fname">
<input type="button" onclick="success()">

I use this to get the value of the textbox;

var depttxt = document.getElementsByID('fname');

However when I try to find the value of the value like so;

function success() {
    alert(depttxt);
}

The alert box says undefined. If then put .value after the variable in the alert, it breaks and no alert box shows up. Can anyone tell me what I'm doing wrong here?

Thanks all!

1
  • 5
    learn to use your browser console to look at errors
    – charlietfl
    Nov 9, 2015 at 16:11

3 Answers 3

6

Remove s and D => d. The function name is getElementById:

var depttxt = document.getElementById('fname');
2
var depttxt = document.getElementById('fname');

Without the s.

2
  • 1
    Ah, well spotted. It's also a lower case d at the end. Nov 9, 2015 at 16:10
  • getElementByID is wrong...
    – Legionar
    Nov 9, 2015 at 16:18
1

Moan #1: Don't use inline JS :)

Do like this:

HTML:

<input type="text" id="fname" />
<input type="button" id="buttonId" />

JS:

$(document).ready(function() {
    var btn = $('#buttonId');
    $(btn).on('click', function() {
        alert('hello world');
    });
});

this would be a better way of doing jQuery functions on your site :)

5
  • Upvote for promoting good practice. Double upvote if you show the vanilla method and update jQuery to do the proper value alert Nov 9, 2015 at 16:15
  • 2
    An user which is having dificulty to use getElementById() would understand what you have posted ? Don't overkill the problem. At least explain what you have proposed. Nov 9, 2015 at 16:15
  • @DontVoteMeDown technically the post was tagged jQuery, so this is valid answer if a little more explanation is added. Not worthy of a downvote IMO. Nov 9, 2015 at 16:16
  • @SterlingArcher sure but the original code doesn't approach load events and stuff, user may not know what is it. Nov 9, 2015 at 16:18
  • I know, but I'm just happy they are promoting anti-inline-js practices, so I gave points for that alone lol. Nov 9, 2015 at 16:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.