Reputation: 11
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
}
}
?>
Upvotes: 0
Views: 976
Reputation: 1656
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>
Upvotes: 0
Reputation: 512
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
Upvotes: 1