简体   繁体   中英

Pass variable to HTML form Javascript

Please excuse my inexperience as I am not a programmer just someone who dabbles at trying to make something work. I'm not sure of the correct terminology and complicated explanations will go straight over my head!

In essence I am trying to get part of the URL of a web page passed to a simple Form that is linked to a shopping cart. ie how do I get the filename into the form where I have xxxxxxx. Is it possible in Javascript?

<script type="text/javascript">
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
document.write (filename);

</script>
<form action="http://www.mywebspace.com/cf/add.cfm" method="post">
<input type="hidden" name="userid" value="12345678">
<input type="hidden" name="product" value="xxxxxxx">
<input type="hidden" name="price" value="5.00">
<input type="Submit" value="Buy now!">
</form>  

I've provided a snippet code that will work with your current HTML structure. Though I do suggest you give the product field an id to prevent the necessity to loop and search elements:

var url = window.location.pathname,
    filename = url.substring(url.lastIndexOf('/')+1);
    fields = document.getElementsByTagName('input');

for(var i = 0; i < fields.length; i++){
    if(fields[i].name == 'product') {
        fields[i].value = filename;
        break;
    }
}

If the form only exists once on a given page, this is an easy solution:

Change it to be:

<input type="hidden" id="productField" name="product" value="xxxxxxx">

In your javascript,

document.getElementById('productField').value = filename;

Yes this is possible.

Instead of doing document.write you need to update the form. Assuming your filename value is currently correct:

 //js
 document.getElementById( "name-of-file").value = filename;

 <!- html -->

... ...

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