【问题标题】:How to write in 2 input at the same time如何同时写入2个输入
【发布时间】:2019-07-30 14:46:28
【问题描述】:

您知道如何同时在两个输入中写入文本吗?输入 1 中写入的内容出现在输入 2 中,但经过修改,例如: 您好,您知道如何同时在两个输入中写入文本吗?输入 1 中写入的内容出现在输入 2 中,但经过修改,例如:

输入 1:这是一个文本

输入 2:这是一个文本

我尝试使用str_replace (),但我无法实时使用

<?php 

$texto = $_POST['title'];
$urlcambiado = str_replace(" ", "-", $texto);

?>

<input type="text" name="title" class="form-control" placeholder="Ejemplo: sword-art-online">
<input type="text" name="url_code" class="form-control" placeholder="Ejemplo: sword-art-online">

【问题讨论】:

  • PHP 在服务器上运行。要完成您想要做的事情,您需要使用 JavaScript。

标签: php html input


【解决方案1】:

这将使用纯 javascript 完成您想要的操作:

function URLChange(titlestr) {
  var url=titlestr.replace(/ /g,"-");
  document.getElementsByName("url_code")[0].value=url;
}
<input type="text" name="title" class="form-control" placeholder="Ejemplo: sword-art-online" onkeyup='URLChange(this.value);'>
<input type="text" name="url_code" class="form-control" placeholder="Ejemplo: sword-art-online">

【讨论】:

    【解决方案2】:

    这必须在客户端使用 JavaScript 完成,有点像这样:

    引用两个输入字段

    两者的名称属性分别设置为titleurl_code。要获得对它的引用,我们可以使用getElementsByName() 方法,该方法返回一个 HTMLCollection - 一个数组。由于每个名称只有一个元素,我们可以附加 [0] 以获取数组中的第一个元素。 var firstInput=document.getElementsByName("title")[0]; var secondInput=document.getElementsByName("url_code")[0];

    附加一个输入事件监听器

    要确定用户是否在第一个输入中输入了任何内容,我们需要使用此侦听器,该侦听器调用回调函数,然后我们可以使用它来获取实际文本。

    firstInput.addEventListener("input",process);
    

    修改第二个输入中的文本

    在回调函数中,我们可以从第一个输入中检索文本,使用正则表达式将空格替换为减号并将文本分配给第二个文本字段。

    function process(e) {
      secondInput.value = e.target.value.replace(/\s/g, '-');
    }
    

    这是一个完整的例子:

    var firstInput = document.getElementsByName("title")[0];
    var secondInput = document.getElementsByName("url_code")[0];
    
    function process(e) {
      secondInput.value = e.target.value.replace(/\s/g, '-');
    }
    firstInput.addEventListener("input", process);
    <input type="text" name="title" class="form-control" placeholder="Ejemplo: sword-art-online">
    <input type="text" name="url_code" class="form-control" placeholder="Ejemplo: sword-art-online">

    【讨论】:

      猜你喜欢
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多