javascript - 如何使带有 <input> 按钮的搜索栏在输入时打开域?

标签 javascript html forms

我目前有一个自定义 DuckDuckGo 搜索栏的代码:

<form action="https://duckduckgo.com/" method="get" id="ddg-search">
    <div class="div-block-4">
        <input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
    </div>
</form>

当您在框中输入文本并按 Enter 键时,它会自动打开 URL https://duckduckgo.com/?q={{SEARCH}}

如果输入了一个域,我怎样才能使这个栏转到一个域?理想情况下,它不会验证域,只是如果它看到模式 xxxx.* 中没有空格的字符串,它就会在新选项卡中打开该页面。

感谢您的帮助!

最佳答案

解决这个问题的一种方法是捕获表单的提交事件,分析输入值,当它是一个域时,用该域打开一个新窗口,并通过返回 false 取消提交。如果不是有效域,则返回 true,让表单照常进行。

您的 HTML:

<form action="https://duckduckgo.com/" method="get" onsubmit="return decideWhatToDo()" id="ddg-search">
    <div class="div-block-4">
        <input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
    </div>
    <input type="submit" />
</form>

您的 JavaScript:

function decideWhatToDo() {  
  let inputValue = document.getElementById('field-3').value;

  if (isDomain(inputValue)) {
    // the form won't be sent and a new window will open requesting the domain    
    if (!startsWithProtocol(inputValue)) {
      inputValue = 'http://' + inputValue;
    }

    window.open(inputValue, '_blank');
    return false;
  } 

  // Proceed to send the form as usual
  return true;
}

function startsWithProtocol(value) {
  return /^((https?|ftp|smtp):\/\/)/.test(value);
}

function isDomain(value) {
  return /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/.test(value);
}

关于javascript - 如何使带有 &lt;input&gt; 按钮的搜索栏在输入时打开域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562399/

相关文章:

javascript - 从 sdcard 加载 html 到 android 中的 webview 时出现 HTML、css、js 问题?

java - 获取 Unicode 字符近似等于以在 HTML 页面中显示

php - reCAPTCHA 集中对齐

python - Django 1.6 名称选择未定义

javascript - 是否可以在没有 Javascript 的情况下将比其父元素更宽且绝对定位的元素居中?

javascript - 验证 WordPress 简单工作板插件中的文本字段内容

javascript - 正则表达式在不破坏现有 HTML 代码的情况下转换链接中的主题标签

javascript - 我只是无法让这个 JSON 数据出现

javascript - 无法获取 firebase 用户 ID

PHP/Javascript 表单生成器/模式定义器