简体   繁体   中英

How to pass a variable from JavaScript to HTML?

I have a JavaScript defined in my file as follows:

<script language="javascript">
    var transports = "<%=api.transports%>";
    var httpsTransport;
    var httpTransport;
    var splittedTransports= transports.split(',');
    for(i = 0; i < splittedTransports.length; i++)
    {
        if(splittedTransports[i]=="https") {
            httpsTransport="https";
        } else if (splittedTransports[i]=="http") {
            httpTransport="http";
        }
    }
</script>

And I would like to read it in my HTML page like:

<div class="checkbox">
    <label class="checkbox inline">
        <input type="checkbox"  id="transport_http" name="transport_http"  value="http" <%if(httpTransport=="http"){%>checked<%}%> />
    </label>
    <label class="checkbox inline">
        <input type="checkbox" id="transport_https" name="transport_https"  value="https" <%if(httpsTransport=="https"){%>checked<%}%>/>
    </label>
</div>

But now I get an error that states:

org.mozilla.javascript.EcmaError: ReferenceError: "httpTransport" is not defined.

What am I doing wrong here?

I want to allow user to select an checkbox and save the form, and when he tries to edit the form, I want to show what he has saved in his previous operation. So, when he tries to edit I try to read the values form backend and would like to show that particular option as checked.

<script language="javascript">
var transports = "<%=api.transports%>";
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https"){
   document.getElementById("transport_https").checked = true;
}else if (splittedTransports[i]=="http"){
   document.getElementById("transport_http").checked = true;
}
}

</script>

HTML :

<div class="checkbox">
       <label  class="checkbox inline " >
           <input type="checkbox"  id="transport_http" name="transport_http"  value="http" />
       </label>
       <label  class="checkbox inline" >
           <input type="checkbox" id="transport_https" name="transport_https"  value="https"/>
       </label>
</div>

The variables in your code are declared , but not defined . Give them a random value first, and then update it with the if

<script language="javascript">
 var transports = "<%=api.transports%>";
    var httpsTransport = 'no';
    var httpTransport = 'no';
    var splittedTransports= transports.split(',');
    for(i = 0; i < splittedTransports.length; i++)
    {
    if(splittedTransports[i]=="https"){
        httpsTransport="https";
    }else if (splittedTransports[i]=="http"){
        httpTransport="http";
    }
    }

</script>

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