Javascript函数获取输入值

标签 javascript jquery html forms button

我编写了带有多个按钮的代码,每个按钮都有不同的值。 我正在尝试在 javascript 函数中获取该值。

  <form action="https://www.bing.com" method="get">
    <input class="input" type="text" name="q" id="field" autofocus>
    <div class="buttons">
      <input type="submit" class="button" id="x1" name="x1" value="Bing"> 
      <input type="submit" class="button" id="x2" name="x2" value="Google">
      <input type="submit" class="button" id="x3" name="x3" value="Yahoo"> 
      <input type="submit" class="button" id="x4" name="x4" value="Duck">
      <input type="submit" class="button" id="x5" name="x5" value="Ask"> 
      <input type="submit" class="button" id="x6" name="x6" value="Aol.">
    </div>
  </form>
</div>

<script>
  var form = document.querySelector('form');
  var input = document.getElementById('field');
    var x = document.getElementById('x1').value;

  form.addEventListener('submit', function(ev) {
    ev.preventDefault();

    if(x=="Bing") {

    var redirect = 'https://google.com/search?q=' + input.value; }

    window.location = redirect;
  });
</script>

这里的输入提交仅在单击时才设置值?如果我尝试将所有提交按钮 id 命名为 xx,那么我可以获取函数中单击的按钮。我想在单击相应的提交按钮后执行不同的重定向。 (多次提交操作: 这个问题不重复,是JS特有的,这种情况)

最佳答案

尝试这样。为我工作

    <input class="input" type="text" name="q" id="field" autofocus>
    <div class="buttons">
      <input type="submit" class="button" id="x1" name="x1" value="Bing"> 
      <input type="submit" class="button" id="x2" name="x2" value="Google">
      <input type="submit" class="button" id="x3" name="x3" value="Yahoo"> 
      <input type="submit" class="button" id="x4" name="x4" value="Duck">
      <input type="submit" class="button" id="x5" name="x5" value="Ask"> 
      <input type="submit" class="button" id="x6" name="x6" value="Aol.">
    </div>

</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>


<script>

$(".button").on("click", function(e){
e.preventDefault();
var x = $(this).attr("value");
var redirect = "" 
if (x=="Google")
{

 window.location = "https://google.com/search?q=" + $(".input").val();

}

});

</script>

扩展 if 条件以获得更多搜索选项。

谢谢

关于Javascript函数获取输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30022548/

相关文章:

Jquery 单击仅工作一次

jquery - 如何使用 jquery 设置 HTML5 中表格单元格的背景和字体颜色

javascript - javascript 中的形状补间

jquery - 表大小差异

javascript - 将本地存储值插入数据库

javascript - TinyMCE 不工作——即使有他们的例子?

javascript - 使用 JavaScript/Jquery 关闭 .aspx

html - 不是所有的 CSS 属性都可以向下级联,或者某些标签会忽略父级的属性?

javascript - 在 Three.js 中旋转天空盒

javascript - 在 Angular.js 中,如何修改对象列表中元素的属性,这些对象在点击时使用 ng-repeat 迭代?