0

So I'm kind of a Javascript newbie and having trouble figuring out how to pass a variable from my HTML template to Javascript.

I want to pass the search query that a user enters to javascript.

Here's my template to get the search query.

<form class="well-whatsnext form-search" style="text-align:center; border-radius:10px 10px 10px 10px; width:900px; height:0px;background-repeat:no-repeat;margin-bottom:100px;"  action="/search/?q="> 
<center>
 <input type="text" id = "form-search" value="Search for Stuff" class="input-xxlarge search-query" style="margin: 30px 0px 0px 70px; height:50px;width:600px;font-size:20px;vertical-align:middle;text-align:center;border-radius:10px 0px 0px 10px;float:left;border-right:0px;color:grey;border-right:0px;" name="q">
</center>
<br>
</form>

Here's my Javascript snippet:

$("#form-search").click(function() {
    // This sends us an event every time a user clicks the button
    mixpanel.track('MainSearch', {'query' : search-query, 'url' : window.location.pathname});
});

It is clear that search-query is not the correct way to refer to the query since I'm not getting the correct output I want.

How do I capture the variable of the query searched for by the user?

2 Answers 2

2

Use plain JavaScript wherever possible.

{'query': document.getElementById('form-search').value}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks -- what's the difference between this method and the one above?
The one above is about 100 times slower and relies on you only using the "search-query" class once on the entire page. IDs are by definition unique.
I don't know if 100 times slower is a fair assessment, more like 85% (jsperf.com/jquery-selector-value)
@vol7ron The above answer uses a class name search though, which is slower still.
2

Use $('.search-query').val() to get the value of the input element with that class name:

{ 'query' : $('.search-query').val() ... }

3 Comments

Thanks so much! So is that basically the format for inserting an input in Javascript -- $('.<class_name>).val() -- sorry I'm new to Javascript and just using it for MixPanel mainly, hence why I'm hacking my understanding of it....
@user1328021 This is JavaScript, though not purely JavaScript. And yes, you need $('.class-name') but note that the . in the beginning means the name that comes after it is a class name. For elements with id attributes, you need #. For example: $('#id-name)`.
@David Every time jQuery is used as a selector engine, God kills a lolcat.

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.