user2465936
user2465936

Reputation: 1040

Click button. Javascript alert box. If click OK, page reloads and need to create php variable with html input form value

User clicks on Delete button. Javascript alert box popups with OK and Cancel. If user clicks OK, then page reloads (post form) and I need to create php variable with value from here name="confirm_delete")

Here is my code

<form action="<?php echo (htmlspecialchars($_SERVER["PHP_SELF"])) ?>" method="post">

<input name="delete" type="submit" id="delete" value="Delete">

<input type="hidden" name="confirm_delete" id="confirm_delete" value="0" >

<script>
$(document).ready(function() {

  $("#delete").click(function(){

    var answer = confirm("Are you sure you want to delete?");
    if (answer){
    return true;
    document.getElementById('confirm_delete').value = 1;
    } else {
    return false;
    document.getElementById('confirm_delete').value = 0;
    }

  });

});
</script>

Then print_r($_POST['confirm_delete']); but value always is 0. That means that document.getElementById('confirm_delete').value = 1; does not work.

Please, advice what need to correct

Upvotes: 3

Views: 8260

Answers (1)

Code Lღver
Code Lღver

Reputation: 15603

Replace your javascript code by following:

<script>
$(document).ready(function() {

$("#delete").click(function(){

    var answer = confirm("Are you sure you want to delete?");
    if (answer){
    document.getElementById('confirm_delete').value = 1;
    return true;
    } else {
    document.getElementById('confirm_delete').value = 0;
    return false;
    }

  });
});
</script>

You are using the return true and false first after that you are assigning the value. so return terminates from the function before assign the value. so first assign the value and then use the return.

Upvotes: 4

Related Questions