Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use php to change a html elements inner text

Tags:

javascript

php

I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.

Something like

if ($mytextfield = null) {
    //My custom error text to appear in the spcificed #logggingerror field
}

I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?

Bit of a new thing for me with php, any help greatly appreciated :)

Thanks

like image 550
Graeme Leighfield Avatar asked Jun 06 '26 22:06

Graeme Leighfield


1 Answers

You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.

Do it like this:

<?php
if(isset($_POST['submit'])){
    if(empty($_POST['somevar'])){
        $error = "Somevar was empty!";
    }
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />

<?php
if(isset($error) && !empty($error)){
    ?>
    <span class="error"><?= $error; ?></span>
    <?php
}
?>
</form>
like image 120
Erik Terwan Avatar answered Jun 08 '26 13:06

Erik Terwan