How to get text box value in JavaScript

前端 未结 15 1736
面向向阳花
面向向阳花 2020-12-07 14:43

I am trying to use JavaScript to get the value from an HTML text box but value is not coming after white space

For example:



        
相关标签:
15条回答
  • 2020-12-07 15:07

    Your element does not have an ID but just a name. So you could either use getElementsByName() method to get a list of all elements with this name:

    var jobValue = document.getElementsByName('txtJob')[0].value  // first element in DOM  (index 0) with name="txtJob"
    

    Or you assign an ID to the element:

    <input type="text" name="txtJob" id="txtJob" value="software engineer">
    
    0 讨论(0)
  • 2020-12-07 15:07

    You Need to change your code as below:-

    <html>
    <body>
    <div>
    <form align="center" method=post>
        <input id="mainText" type="text" align="center"placeholder="Search">
    
        <input type="submit" onclick="myFunction()" style="position: absolute; left: 450px"/>
    </form>
    </div>
    <script>
    function myFunction(){
        $a= document.getElementById("mainText").value;
        alert($a);
            }
    </script>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-07 15:08
    <!DOCTYPE html>
    <html>
    <body>
    <label>Enter your Name here: </label><br>
    <input type= text id="namehere" onchange="displayname()"><br>
    
    
    <script>
    function displayname() {
        document.getElementById("demo").innerHTML = 
    document.getElementById("namehere").value;
    }
    
    </script>
    
    
    <p id="demo"></p>
    
    </body>
    </html> 
    
    0 讨论(0)
  • 2020-12-07 15:09

    If it is in a form then it would be:

    <form name="jojo">
    <input name="jobtitle">
    </form>
    

    Then you would say in javascript:

    var val= document.jojo.jobtitle.value
    
    document.formname.elementname
    
    0 讨论(0)
  • 2020-12-07 15:09



    The problem is that you made a Tiny mistake!

    This is the JS code I use:

    var jobName = document.getElementById("txtJob").value;
    

    You should not use name="". instead use id="".

    0 讨论(0)
  • 2020-12-07 15:10

    Provided when you want the text box value. Simple one:

    <input type="text" value="software engineer" id="textbox">
    
    var result = document.getElementById("textbox").value;
    
    0 讨论(0)
提交回复
热议问题