0

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. i.e. 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>  
2
  • 2
    Building a shopping cart is not an easy endeavor. If you can't figure out how to use Javascript to copy a url into an input value then you need to read up and learn some more first. Please. Commented Jun 28, 2012 at 20:29
  • I'm not building a shopping cart I'm trying to integrate Buy now buttons from web pages produced by one application into an existing online shopping cart. Commented Jun 28, 2012 at 21:30

3 Answers 3

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help and code. I'm now off to try and see if I can make this work. Your help is appreciated.
1

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;

1 Comment

As previously thanks for the help and code. I'm now off to try and see if I can make this work. Your help is appreciated.
0

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 -->

... ...

1 Comment

Again thanks for the help and code. I'm now off to try and see if I can make this work. Your help is appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.