Search code examples
javascriptgreasemonkey

alert a variable value


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)

  }
}

Solution

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