dac086
dac086

Reputation: 91

Passing button id to function

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

Upvotes: 2

Views: 3238

Answers (5)

Mauno V&#228;h&#228;
Mauno V&#228;h&#228;

Reputation: 9788

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.

Upvotes: 1

Grinn
Grinn

Reputation: 5543

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;
}

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

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.

Upvotes: 2

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

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;
}

Upvotes: 1

Hackerman
Hackerman

Reputation: 12295

Try this way:

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


function doSomething(myId) {
goUrl = 'http://www.example/' 
+ myId; 
window.location = goUrl;
}

Upvotes: 1

Related Questions