我只想在 php 验证失败时将值输入框中的文本更改为红色?
如何使用 JQuery 来完成此操作?
我使用 Javascript 做到了这一点,除了每次我单击“提交”时,它都会变成红色,然后消失......
<form class="link-form" method="post" action="">
<label>DIRECT LINK</label>
<input type="text" id="url" name="url" value="<?php if(isset($_POST['url'])) { echo htmlspecialchars($_POST['url']); } ?>" />
<input class="btn-submit" type="submit" id="submit" name="submit" value="Generate Direct Link" />
<?php
$directLink = "";
$error = "";
$url = $_POST['url'];
if(isset($_POST['submit'])) {
$partsUrl = parse_url($url);
if ($partsUrl["scheme"] === "https://" && $partsUrl["host"] === "example.com/")
{
$key = substr($partsUrl["path"],8,-5);
$directLink = "https://example.com/".htmlspecialchars($key);
}
else
{
$error = "Invalid, Please insert the correct Link";
}
}
?>
<label>DIRECT LINK</label>
<input type="text" id="directLink" name="directLink" value="<?php if (!empty($directLink)) { echo $directLink; } else { echo $error; } ?>" />
</form>
function colorChange() {
var inputVal = document.getElementById("directLink").value;
if (inputVal === "Invalid, Please insert the correct Link") {
document.getElementById("directLink").style.backgroundColor = "red";
}
else
{
document.getElementById("directLink").style.backgroundColor = "black";
}
}
或者我尝试了下面的 JQuery 示例,但什么也没做。
$('#submit').on('click',function(){
var text = $('#directLink').val();
if(text === 'Invalid, Please insert the correct Link'){
$('#directLink').css({'background-color':'red !important'});
}
});
最佳答案
您可以使用 jQuery 的 css
方法在文本字段上设置 background-color
,如下所示
$('#directLink').css({'backgroundColor':'red'});
如果您只想将文本颜色更改为红色,则应该设置 color
属性
$('#directLink').css({'color':'red'});
如果您尝试使用 red !important
,它只会失败而不会出现任何错误,因为 jQuery 在理解 !important
时存在问题。如果您确实需要使用它,请查看这些解决方法,但就您而言,我认为 !important 确实不需要:)
还有一些变化:-
- 在 if 条件中返回 false 以防止表单 出现错误情况时提交
- 检查 url 的值而不是 directLink,因为它不起作用 下次您发布有效网址时,directLink 仍然有错误 消息和表单将不会提交。
这是一个bin一起玩。
关于javascript - 如果验证失败,使用 JQuery 更改值输入上的文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29193733/