更改输入的背景颜色

时间:2015-08-29 02:16:48

标签: php jquery

我这里有一个代码,我想要完成的是实时检查,当存在用户名时,该文本输入的背景颜色将会改变。顺便说一下,我使用了纤薄的框架,这就是我现在所做的:

html和jQuery:

<input type="text" name="txt_un" id="txt_un" />

<script>
$("#txt_un").keyup(function (e) {
   var username = $(this).val();
   $.post('/check/username/availability', {'username':username}, function(data) { 
   $("#user-result").html(data); //this will dump the data received from the php but I just want it to change the color of the input
   });
});
</script>

php route:

$app->get('/check/username/availability', function() use($app) {
    $db = new db();
    $db->setErrorCallbackFunction("myErrorHandler", "text");
    $request = \Slim\Slim::getInstance()->request()->post();
    $app = \Slim\Slim::getInstance();
        $bind = array(
            ":un" => $request['txt_un']
        );
        $result = $db->select("accounts", "username = :un", $bind);
        if(count($result) > 0) {
            //change background color of txt_un
        } else {
            //change background color of txt_un
        }
});

如何使用我的代码完成它?还是有另一种方法吗?谢谢。

2 个答案:

答案 0 :(得分:1)

您可以在php脚本中输出颜色代码(#ffffff或红色)或某些标志。 在JS中,您可以使用$(selector).css方法。

function Change(color){
    $('.example').css({
        background: color
    });
}

Change('red');

尝试:http://jsfiddle.net/x7xm7svr/

关于方法:http://api.jquery.com/css/

在您的情况下,如果服务器方法返回0 on已存在且1不存在:

$("#txt_41").keyup(function (e) {
   var username = $(this).val();
   $.post('/check/username/availability', {'username':username}, function(data) { 
        if(data=='0')
            { $("#txt_un").css({background: 'red'}); }
        else
            { $("#txt_un").css({background: 'green'}); }
   });
});

答案 1 :(得分:0)

我使用Roman Kirillov的答案,并通过改变从post到get的路线。这是最终的代码:

路线:

$("#txt_41").keyup(function (e) {
   var username = $(this).val();
   $.post('/check/username/availability', {'username':username}, function(data) { 
        if(data=='0')
            { $("#txt_41").css({background: 'red'}); }
        else
            { $("#txt_41").css({background: 'green'}); }
   });
});

jQuery的:

NullPointerException

感谢您查看:)