简体   繁体   English

Javascript捕获表单文本字段on更改为隐藏字段

[英]Javascript capture form text field onChange to hidden field

I have a form with a simple text field for a person's full name. 我有一个带有一个简单文本字段的表格,用于填写一个人的全名。

After a user enters their name and moves/tabs to the next field, I want to be able to capture the full name, extract only the first name, and attach to a separate hidden form field. 用户输入名称并将其移动/跳至下一个字段后,我希望能够捕获全名,仅提取名字,并附加到单独的隐藏表单字段。

If the user goes back and corrects their full name, the extraction should repeat to get the correct first name. 如果用户返回并更正其全名,则应重复提取以获取正确的名字。 The full name text field would still be passed along during form submittal. 全名文本字段仍将在表单提交期间传递。

I'm thinking plain JS would be the best approach (I'm not using JQuery). 我认为普通的JS是最好的方法(我没有使用JQuery)。

<form>
    <input type="text" name="fullname" value="">
    <input type="hidden" name="firstname" value="">
</form>

you can try this 你可以试试这个

this is your html 这是你的html

<form>
    <input type="text" name="fullname" value="" id="fullname">
    <input type="hidden" name="firstname" value="" id="firstname">
</form>

this is your javascript 这是你的javascript

<script>

    let fullName = document.getElementById("fullname");

    let firstName = document.getElementById("firstname");

    fullName.addEventListener("blur", function() {

      let names = fullName.value.split(" ");

      if (names.length > 0) {
        firstName.value = names[0];
      }

    });

</script>

https://jsfiddle.net/3k8kur9u/ https://jsfiddle.net/3k8kur9u/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM