2

I have this html button that I am trying to pass the id to a function

<button class= "btn1" id="buttonid1">Set Text</button>
<button class= "btn1" id="buttonid2">Set Text</button>                      

Here is the Javascript to it

$(".btn1").click(function(){
    doSomething();                  
    });

function doSomething() {
    goUrl = 'http://www.example/' 
    + $(this).attr('id'); 
    window.location = goUrl;
    }

I want the function to redirect the browser to a different website based on button pressed

dac086
  • 91
  • 3
  • 11
  • `$(this)` is undefined in `doSomething` method. You should pass the button and get id of the button, or pass the id of the button to the method. – pms Jul 23 '14 at 17:53

5 Answers5

2

Why creating an anonymus function to run a function. Just directly pass the function :

$(".btn1").click(doSomething);

You don't have to change the doSomething function.

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
1

Try this way:

$(".btn1").click(function(){
    doSomething($(this).attr('id'));                  
});


function doSomething(myId) {
goUrl = 'http://www.example/' 
+ myId; 
window.location = goUrl;
}
Hackerman
  • 12,139
  • 2
  • 34
  • 45
1

I think IDs are heavily abused. You can just pass the button itself:

$(".btn1").click(function(){
    doSomething(this);                  
});

function doSomething(button) {
    goUrl = 'http://www.example/' 
    + button.id; 
    window.location = goUrl;
}
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
1

You could use data-* attributes to store a id which you wan't to append to your url:

HTML:

<button class="btn" data-id="1">Button id 1</button>
<button class="btn" data-id="2">Button id 2</button>

With your js, you then just read the value of data-id and move to that url:

JavaScript:

$(".btn").click(function(){

    // go to url e.g. http://example.com/1
    window.location.href = "http://example.com/" + $(this).data("id");

});

Finally, as it seems, your buttons are acting as links (doing navigation) you should consider changing them to links. (a href). Consider this case by case basis. window.location.href already simulates similar behavior as clicking a link. You can read more about it from javascript redirect.

Cheers.

Community
  • 1
  • 1
Mauno Vähä
  • 9,688
  • 3
  • 33
  • 54
0

The problem is that you've wrapped doSomething within a function, so the context of this is no longer your element.

Here is the code, with corrections:

$(".btn1").click(doSomething);

function doSomething() {
    goUrl = 'http://www.example/' 
    + $(this).attr('id'); 
    window.location = goUrl;
}
Grinn
  • 5,370
  • 38
  • 51