Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

jQuery is not updating the forms action on hitting return

I'm trying to get the action attribute of my form to update on keypress. This is raising 2 issues:

1 - on hitting return, it only includes the first variable and the string needed to push the search, but misses the alterdLink var search query.

2 - the jQuery always misses of the final keystroke (The final keystroke can also be the first if you only type 1 character)

Here is my code:

    $('.search-box').on('keypress', function() {
        searchTerms = $(this).val()
        httpLoc = 'http://www.example.com/search'
        var alteredLink = searchTerms.replace(/\ /g, '+')
        if (alteredLink.trim() != '') {
            var fullLink = httpLoc + 'needed-string-for-search' + alteredLink //Misses this last var on hitting return
            console.log(fullLink)

            $('.search-form').each(function() { //The design forced the need fo several forms on the page...
                $(this).attr('action', fullLink)
            })
        }

    })

It will spit out the full link (minus 1 character in the alterdLink variable) to the console, but when you hit return it simply ignores this. THe code has the same outcoem whetherornot you use keydown, keyup or keypress. Any ideas?

1 Answer

Okay. So, for some reason, the form strips out the final(?) get variable. The first passes with no issue. For this, It appears I may need to hack an anchor element to work like a form.

If you have a better idea, please let me know...

STILL NEED AN ANSWER FOR THE KEYPRESS ISSUE!! :)

Solved: .. okay... Maybe keyup does work :$