Home > Software engineering >  Edit specific input button based on user input, and save it with a separate button in vanilla JS
Edit specific input button based on user input, and save it with a separate button in vanilla JS

Time:05-03

I'm trying to make an input, it has its value from the beginning.
Then, when the user double click on a span, the cursor needs to be in input field and the user should be able to edit it.
Once edit is ready, he needs to press save button in order to save it, not just click outside of the input field(which is by default)

The second button will just delete, reset the name string, and then once again when you press save, it will save the empty string.

All that, will depend on which span the user is dblckicking, so the respective input of a respective span has to be accessed for edit.

I've done something like this for now..
But it's far to be ready. Would appreciate you're ideas.
I need to do it using vanilla JavaScript

var numberOfbuttons = document.querySelectorAll(".name").length;

for (i = 0; i < numberOfbuttons;   i) {
     
      document.querySelectorAll('.name')[i].ondblclick = function() {
      document.getElementById('in1').disabled = false;    
      document.getElementById('in1').value = 'hahmmm';
      };
      
}
<span id="spn1" >
   <input id="in1" type="text" disabled="true" value="Homer Simpson">
   <div >
      <button >save</button>
      <button >delete</button>
   </div>
</span>
<span id="spn2" >
   <input id="in2" type="text" disabled="true" value="Marge Simpson">
   <div >
      <button >save</button>
      <button >delete</button>
   </div>
</span>
<span id="spn3" >
   <input id="in3" type="text" disabled="true" value="Bart Simpson">
   <div >
      <button >save</button>
      <button >delete</button>
   </div>
</span>

CodePudding user response:

In order to make the correct input field editable, you must not work with the ID of the first input field in the loop. Here is a way to select the correct input field via the double-clicked span element:

document.querySelectorAll(".name").forEach(span => {
    span.ondblclick = function() {
        let input = span.querySelector("input");
        input.disabled = false;
        input.value = "hahmmm";
        input.focus();
        span.querySelector("button.check").onclick = function() {
            input.disabled = true;
        }
        span.querySelector("button.close").onclick = function() {
            if (input.disabled == false) {
                input.value = "";
                input.focus();
            }
        }
    }
});

I'm not quite sure what the save button is supposed to do. Right now it just disables the input field again, keeping the new value.

  • Related