简体   繁体   中英

How do I pass a JS variable into the “value=” parameter of an INPUT statement

The example below should display the value from the JS as the value in the INPUT statement but does not.

<html>
<body>

<script type="text/javascript">
var qty = 1;
if (qty<3)
{
var shipping=1.92;
var shp_method="USPS First Class Package";
}
else if (qty>=3 && qty<14)
{
var shipping=4.85;
var shp_method="USPS Small Flat Rate Package";
}
else
{
var shipping=10.82;
var shp_method="USPS Medium Flat Rate Package";
}
</script>
<input type="text" name="shp_method" value="<?=shp_method;?>" TEXT STYLE="text-align:center" readonly="readonly" size="30">
</body>
</html>

The syntax you are using:

value="<?=shp_method;?>"

is valid only for PHP.

If you want to do with javascript, you can do something like this:

document.getElementById('#textbodID').value = shp_method;

Your code should be like this:

<script type="text/javascript">
window.onload = function(){
    var qty = 1;
    if (qty<3)
    {
    var shipping=1.92;
    var shp_method="USPS First Class Package";
    }
    else if (qty>=3 && qty<14)
    {
    var shipping=4.85;
    var shp_method="USPS Small Flat Rate Package";
    }
    else
    {
    var shipping=10.82;
    var shp_method="USPS Medium Flat Rate Package";
    }

        document.getElementById('#textbodID').value = shp_method;
};
</script>

Where textbodID is assumed to be the id of your input field which can be assigned like this:

<input id="textbodID" />

try like this:

<input type="text" name="ye" id="yea"> //input box 

        <script type="text/javascript">
        var mytime=new Date();
        document.getElementById("yea").value=(mytime.getFullYear());
</script>
<input type="submit" value="Submit" name="submit">// use submit button to get input value

then use scriplet tag in same jsp page:

like this:

<%  String y=request.getParameter("submit"); 
   if(y.equals("Submit"))
   {
    String s=request.getParameter("ye");
    System.out.println(s);
   }
%>

after click submit you can see javascript value in your console. then save this string value in your database and then u can access this String everywhere. please don't copy and paste this example. just try to write in your page to avoid errors.

First of all add an id attribute to the input. this will automatically set the value as soon as the page loads:

window.onload = function (){
var qty = 1;
if (qty<3)
{
var shipping=1.92;
var shp_method="USPS First Class Package";
}
else if (qty>=3 && qty<14)
{
var shipping=4.85;
var shp_method="USPS Small Flat Rate Package";
}
else
{
var shipping=10.82;
var shp_method="USPS Medium Flat Rate Package";
}
document.getElementById('inputId').value = shp_method;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM