简体   繁体   中英

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

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>

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';
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM