Newbie
Newbie

Reputation: 25

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!

Upvotes: 0

Views: 2490

Answers (2)

dlwiest
dlwiest

Reputation: 655

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']);

Upvotes: 0

Martin
Martin

Reputation: 6687

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); ?>" />

Upvotes: 0

Related Questions