2012-08-13 83 views
0

我在我的網站上有一個基本的聯繫表單,我正在嘗試將PHP的ucwords()函數添加到用戶first_name和last_name字段的表單中,以便它們正確地大寫第一個字母。我如何將這添加到實際的HTML表單中?如何將PHP中的ucwords()添加到HTML表單值?

編輯:我希望這些更改僅在用戶提交表單後才能應用。我並不在意用戶是如何輸入它的,我只是需要有人向我展示一個例子。

像我將如何添加PHP ucwords()代碼到這個簡單的形式?

<!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> 

我假設我做了一些像value='<php echo ucwords() ?>'但我不知道如何?

謝謝!

+0

如果你的意思,因爲他們類型,您需要使用Javascript了點。如果您在提交表單後需要它,那麼在處理該字段之前,您只需使用該字段的POST數據和'ucwords'。 – tigrang 2012-08-13 18:45:05

+0

你的意思是你想要將這個應用到用戶輸入的輸入,或者只是在服務器上處理文章時? – 2012-08-13 18:45:16

+0

我只關心數據是如何發佈和處理的。 – Newbie 2012-08-13 18:48:50

回答

1

假設短標籤啓用:

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

否則,你說

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

這將不起作用 – 2012-08-13 18:49:21

+0

問題已被編輯 - 但仍然是錯誤的。我猜OP意味着要問一個JavaScript問題。 – Martin 2012-08-13 18:52:42

0

假設你想做到這一點無需刷新頁面,則需要使用JavaScript。最簡單的辦法是一個onkeyup事件添加到輸入字段和模擬PHP的ucwords功能,這將是這個樣子......

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

編輯:在回答您的編輯,如果你想獲得的價值,他們使用ucwords發送,所有你需要做的就是$newVal = ucwords($_POST['fieldName']);

+0

我正在尋找更多的東西:value ='<?php if(!empty($ first_name)){echo echo ucwords($ first_name); }?>'這可能嗎? – Newbie 2012-08-13 18:55:10

+0

除了雙「回聲」外,看起來不錯。 – dlwiest 2012-08-13 18:56:06

+0

當我使用:value ='<?php if(!empty($ first_name)){echo ucwords($ first_name); }?>'我的表單提交後,first_name值不會改變?第一個字母仍然是小的情況? – Newbie 2012-08-13 19:00:39

0

當用戶提交表單時,你可以通過PHP的$ _POST變量[因爲method =「post」]來訪問提交的信息,並且必須指定您需要提交信息的實際頁面將進一步處理

<?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

相關問題