HTML:
<form id="frm"></form>
JS:
$(function () {
$("#frm").append('<input class="btn" type="submit" name="GoTest" value="Preview"/>');
$("#frm").append('<input class="btn" type="submit" name="GoTest1" value="Next"/>');
$("#frm > .btn").on("click", function (e) {
e.preventDefault();
if ($(this).val() == "Next") {
alert("It's button Next");
} else {
alert("It's button Preview");
}
});
});
SIMPLIFIED CODE:
$(function () {
$("#frm").append('<input class="btn" type="submit" name="GoTest" value="Preview"/>');
$("#frm").append('<input class="btn" type="submit" name="GoTest1" value="Next"/>');
$("#frm > .btn").on("click", function (e) {
e.preventDefault();
alert("It's button " + $(this).val());
});
});
WITHOUT USING CLASS ATTRITBUTE: jsFiddle
$(function () {
$("#frm").append('<input class="btn" type="submit" name="GoTest" value="Preview"/>');
$("#frm").append('<input class="btn" type="submit" name="GoTest1" value="Next"/>');
$("#frm > [name^='GoTest']").on("click", function (e) {
e.preventDefault();
alert("It's button " + $(this).val());
});
});
Documentation:
[attribute^=value]
: All elements with a name attribute value starting with value.
Updated: To use the child property, please note the e.preventDefault() will stop the auto POST
of the FORM
html tag.