Francisco Maria Calisto Francisco Maria Calisto - 4 months ago 20
Javascript Question

How to restrict an append String in JavaScript?

Calling JavaScript function on delete

OnclintClick
event will give us the confirmation button message returning
Yes
when clicked
OK
.

The problem is, when clicked a second time, it will append the next String.


ex:
Yes, Yes



JavaScript

function Confirm() {

var confirm_value

confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";

if (confirm("Are you sure want to delete supplier?")) {
confirm_value.value = "Yes";
}

else {
confirm_value.value = "No";
}

document.forms[0].appendChild(confirm_value);
}


Explanation

The JavaScript Confirm method store the input provided by the user in a dynamically created hidden field i.e. if
OK
is pressed it will be stored the value
Yes
and if
Cancel
is pressed it will be stored the
No
value, so that it can pass the user inputs onto server side code.

Then It will allow the button to do normal PostBack and raise the
OnClick
event.

Question

How could the append be restricted to this?

Answer

Just give the element an ID, and check for the ID the next time

function Confirm() {

    var id = "confirm_value",
        confirm_value = document.getElementById("confirm_value");

    if ( !confirm_value ) {
        confirm_value  = document.createElement("input");
        confirm_value.type = "hidden";
        confirm_value.name = id;
        confirm_value.id   = id;

        document.forms[0].appendChild(confirm_value);
    }

    confirm_value.value = confirm("Are you sure want to delete supplier?") ? "Yes" : "No";
}