【问题标题】:Change Input background color as entry is validated在验证条目时更改输入背景颜色
【发布时间】:2014-01-03 18:10:29
【问题描述】:

我一直在使用此代码来检查用户在输入字段中输入的位置是否存在于我们的数据库中。目前,如果它确实匹配,则会更新一个单独的跨度以显示它匹配。

但是我想更改此设置,以便用户当前所在的输入框在匹配时更新其背景颜色。

function location(str)
{
if (str.length==0)
  {
  document.getElementById("location").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("location").innerHTML=xmlhttp.responseText;
    }
  }

xmlhttp.open("GET","check.php?loc="+str,true);
xmlhttp.send();
}

check.php 查询数据库,如果没有匹配则返回#FFFFFF,如果匹配则返回#C000C0。我想更新实际输入框的背景颜色,而不是使用 ID 位置更新跨度。

在另一个脚本中我使用$(this).css("background-color", color); 是否可以使用相同的?并使用 $(this) 更新它们当前所在的字段?

由于页面是一个表单,位置字段被命名为 loc[] 并且可能出现多次,因此使用 $(this) 可能更容易找到它们当前所在的实际输入字段。

谢谢

【问题讨论】:

  • 如果您提到的另一个脚本在同一页面中使用(暗示页面中包含 jQuery),那么是。你可以使用$(<id of input box>).css("background-color", color);
  • @srvikram13 感谢您的回复。我希望使用 $(this) 而不是 $() 因为每个输入具有相同的名称/id。考虑他们应该有唯一的 ID。谢谢
  • HTML 页面中的元素 ID 应该是唯一的。如果您希望访问一堆相似或相关的元素,请考虑使用类。

标签: jquery forms input xmlhttprequest


【解决方案1】:

在另一个脚本中,我使用 $(this).css("background-color", color);是吗 可以使用相同的吗?并使用 $(this) 更新字段 他们目前在?

您可以使用this kewword 传递event 源对象,您需要在位置函数中添加新参数。

function location(str, source)
{
    $(source).css("background-color", color);

    //OR

    source.style.backgroundColor = color;         //or using native method


   ///Your code goes here.
}

编辑基于 cmets

你已经在传递 this.value 你应该传递这个并且不需要第二个参数

function location(source)
{
    str = source.value
    $(source).css("background-color", color);

    //OR

    source.style.backgroundColor = color;         //or using native method    

   ///Your code goes here.
}

【讨论】:

  • 谢谢。我想我明白。我会试试这个,看看我得到了什么。
  • 如果我尝试将 this.value 更改为 str it 错误,我正在使用 onkeyup="location(this.value)"
  • 那么你不需要 seocnd 参数 onkeyup="location(this)" 并且在定位函数中使用 source.value
  • 谢谢 - 我不断收到Uncaught ReferenceError: source is not defined
  • 我的错误在这里,你需要 source.style.backgroundColor = color;不过,您只需要其中一个语句。
猜你喜欢
  • 2021-11-21
  • 2021-03-07
  • 2019-02-03
  • 2011-04-17
  • 2012-01-27
  • 1970-01-01
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多