最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - use php to change a html elements inner text - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited Sep 25, 2011 at 19:22 Rusty Fausak 7,5251 gold badge29 silver badges39 bronze badges asked Sep 25, 2011 at 19:14 Graeme LeighfieldGraeme Leighfield 2,9854 gold badges27 silver badges40 bronze badges 1
  • Are you wanting to run PHP on the client, or submit to the server and return a result to the client? – Jared Farrish Commented Sep 25, 2011 at 19:26
Add a comment  | 

4 Answers 4

Reset to default 5

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>

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.

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

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.

发布评论

评论列表(0)

  1. 暂无评论