Epleroma
Epleroma

Reputation: 153

Use Jquery to append a field input value to the url as a query string

I believe I have most of this right, but may be messing up the order, and can't get a fiddle to save for some reason. Basically I need to grab part of a form Input and append it as a query string on submit so as to trigger the affiliate cookie on the next page. All codes would start with a AAA-11 value and then the actual affiliate reference code. So

<form>
    <label>Affiliate Code</label>   
    <input type="text" id="code">
    <input type="submit" id="submit_btn">        
</form>

And the JS:

$('#submit_btn').on('click', function() {
    var str = $('#code').val();
    var acode = str.substr(6);
    location.href = location.href + "?ref=" + acode;
});

What am I missing here?

Upvotes: 1

Views: 3822

Answers (1)

Artur Filipiak
Artur Filipiak

Reputation: 9157

Your button is submitting the form because of its attribute type="submit"

You can change the attribute to type="button", or programmatically prevent form submission using event.preventDefault(), so that you can modify the data.

$('#submit_btn').on('click', function(event) {
    event.preventDefault();
    var str = $('#code').val();
    var acode = str.substr(6);
    location.href = location.href + "?ref=" + acode;
});

[EDIT] (comment)

If you need to modify the form action and submit the form aswell, use this:

$('#submit_btn').on('click', function(event) {
    event.preventDefault();
    var str = $('#code').val();
    var acode = str.substr(6);
    // change form action attribute and submit the form:
    $(this).closest('form').attr('action', location.href + "?ref=" + acode).submit();
});

Upvotes: 1

Related Questions