Reputation: 51
I am trying to change the class of a button if a condition is not met,and that is if(strlen($username) < 5)
then change the class of the button .This is my php:
<?php $buttonClass = 'btn btn-primary'; ?>
<?php
if(isset($_POST['name']) && $_POST['name'] != ""){
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['name']);
$quer = "SELECT * FROM users WHERE username = '$username'";
$resu = mysqli_query($dbc,$quer);
$check = mysqli_num_rows($resu);
if(strlen($username) < 5){
echo '<span class = "glyphicon glyphicon-remove" style = "color:red"> Trebuie sa introduci mai mult de 4 caractere </span>';
$buttonClass .= ' disabled';
exit();
}
if(is_numeric($username[0])){
echo '<span class = "glyphicon glyphicon-remove" style = "color:red"> Primul caracter trebuie sa fie o litera </span>';
exit();
}
if($check < 1){
echo '<span class = "glyphicon glyphicon-ok" style = "color:green"> ' . $username . ' este valabil</span>';
exit();
}else{
echo '<span class = "glyphicon glyphicon-remove" style = "color:red"> Acest username este deja luat </span>';
exit();
}
}
?>
<script type="text/javascript" language = "javascript">
function checkUsername () {
var status = document.getElementById("usernamestatus");
var u = document.getElementById("username").value;
if(u != "")
{
status.innerHTML = 'Se verifica...';
var hr = new XMLHttpRequest();
hr.open("POST","register.php",true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
status.innerHTML = hr.responseText;
}
}
var v = "name="+u;
hr.send(v);
}
}
</script>
And this is my html:
<div class="form-group">
<label for="username" class="col-lg-2 control-label">Username:</label>
<div class="col-lg-10">
<input type="text" name = "username" class="form-control" id="username" onkeyup="checkUsername()">
<br><div class = "userspan">
<span style = "font-size:15px"id = "usernamestatus"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="submit" class="<?php echo $buttonClass ?>" id = "submit" >Submit</button>
</div>
</div>
Upvotes: 0
Views: 75
Reputation: 82
You need to initialize the class variable first.
$buttonClass = 'btn btn-primary';
And then if your conditions are met, you can change it.
if(isset($_POST['name']) && $_POST['name'] != ""){
...
if(strlen($username) < 5)
{
$buttonClass .= ' disabled';
}
}
And then print it in HTML.
<button type="submit" class="<?php echo $buttonClass ?>" id = "submit" >Submit</button>
Upvotes: 1