2017-02-21 87 views
0

我使用Bootstrap,我有两个相同的形式。我正在尝试向Google搜索结果添加表单提交,并且它可以正常工作,但是当我包含两个相同的表单时,由于这两个表单的ID相同,因此无法工作。我怎样才能解决这个问题?该ID需要相同,因为谷歌寻找“G”。我有两种形式的原因是因为我在移动设备上的显示方式不同。使用媒体查询。以下是我的代码谢谢。问题与表单验证Javascript

<form name="globalSearch" class="navbar-form" role="search" form action="" onsubmit="return validateSearch()"> 
     <div class="input-group add-on"> 
      <input type="hidden" name="cx" value="" /> 
      <input type="hidden" name="cof" value="FORID:11;NB:1" /> 
      <input type="hidden" name="ie" value="UTF-8" /> 
      <input class="form-control" placeholder="Search entire site..." id="q" name="q" type="text"> 
      <div class="input-group-btn"> 
      <button class="btn btn-default btnSubmit" type="submit"> 
       <i class="glyphicon glyphicon-search"></i> 
      </button> 
      </div> 
     </div> 
</form> 

function validateSearch() { 
     if (globalSearch.q.value.length == 0) { 
      document.getElementById("q").value = "Enter a Value"; 
      document.getElementById("q").style.color = "red"; 
      return false; 
     } 
    } 
+0

在单个页面上重复ID是个坏习惯。使用不同的ID并保持相同的名称。 –

+0

“q”对于Google来说是必需的。我不能改变它 – Tom

+0

你确定这是必要的ID,而不只是在名称属性?正如我可以从google.com搜索页面看到的,他们只是使用name属性和自定义ID。 –

回答

1

你可能想改变占位符,所以用户不必删除文本而不是输入查询。请查看更新的功能。

function validateSearch() { 
    var q = document.getElementById('q'); 
    if (q.value.length == 0) { 
    q.setAttribute('placeholder', 'Enter search term') 
    q.style.borderColor = "red"; 
    return false; 
    } 
} 
1

两个元素不能共享相同的ID。 无论是使用CSS样式,使移动不同的外观,无论是隐藏的web服务器的形式之一(PHP /等)侧或者不使用的getElementById - 相反,使用jQuery:

<form name="globalSearch" ... > 
<input name="q" data-input-type="desktop" id="q"> 
.. 
</form> 
<script> 
function validateSearch() { 

    var field = $("input[data-input-type="desktop"]'); 
    field.val("Enter value here..."); 
    field.css("color","red"); 
} 
</script>