How to delete input field if I click on button?

1.8k views Asked by At

I have a form with an input field that works in this way:

If someone write something and then click on the "add" button near the input field, that "something" is added to a list of elements below.

<input type="text" name="_element" placeholder='Type something' @change=${this.onPropChange} required>
<button type="button" name="element" @click=${this.onChange}>Add</button>

List of elements:

<div>
   ${this.value.elements && this.value.elements.map((element) => {
        return html`
                  <li>
                    <span class="label" style = "font-weight: bold;">Element: </span>
                    <span>${element}</span>
                  </li>
        ` 
     })
   } 
</div>

onChange function:

onChange(e) {
        
        switch (e.target.getAttribute('name')){
            case '_element':
            this._element = e.target.value;
            break;
            case 'element':

              this.value = {...this.value, elements: [...this.value.elements||'']};
              this.value.elements.push(this._element);
              this._element='';
                         
            break;
   }
}

I'd like that when someone click on "add" button, the "something" written in the input field is cleared. I can't use submit button or input type = submit".

Does it exist a way to do it?

Thanks in advance!

1

There are 1 answers

3
Maxeezy On

You could extend your onChange function to find the input field and set its placeholder value to '' empty string each time you hit the button.

Set an id into your input tag like:

<input id='input_field' type="text" name="_element" placeholder='Type something' @change=${this.onPropChange} required>

Extending your onChange function like this might help, if I got you right:

const element = document.getElementById('input_field');
element.value = '';