How to set value of one input field based on another input field?

纵饮孤独 提交于 2021-01-29 12:20:45

问题


I am trying to set the value of slug field by manipulating the input of another field title using JavaScript. When I type in the slug and then again i start typing in the title field the value of slug field doesn't get updated. here is my form

document.getElementById('title').addEventListener("input", function(){
    let title = document.getElementById('title').value;       
    console.log(title);
    title = title.toLowerCase();
    title = title.replace(/\s+/g, '-');
    document.getElementById('slug').setAttribute("value", title);
    console.log(document.getElementById('slug').value);
});
<form method="POST" action="http://laravel.dv/admin/blog/post/store" id="create-post" enctype="multipart/form-data">
  <input type="hidden" name="_token" value="2HeXBBKd1HSmpuGvjYqF1KygbGsCQaZtkuUthi1s">            <div class="page-title">
      <h1>Create A Blog</h1>
  </div>
  <br>
  <div class="row">
    <div class="col-12">
      <div class="form-control">
          <input type="text" id="title" name="title" value="" placeholder="Title" >
      </div>
      <div class="form-control">
          <input type="text" id="slug" name="slug" value="" placeholder="Slug" >
      </div>
      <div class="form-control">
          <input type="file" name="image" placeholder="Image upload">
      </div>
      <div style="margin: 0 0 20px;">
          <textarea name="body" id="summernote"></textarea>
      </div>
    </div>
      <div class="col-12">
          <input type="submit" name="btnSubmit" class="btn-primary" value="Save Post" />
      </div>
  </div>
</form>

                  
        

回答1:


Hi try using the value property instead:

document.getElementById('title').addEventListener("input", function(){
  let title = document.getElementById('title').value;        
  console.log(title);
  title = title.toLowerCase();
  title = title.replace(/\s+/g, '-');
  document.getElementById('slug').value = title;
  console.log(document.getElementById('slug').value);
});

Should work :)

This is because value should be accessed with the dot notation and also setAttribute is used to modify the original value of the input which in your case is not present




回答2:


Event Object

Always pass the Event Object⁰ to an event listener/handler/callback:

document.forms[0].addEventListener("input", syncData); 
           ³                                     ²
function syncData(eventObj) {...
           ¹         ⁰

Note that the callback function syncData()¹ is a named function that's not wrapped in the event listener. Also note that when called by an event listener/handler the parenthesis ()² are removed. The reason why is because when rendered, () would run immediately rather than run when a registered event is fired. One last thing for this part is the DOM Object registered to the input event: document.forms[0]. That is a reference to the <form> tag via document.forms interface


Event.target & Event.currentTarget

The event properties: Event.target¹ and Event.currentTarget⁰ come from the Event Object. e.target is a reference to the tag that was clicked, inputted, etc. (ex. #slug) and e.currentTarget is a reference to the ancestor tag that's registered to the event (ex. form). The form.elements is an array-like object that contains all form fields of a given form, the .elements² property makes it possible to reference any of form controls by id or name -- this: form.elements.fields.title.value is the same as: document.getElementById('title').value;

  const form = e.currentTarget;⁰
  const active = e.target;¹
  const fields = form.elements;²

Demo

I wasn't 100% sure about how you wanted the text input behavior so I made the typing in sync both ways.

<!DOCTYPE html>
<html>

<head>
  <style>
    .as-console-wrapper {
      width: 350px;
      min-height: 100%;
      margin-left: 45%;
    }
    
    .as-console-row.as-console-row::after {
      content: '';
      padding: 0;
      margin: 0;
      border: 0;
      width: 0;
    }
  </style>
</head>

<body>
  <form method="POST" action="http://laravel.dv/admin/blog/post/store" id="create-post" enctype="multipart/form-data">
    <input type="hidden" name="_token" value="2HeXBBKd1HSmpuGvjYqF1KygbGsCQaZtkuUthi1s">
    <div class="page-title">
      <h1>Create A Blog</h1>
    </div>
    <br>
    <div class="row">
      <div class="col-12">
        <div class="form-control">
          <input type="text" id="title" name="title" value="" placeholder="Title">
        </div>
        <div class="form-control">
          <input type="text" id="slug" name="slug" value="" placeholder="Slug">
        </div>
        <div class="form-control">
          <input type="file" name="image" placeholder="Image upload">
        </div>
        <div style="margin: 0 0 20px;">
          <textarea name="body" id="summernote"></textarea>
        </div>
      </div>
      <div class="col-12">
        <input type="submit" name="btnSubmit" class="btn-primary" value="Save Post" />
      </div>
    </div>
  </form>
  <script>
    document.forms[0].addEventListener("input", syncData);

    function syncData(e) {
      const form = e.currentTarget;
      const active = e.target;
      const fields = form.elements;
      let txt;
      if (active.type === 'text') {
        txt = active.value.toLowerCase().replace(/\s+/g, '-');
        console.log(txt);
        active.title = txt;
        fields.title.value = txt;
        fields.slug.value = txt;
      }
    }
  </script>
</body>

</html>


来源:https://stackoverflow.com/questions/54346959/how-to-set-value-of-one-input-field-based-on-another-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!