views:

98

answers:

2

How do I display the value of a variable in javascript in an alert box?

For example I've got a variable x=100 and alert(x) isn't working.

the script used in grease monkey is here

var inputs = document.getElementsByTagName('input');

var new;
for (i=0; i<inputs.length; i++) {
  if (inputs[i].getAttribute("name") == "ans") {   
new=inputs[i].getAttribute("value"));

alert(new)

  }
}
+3  A: 

A couple of things:

  1. You can't use new as a variable name, it's a reserved word.
  2. On input elements, you can just use the value property directly, you don't have to go through getAttribute. The attribute is "reflected" as a property.
  3. Same for name.

So:

var inputs, input, newValue, i;

inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
    input = inputs[i];
    if (input.name == "ans") {   
        newValue = input.value;
        alert(newValue);
    }
}
T.J. Crowder
The first point you made is correct. However, you do *not* need to use `getAttribute` to grab values. `input.value` and `input.name` work just fine.
Delan Azabani
@Delan: That's what I said, and that's what my example rewrite does.
T.J. Crowder
thanks. The problem was with new keyword. If there are four radio buttons and one of those is the value returned in "myvalue" variable how do i check that particular value
muqtar
@muqtar: I'm not entirely sure I understand that question, but it's a separate question, so you should probably ask it separately. StackOverflow differs from discussion sites in that the idea is to have a well-isolated question and (hopefully!) correct answer to it. (If this sorted out *this* question, you can tick the checkmark next to the beginning of the answer to accept the answer.)
T.J. Crowder
ok thaks.I will do it.
muqtar
T. J. Crowder, really sorry, I must be an idiot; I read the "can" as "can't". Whoops!
Delan Azabani
@Delan: LOL! No worries, we've all done it. :-)
T.J. Crowder
A: 

If you're using greasemonkey, it's possible the page isn't ready for the javascript yet. You may need to use window.onReady.

var inputs;

function doThisWhenReady() {
    inputs = document.getElementsByTagName('input');

    //Other code here...
}

window.onReady = doThisWhenReady;
Coronus