简体   繁体   中英

How to change input value dynamically

I want to change an input value depending on a $_POST variable. Something like this:

<?php if ($_POST['yourname'] != "") 
    { 
        $('input[name=yourname]').attr('title', $_POST['yourname']); 
    } ?>

But it doesn't work. How can I do that?

Thanks!

EDIT: I have this input:

<input class="clearme" name="yourname" type="text" title="Insert your name"  />

直接添加到html:

<input class="clearme" name="yourname" type="text" title="Insert your name" value="<?php echo isset($_POST['yourname']) ? $_POST['yourname'] : ''; ?>"  />

You can't use javascript in PHP. PHP runs on the server, while javascript runs in the clients browser.

You need to do this in pure javascript, not PHP.

Try this in the one file, replacing 'name_of_cur_file.php' with the name of the current php file.:

<?php

if($_POST['yourname'] > ""){
$yourname = $_POST['yourname'];
}else{
$yourname = ""; // set to avoid errors
}
?>
<form action="name_of_cur_file.php" method="post">
<input type="text" value="<?php echo $yourname;?>" />
<input type="submit" value="go" />
</form>

WARNING!!! - Lacking any validation for this example!!!

If you want the code sent from the server to execute then:

<?php if ($_POST['yourname'] != "") 
    { 
        <script type="text/javascript">
             $(document).ready(function () {
                 $('input[name=yourname]').attr('title', $_POST['yourname']);
             });
        </script>
    } ?>

You have jquery code in php.You have complete first php tag then you have write your jquery code in script code like

<?php if ($_POST['yourname'] != "") 
    { 
?>
      <script>
        $('input[name=yourname]').attr('title', $_POST['yourname']); 
      </script>
<?php
    } ?>

You can also write php code only like

 <?php 
$title="Insert your name";
if ($_POST['yourname'] != "") 
        { 

           $title=$_POST['yourname'];

        } ?>

<input class="clearme" name="yourname" type="text" title="<?php echo $title; ?>" />

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