给input赋值的问题

郑爽
  • 57
<form name="favform" action="javascript:void(0)" onsubmit="return gotofav(this)">
<input type="txt" name="fav1" value="-1.933227,115.807851"><input type="submit" value="go" /></form>

<form name="favform" action="javascript:void(0)" onsubmit="return gotofav(this)">
<input type="txt" name="fav2" value="-1.933227,115.807851"><input type="submit" value="go" /></form>

<form name="favform" action="javascript:void(0)" onsubmit="return gotofav(this)">
<input type="txt" name="fav3" value="-1.933227,115.807851"><input type="submit" value="go" /></form>

document.getElementById("这里应该怎么写").value =`${newLatLng.lng},${newLatLng.lng}`;

多个表单,一个函数,需要给input赋值。该怎样做呢?谢谢老师。

回复
阅读 170
1 个回答

可以参考下这个,点击一个表单中的go后,只给给该表单内的input赋值

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <form
      name="favform"
      action="javascript:void(0)"
      onsubmit="return gotofav(this)"
    >
      <input type="text" name="fav1" value="-1.933227,115.807851" /><input
        type="submit"
        value="go"
      />
    </form>

    <form
      name="favform"
      action="javascript:void(0)"
      onsubmit="return gotofav(this)"
    >
      <input type="text" name="fav2" value="-1.933227,115.807851" /><input
        type="submit"
        value="go"
      />
    </form>

    <form
      name="favform"
      action="javascript:void(0)"
      onsubmit="return gotofav(this)"
    >
      <input type="text" name="fav3" value="-1.933227,115.807851" /><input
        type="submit"
        value="go"
      />
    </form>

    <script>
      /**
       * 由于onsubmit调用时你传入了this,而onsubmit函数的this就是对应的form
       * 所以我们可以直接从gotofav的参数中获取form,进而执行响应的操作
       * **/
      const gotofav = (form) => {
        if (!form) return

        Array.from(form.querySelectorAll('[type="text"]')).forEach((input) => {
          input.value = 'newValue'
        })
      }
    </script>
  </body>
</html>
你知道吗?

宣传栏