dabadaba
dabadaba

Reputation: 9522

Uncaught ReferenceError with: var not defined

I have a table with cities that you can upvote and downvote. Depending on which button you click a hidden input takes this or that value, and I manage that via javascript. But it seems like there is something wrong with the function call.

Here's the HTML:

<td><span class="icon icon-thumbs-down cursor" onclick="downvote(Hamburgo, 24)"></span></td>

And here the dummy functions:

function upvote(ciudad, user_id)
{
    document.write("aa"); // this doesn't even work
    //$("#voto-positivo").attr("value", ciudad);
    //$("#usuario").attr("value", user_id);
    //$('#form-votar').submit();
}

function downvote(ciudad, user_id)
{
    $("#voto-negtivo").attr("value", ciudad);
    $("#usuario").attr("value", user_id);
    $('#form-votar').submit();
}

The first value of the function is taken within a php loop and the second one is the id of the user, all ok.

With Google Chrome I get the following error:

Uncaught ReferenceError: Hamburgo is not defined votar:59

onclick

In case it needs to be said, yes, the javascript source is loaded.

Upvotes: 0

Views: 525

Answers (1)

PSL
PSL

Reputation: 123739

You need to wrap Hamburgo in quotes otherwise it is looking for a variable with that name in the global scope which you don't have and you get this error.

onclick="downvote('Hamburgo', 24)"

and just use val

function downvote(ciudad, user_id){
    $("#voto-negtivo").val(ciudad);
    $("#usuario").val(user_id);
    $('#form-votar').submit();
}

On a side note, avoid using inline handlers and register events through javascript.

Example:

<td>
   <span class="icon icon-thumbs-down cursor" data-ciudad = "Hamburgo" data-userid="24">
   </span>
</td>

and

 $(function(){
   $('.icon-thumbs-down').click(function(){
        var $this = $(this);
        $("#voto-negtivo").val($this.data('ciudad'));
        $("#usuario").val($this.data('userid'));
        $('#form-votar').submit();
   });
 });

Upvotes: 5

Related Questions