0

Add a class to an element by JQuery, If php condition is checked. Hi. This code does not work. If anybody knows an alternative method I much appreciate it. Thank you.

<form method="post">
 <input class="blue" name="btn" type="Submit" value="Submit" />
</form>

<?php

if(isset($_POST["btn"])){
  $query = mysqli_query($con,"select * from table");
  $row = mysqli_fetch_assoc($query);
  $name = $row['name'];
  if($name == "kamal"){
    ?>
      <script type="text/javascript">
        $('.blue').addClass('green');
      </script>
    <?php
  }
  else{
    ?>
      <script type="text/javascript">
        $('.blue').addClass('red');
      </script>
    <?php
  }
}

?>

0

2 Answers 2

1

Actually you have to add $(document).ready

Like this:

$(document).ready(function(){

   $('.blue').addClass('red').removeClass('blue');

});

This way you can call your jquery function after document load

——Edit——

By the way i recommend you to make this all php or all javascript. It doesn’t have any sense to send a form by php and replace class with jquery. Actually you can do the same printing the result with new class with simple echo in php.

But if you want to make this dynamic you can use jquery for send the form by Ajax preventing submit, getting the response from php route and displaying change of color dynamically without reloading page

Sign up to request clarification or add additional context in comments.

1 Comment

Still does not work :( , but thank you for this information.
0

I suggest you handle this via php as it's more logical in this example

In which case I would store the class in a variable and echo it directly into the element's class property like so:

<?php
$input_class = '';
if(isset($_POST["btn"])){
  $query = mysqli_query($con,"select * from table");
  $row = mysqli_fetch_assoc($query);
  $name = $row['name'];
  if($name == "kamal"){
    $input_class = 'green';
  }
  else{
    $input_class = 'red';
  }
}

?>

<form method="post">
 <input class="blue" name="btn" type="Submit" value="Submit" class="<?php echo $input_class; ?>"/>
</form>

1 Comment

This is a good alternative method, thank you very much, i'll work on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.