0

I am working with a api where i need to post a url from a form and get response. Everything is working well except one thing. I could not figure out how to get url posted in form input in to a variable for javascript. Take a look at following.

 <form action="#" method="post">
 <input type="text" class="url" name="url" />
 <input type="submit" value="Analyse for Page Speed" value="submit" />
 </form>

I use above form to get url and i want that url to be a value for the following variable

 // Specify the URL you want PageSpeed results for here:
 var URL_TO_GET_RESULTS_FOR = 'your url here';

How to get this done?

9
  • You don't need jQuery for this. Your title is misleading. Commented Jul 2, 2013 at 14:19
  • You should give the form an ID so that you can select it with Javascript. Commented Jul 2, 2013 at 14:19
  • You want to set that variable value with the field url value? Or the reverse? And when you want that. In which event? Commented Jul 2, 2013 at 14:19
  • 1
    @crush: I think we can assume he is using it already since he asked for a jQuery solution (in the title). Regardless of where he put it, it's pretty clear what he wants. This is different than someone suggesting to start using jQuery for a trivial problem such as this. Not all newbies are good at choosing all of the appropriate tags for their question. Commented Jul 2, 2013 at 14:24
  • 1
    @crush: I'm pretty convinced that jQuery is already available. If you're not sure about it, perhaps it would be better to simply ask that question. Your comment gives off a vibe of telling him that he's doing something wrong. Commented Jul 2, 2013 at 14:28

2 Answers 2

3

Is this what you're looking for?

var URL_TO_GET_RESULTS_FOR = document.getElementsByName('url')[0].value;

getElementsByName returns an array with all elements having the name passed as parameter. Since I'm assuming you have only one element with name="url", I get the first position of the array and returns the value.

Sign up to request clarification or add additional context in comments.

1 Comment

I believe he wants that too, but he doesn't especified when.
1

As @crush pointed out in the comments, this task alone probably does not merit the use of jQuery. So if you aren't already using it, this should probably not be the deciding factor. If you need a pure JS solution, go with @ClaudioRedi's answer.

However, I'm assuming you're already using jQuery, and are asking for a jQuery solution. So here it is:

var URL_TO_GET_RESULTS_FOR = $('form input[name="url"]').val();

This will get the value of an <input> with the name url within a <form> element.

Comments

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.