How to get text box value in JavaScript

前端 未结 15 1734
面向向阳花
面向向阳花 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 14:50
    var word = document.getElementById("word").value;//by id
    or
    var word = document.forms[0].elements[0].value;//by index
    //word = a word from form input
    var kodlandi = escape(word);//apply url encoding
    
    alert(escape(word));
    or
    alert(kodlandi);
    

    the problem you are not using encoding for input values from form so not browser adds ones to ...

    ontop has some problems as unicode encoding/decoding operations so use this function encoding strings/arrays

    function urlencode( str ) 
    {
    // http://kevin.vanzonneveld.net3.    
    // +   original by: Philip Peterson4.    
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)5.    
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'7. 
       var ret = str; 
       ret = ret.toString();
       ret = encodeURIComponent(ret);
       ret = ret.replace(/%20/g, '+');
       return ret;
    }
    
    
    ex.
    var word = "some word";
    word = urlencode(word);
    
    0 讨论(0)
  • 2020-12-07 14:53

    +1 Gumbo: ‘id’ is the easiest way to access page elements. IE (pre version 8) will return things with a matching ‘name’ if it can't find anything with the given ID, but this is a bug.

    i am getting only "software".

    id-vs-name won't affect this; I suspect what's happened is that (contrary to the example code) you've forgotten to quote your ‘value’ attribute:

    <input type="text" name="txtJob" value=software engineer>
    
    0 讨论(0)
  • 2020-12-07 15:00
     var jobValue=document.FormName.txtJob.value;
    

    Try that code above.

    jobValue : variable name.
    FormName : Name of the form in html.
    txtJob : Textbox name

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

    Set id for the textbox. ie,

    <input type="text" name="txtJob" value="software engineer" id="txtJob"> 
    

    In javascript

    var jobValue = document.getElementById('txtJob').value
    

    In Jquery

     var jobValue =  $("#txtJob").val();
    
    0 讨论(0)
  • 2020-12-07 15:01

    This should be simple using jquery:

    HTML:

      <input type="text" name="txtJob" value="software engineer">
    

    JS:

      var jobValue = $('#txtJob').val(); //Get the text field value
      $('#txtJob').val(jobValue);        //Set the text field value
    
    0 讨论(0)
  • 2020-12-07 15:05

    because you used space between software engineer html/php will not support space between value under textbox, you have to use this code <input type="text" name="txtJob" value=software_engineer> It will work

    0 讨论(0)
提交回复
热议问题