how to get the text input value in javascript

i have written this code , i have a text field and when i enter something in text box and click submit.the value of text box should alert message box.
how to do this? pls help me

here is what i have tried

<form name="input" action="#" method="post" 
    <input type="text" name="cost" value=" ">
</form>

javascript:

   var trlist = document.getElementsByName("cost");
   alert(trlist);

How to get values from textbox and print it in alertbox?

23 thoughts on “how to get the text input value in javascript”

  1. You need to close the form tag first

    <form name="input" action="#" method="post" >
        <input type="text" name="cost" value=" ">
    </form>
    

    Use the value property

    var trlist = document.getElementsByName("cost").value;
    alert(trlist);
    
    Reply
  2. Here you can get value of "cost" to variable name "trlist" and i just display it using alert

    var trlist = document.getElementById("cost").value;
    alert(trlist);

    getElementById is keyword to get value

    Reply
  3. var trlist = document.getElementsByName('cost')[0].value;
    alert(trlist);
    

    getElementsByName() returns an HTMLCollection, which doesn’t have a value property. HTMLCollection mimics an Array, so its elements can be accessed using the array notation array[index]

    document.getElementsByName('cost')[0] returns the first element with name attribute set to cost, which in your case is <input type="text" name="cost" value=" ">

    Reply
  4. Is better that you declared id inside the <input type="text" name="cost" value=" ">

    <form name="input" action="#" method="post" 
        <input type="text" name="cost" value=" " id="cost">
    </form>
    

    and after you call with :

    var trlist = document.getElementById("cost").value;
       alert(trlist);
    

    EXample

    In your case when you use getElementbyname return undefined
    JSFIDDLE

    And if you want to use getElementbyname solution on JSFIDDLE

    Reply

Leave a Comment