简体   繁体   中英

Javascript and HTML - Variable Doesn't Show Up

I have the following code snippet in HTML:

 <form class="navbar-search pull-right search-query" value = "" action="/search/?q=" style="line-height:25px;">
    <input type="text" id="navbarsearch" class="search-query span2" style="border-radius:14px 14px 14px 14px;" name = "q" placeholder="Search">
      <i class="icon-search icon-white" onclick="document.forms.search.submit();"></i>
         &nbsp;&nbsp;&nbsp;
 </form>

I'm trying to pass this variable to Javascript as follows, but the query variable is not being passed properly for some reason I don't think....

<script type="text/javascript">
    $("#navbarsearch").click(function() {
        // This sends us an event every time a user clicks the button
        mixpanel.track('SearchQuery', {'query': document.getElementById('navbarsearch').value, 'url' : window.location.pathname});
    });
</script>

The action is showing up in MixPanel, but the query variable is not. Am I doing something wrong?

You need to put it inside the document.ready:

$(function() {   //  <--- there.
    $("#navbarsearch").click(function() {
    mixpanel.track(
        'SearchQuery',
        {
            'query': $(this).val(),   
            'url' : window.location.pathname
        }
    );
});
});

The click event is set off when a user clicks with their mouse. I think you want to listen to keystrokes?

Try:

$("#navbarsearch").keydown(function() {
    mixpanel.track('SearchQuery', {
         'query': document.getElementById('navbarsearch').value,
         'url' : window.location.pathname
    });
});

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