0

I'm currently creating a donation form that allows for custom donations. My donation plugin detects the ?amount= url value and pre-selects it when the user lands on the donation page.

So far this is the html input:

<input type="text" placeholder="7.00" name="singular" id="singular">
<a href="http://example.com/donate/?amount=" id="myLink" class="et_pb_button dnt">Donate</a>

And this is the javascript:

$('#singular').on('input', function() {
  $('#myLink').prop('href', this.value);
});

When I click the actual donate button however, it adds the inputted value to the end of the current pages url, e.g: http://example.com/page1/7 instead of taking you to http://example.com/donate/?amount=7.

I know it must be something stupidly simple. How can I fix this?

Update on Error

When loading the https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js the script suggested works fine.

But when I remove that jquery.min and load the full wordpress core jquery (version: 1.12.4) Chrome Inspect display the following error:

Uncaught TypeError: $ is not a function

Update 2.0

I couldn't find an easy way to solve the error but in my searches I did find a solution that is non javascript dependent if anyone else is interested in doing this:

How to pass input field values as a url query string that will be opened on click of a submit button?

AnnaMar
  • 29
  • 5

1 Answers1

1

The problem with your code is that you're overwriting the href attribute of the link by the value of the input. This makes the href of the anchor relative to current page's URL, and that's why it navigates to the URLs, such as http://example.com/page1/7.

You will need to change the query parameter with the value of the input box.

One way to do this is to use the URL API to change the amount query param instead. See the following snippet.

$('#singular').on('input', function() {
  var href = new URL($('#myLink').prop('href'));
  href.searchParams.set('amount', this.value);
  $('#myLink').prop('href', href.toString())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="7.00" name="singular" id="singular">
<a href="http://example.com/donate/?amount=" id="myLink" class="et_pb_button dnt">Donate</a>
31piy
  • 23,323
  • 6
  • 47
  • 67