简体   繁体   中英

How To Add ucwords() in PHP To HTML Form Value?

I have a basic contact form on my website and I am trying to add the PHP ucwords() function of PHP to the form for the users first_name and last_name fields so they capitalize the first letter correctly. How would I add this to the actual HTML form?

Edit: I want these changes to be applied only after the user submits the form. I don't really care about how the user types it in. I just need someone to actually show me an example.

Like how would I add the PHP ucwords() code to this simple form?

<!DOCTYPE html>
<html>
<body>

<form action="www.mysite.com" method="post">
First name: <input type="text" name="first_name" value="" /><br />
Last name: <input type="text" name="last_name" value="" /><br />
<input type="submit" value="Submit" />
</form>

</body>
</html>

I am assuming I do something like value='<php echo ucwords() ?>' but I have no idea how?

Thanks!

When user submit the form you can access the submitted information through $_POST variable [because method="post"] of PHP and in action you have to specify the actual page where you need the submitted information to be process further

<?php
// for example action="signup_process.php" and method="post" 
// and input fields submitted are "first_name", "last_name" 
// then u can access information like this on page "signup_process.php"

// ucwords() is used to capitalize the first letter 
// of each submit input field information

$first_name = ucwords($_POST["first_name"]);
$last_name = ucwords($_POST["last_name"]);
?>

PHP Tutorials

Assuming short tags are enabled:

$firstName = 'Text to go into the form';
<input type="text" name="first_name" value="<?=ucwords($firstName)?>" />

Otherwise as you stated

<input type="text" name="first_name" value="<?php echo ucwords($firstName); ?>" />

Assuming you wanted to do it without a page refresh, you need to use Javascript. Simplest way would be to add an onkeyup event to the input field and simulate PHP's ucwords functions, which would look something like...

function ucwords(str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

Edit: In response to your edit, if you want to get the value they sent with ucwords applied, all you need to do is $newVal = ucwords($_POST['fieldName']);

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