39

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)

  }
}
5
  • 4
    show us what u did,including html. Jun 6, 2010 at 6:06
  • 1
    Your question is missing a lot of details. Jun 6, 2010 at 6:13
  • 1
    Off-topic, but I think it would probably help you to pick up a good book on Javascript. I thought Flanagan's Javascript: The Definitive Guide was quite good, but really, you have a lot of choices in terms of JS books at this point. :-) Jun 6, 2010 at 6:40
  • 1
    @T.J. Agree, at least a good guide like Eloquent JavaScript will help him a lot... +1 Jun 6, 2010 at 6:44
  • 5
    Why the down votes? It seems like a good question...
    – Russell
    Jun 6, 2010 at 6:49

7 Answers 7

26

Note, while the above answers are correct, if you want, you can do something like:

alert("The variable named x1 has value:  " + x1);
20

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);
    }
}
5
  • 1
    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. Jun 6, 2010 at 6:28
  • 2
    @Delan: That's what I said, and that's what my example rewrite does. Jun 6, 2010 at 6:33
  • 1
    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
    – technocrat
    Jun 6, 2010 at 6:34
  • 1
    @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.) Jun 6, 2010 at 6:37
  • 1
    T. J. Crowder, really sorry, I must be an idiot; I read the "can" as "can't". Whoops! Jun 6, 2010 at 8:49
4

show alert box with use variable with message

<script>
$(document).ready(function() {
var total = 30 ;
alert("your total is :"+ total +"rs");
});
</script>
3

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

See with the help of the following example if you can use literals and '$' sign in your case.

    function doHomework(subject) {
    
      alert(\`Starting my ${subject} homework.\`);
    
    }

doHomework('maths');
2
var input_val=document.getElementById('my_variable');for (i=0; i<input_val.length; i++) {
xx = input_val[i];``
if (xx.name == "ans") {   
    new = xx.value;
    alert(new);    }}
2

If I'm understanding your question and code correctly, then I want to first mention three things before sharing my code/version of a solution. First, for both name and value you probably shouldn't be using the getAttribute() method because they are, themselves, properties of (the variable named) inputs (at a given index of i). Secondly, the variable that you are trying to alert is one of a select handful of terms in JavaScript that are designated as 'reserved keywords' or simply "reserved words". As you can see in/on this list (on the link), new is clearly a reserved word in JS and should never be used as a variable name. For more information, simply google 'reserved words in JavaScript'. Third and finally, in your alert statement itself, you neglected to include a semicolon. That and that alone can sometimes be enough for your code not to run as expected. [Aside: I'm not saying this as advice but more as observation: JavaScript will almost always forgive and allow having too many and/or unnecessary semicolons, but generally JavaScript is also equally if not moreso merciless if/when missing (any of the) necessary, required semicolons. Therefore, best practice is, of course, to add the semicolons only at all of the required points and exclude them in all other circumstances. But practically speaking, if in doubt, it probably will not hurt things by adding/including an extra one but will hurt by ignoring a mandatory one. General rules are all declarations and assignments end with a semicolon (such as variable assignments, alerts, console.log statements, etc.) but most/all expressions do not (such as for loops, while loops, function expressions Just Saying.] But I digress..

    function whenWindowIsReady() {
        var inputs = document.getElementsByTagName('input');
        var lengthOfInputs = inputs.length; // this is for optimization
        for (var i = 0; i < lengthOfInputs; i++) {
            if (inputs[i].name === "ans") {   
                var ansIsName = inputs[i].value;
                alert(ansIsName);
            }
        }
    }

    window.onReady = whenWindowIsReady();

PS: You used a double assignment operator in your conditional statement, and in this case it doesn't matter since you are comparing Strings, but generally I believe the triple assignment operator is the way to go and is more accurate as that would check if the values are EQUIVALENT WITHOUT TYPE CONVERSION, which can be very important for other instances of comparisons, so it's important to point out. For example, 1=="1" and 0==false are both true (when usually you'd want those to return false since the value on the left was not the same as the value on the right, without type conversion) but 1==="1" and 0===false are both false as you'd expect because the triple operator doesn't rely on type conversion when making comparisons. Keep that in mind for the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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