EDIT: document.getElementById('submit').disabled='disabled'; does the trick if I put it instead of return false; but for some reasons, it also disables the button when the username is NOT taken.
Below is basic script to check a username availability.
How can I prevent the form from being submitted if a username is already taken?
Ideally i would like to have a JS alert box pop up.
I've tried to add this to the JS but didn't work:
document.getElementById('submit').disabled
Also I've tried to add onclick="return validate();" to the form itself, but no luck either: the form still can still get submitted.
HTML
<form id="edit" action="edit.php" method="post">
<fieldset>
<label>Username</label><input type="text" class="input" name="username"
id="username"/><span id="status"></span>
<button type="submit" id="submit" value="add">Save</button>
</fielset>
</form>
Script
<script type="text/javascript">
$(document).ready(function() {
$("#username").change(function() {
var username = $("#username").val();
var msgbox = $("#status");
if (username.length >= 4) {
$("#status").html('<img src="images/gif/ajax-loading.gif">');
$.ajax({
type: "POST",
url: "ajax_check.php",
data: "username=" + username,
success: function(msg) {
if (msg == 'OK') {
msgbox.html('<img src="/images/yes.png">');
return true;
} else {
msgbox.html(msg);
return false;
}
}
});
} else {
$("#status").html('<img src="/images/no.png">too long!');
return false;
}
return false;
});
});
edit.php and ajax_check.php only contain some SQL queries.
Also, some users have JavaScript disabled on their browser, how could I get around this?
onclick="return validate();"should do the trick. Where you placed that? it should be in the button element. There is no way to force JS execution, actually the page can be accessed with some download utilities (wget for instance) that don't have any idea what JS is. :)onsubmitevent? Like<form onsubmit="return validate();">.function validate?