DutchyOnDuty
DutchyOnDuty

Reputation: 13

Get value from button in while loop

I've got a while loop with multiple buttons, they are like this:

<button onclick="confirmDelete()" value="<?php echo $game['id'];?>" name="deleteButton">Delete </button> 

It is followed by the following confirm message:

<script>
function confirmDelete() {

var r = confirm(" **HERE I WANT THE ID TO START WITH** ");
if (r == true) {
    // delete
} else {
    // cancel
}
}
</script>

Each button has his own value, but now i want that value in my javascript when i click on that button. I tried multiple things but cant make it work.

EDIT:

If someone can tell me an better/easier way to do this, you're welcome to tell me

Upvotes: 1

Views: 1309

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 98881

Use your function with this argument, i.e.:

<button onclick="confirmDelete(this)" id="myButton" value="someId" name="deleteButton">Delete </button> 
<script>
function confirmDelete(elem) {
var r = confirm(" **HERE I WANT THE ID TO START WITH** ");
var theValue = elem.value; //someId
var theId    = elem.id; //myButton
if (theValue == "True") {
    alert("True")
} else {
    alert("False")
}
}
</script>

LIVE DEMO:
http://codepen.io/anon/pen/QyZgqO

Upvotes: 1

Elliott
Elliott

Reputation: 2205

Pass the game ID into the confirmDelete function as a parameter

<button onclick="confirmDelete(<?php echo $game['id'];?>)" name="deleteButton">Delete </button>

<script>
    function confirmDelete(id) {

        var r = confirm(id);
        if (r == true) {
            // delete
        } else {
            // cancel
        }
    }
</script>

Upvotes: 1

Related Questions