Graeme Leighfield
Graeme Leighfield

Reputation: 2985

use php to change a html elements inner text

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

Upvotes: 3

Views: 32429

Answers (4)

Erik Terwan
Erik Terwan

Reputation: 2780

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>

Upvotes: 5

masoud
masoud

Reputation: 56479

If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.

Upvotes: 4

Nick Nizovtsev
Nick Nizovtsev

Reputation: 373

Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...

For validate the field param you may write like this:

if(strlen($_REQUEST['username']) < 6){
 echo 'false';
}
else{
 echo 'true';
}

Upvotes: 3

Rijk
Rijk

Reputation: 11301

You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.

Upvotes: 2

Related Questions