Ben Tinner
Ben Tinner

Reputation: 59

Button onclick having problems redirecting

I am having problems redirecting users to another page using a button

(assume hostname is localhost:8000)

$('#getFruit').attr('onclick', window.location.host + '/getFruit/banana')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="getFruit">Get Fruit</button>

This should redirect me to localhost:8000/getFruit/banana. However, i got this error in the console

Uncaught ReferenceError: banana is not defined at HTMLButtonElement.onclick

It seems that the browser thinks that banana is a variable.

Any fixes for this?

Upvotes: 0

Views: 97

Answers (3)

AnthonyY
AnthonyY

Reputation: 721

You need to pass a function to onclick, e.g.

$('#getFruit').on('click', function() { window.location = '/getFruit/banana'; })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="getFruit">Fruit</button>

Upvotes: 0

jgutierrez
jgutierrez

Reputation: 26

I think you can do it this way:

$('#getFruit').click(function() { location.href = location.host + '/getFruit/banana'})

Upvotes: 0

robere2
robere2

Reputation: 1716

A URL is not a valid value for the onclick attribute. Your current code is actually trying to run the URL as Javascript when a user clicks the button, which won't work.

You should try redirecting the user using Javascript:

$('#getFruit').click(function() {
  window.location = '/getFruit/banana';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="getFruit">Get Fruit</button>

Upvotes: 2

Related Questions