如何更改php标签中元素的类?

时间:2015-04-15 10:45:42

标签: php

如果条件不满足,我正在尝试更改按钮的类,那就是if(strlen($username) < 5)然后更改按钮的类。这是我的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>

这是我的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>

1 个答案:

答案 0 :(得分:1)

您需要先初始化类变量。

$buttonClass = 'btn btn-primary';

然后,如果您的条件得到满足,您可以更改它。

if(isset($_POST['name']) && $_POST['name'] != ""){
...
  if(strlen($username) < 5)
  {
    $buttonClass .= ' disabled';
  }
}

然后以HTML格式打印。

<button type="submit" class="<?php echo $buttonClass ?>" id = "submit" >Submit</button>