如果字段为空,则回显占位符

发布于 2024-10-22 19:03:19 字数 522 浏览 3 评论 0原文

我有一个输入,我想在其中放入占位符文本,但仅当它的相应值是空字符串。文本框中应输入的值是从 PHP 数组中回显的,但如果该值为空,则应回显占位符。目前,我有这样的代码:

<?php echo sponsorData('address0') == '' ? 'Address Line 1' : 'Other'; ?>

sponsorData() 只是从数组中获取内容;唯一的论点是关键。这里重要的一点是它返回一个字符串。

这段代码给出了奇怪的行为;我得到类似 Hello worldAddress Line 1 的内容,其中 Hello world 是用户输入的文本,而 Address Line 1 显然是占位符。奇怪的是,占位符在提交时被存储到数组中。

我的问题是:有人可以对我的三元运算符进行更正吗?或者,如果这不起作用,请告诉我执行内联 if 语句(blegh)?

谢谢

I have an input that I'd like to put a placeholder text in, but only if it's respective value is an empty string. The value that should go in the textbox is echoed from a PHP array, but if this value is empty, the placeholder should be echoed instead. At the moment, I've got this code:

<?php echo sponsorData('address0') == '' ? 'Address Line 1' : 'Other'; ?>

sponsorData() just gets stuff from an array; it's only argument is the key. The important bit here is it returns astring.

This code gives odd behaviour; I get stuff like Hello worldAddress Line 1, where Hello world is the user typed text and Address Line 1 is obviously the placeholder. Strangely, the placeholder gets stored into the array on submission.

My question is this: can someone offer a correction of my ternary operator or, if that won't work, tell me to do an inline if statement (blegh)?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

飘逸的'云 2024-10-29 19:03:19

尝试以下代码:

<?php echo ((sponsorData('address0') == '') ? 'Address Line 1' : 'Other'); ?>

felix

try the following code:

<?php echo ((sponsorData('address0') == '') ? 'Address Line 1' : 'Other'); ?>

felix

阿楠 2024-10-29 19:03:19

您遇到了运算符优先级问题。尝试:(

<?php echo (sponsorData('address0') == '' ? 'Address Line 1' : 'Other'); ?>

将三元运算符语句放在括号中)。

You're running into operator precedence issues. Try:

<?php echo (sponsorData('address0') == '' ? 'Address Line 1' : 'Other'); ?>

(put brackets around the ternary operator statement).

假面具 2024-10-29 19:03:19

你似乎工作正常,我不认为错误在那里。我将这样做:

$address0 = sponsorData('address0');

$address0 = !empty($address0) ? $address0 : 'placeholder';

You seem to have this working ok, I don't think the error lies there. Here is how I would do it:

$address0 = sponsorData('address0');

$address0 = !empty($address0) ? $address0 : 'placeholder';
心凉 2024-10-29 19:03:19

您必须考虑到 sponsorData('address0') 可能有空格,因此您可以添加 trim 函数,如下所示:

<?php echo ((trim(sponsorData('address0')) == '') ? 'Address Line 1' : 'Other'); ?>

You have to consider that the sponsorData('address0') may have spaces, so you can add the trim function, like this:

<?php echo ((trim(sponsorData('address0')) == '') ? 'Address Line 1' : 'Other'); ?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文