Daniel Stakeley Daniel Stakeley - 18 days ago 6
jQuery Question

How to make changes to only one element with the same class

The project I am working on requires to added a new element and make changes to the element using a edit button. How can I target only element with same class and make changes to it without effecting the other elements with the same class?

CodePen example.

var $input = $("#change");
var $btn = $("#add");
var $btne = $("#edit");
var $content = $("#content");
$btne.hide();


$btn.click( function(){

var typedInfo = document.getElementById("change").value;
var item = $('<li></li>');
item.append(typedInfo);
$content.append(item);


$content.on("click","li", function(){
});

item.click(function(){
var clickedItem = $(this);
$btne.show();
item.text(" ");
var typeNew = $('<input type="text" id="newInput" value = "edit">')
typeNew.click( function(e){
e.stopPropagation();
});
item.append(typeNew);
$btne.click( function(){
var editedInput = document.getElementById("newInput").value;
clickedItem.text(editedInput);
$btne.hide();
});
});

});

Answer

First the id should be unique in the same document so you should replace the duplicate ones by class, e.g :

var typeNew = $('<input type="text" class="newInput" value = "edit">')

Using document.getElementById("newInput") will target all the elements with this id, Use e.target to target just the clicked one :

var editedInput = e.target.value;

Instead of :

var editedInput = document.getElementById("newInput").value;

You should pass the event e to the click :

$btne.click( function(e){
//____________________^
    var editedInput = e.target.value;
    clickedItem.text(editedInput);
    $btne.hide();
});

Hoep this helps.

var $input = $("#change");
var $btn = $("#add");
var $btne = $("#edit");
var $content = $("#content");

$btne.hide();

$btn.click( function(){
  var typedInfo = $("#change").val();
  var item = $('<li></li>');

  item.append(typedInfo);

  $content.append(item);
});

$content.on("click","li", function(){
  var clickedItem = $(this);
  var typeNew = $('<input type="text" class="newInput" value="'+clickedItem.text()+'">')
  $btne.show();

  $(this).html(typeNew);

  typeNew.click( function(e){
    e.stopPropagation();
  });
});

$btne.click( function(e){
  $($content).find('li>input').each(function(){
    $(this).parent().text($(this).val());
  })

  $(this).hide();
});
ul {
  display:flex;
  flex-direction:column;
}

li{
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="change" value="Type Here">
<button id="add">Add Button</button>
<button id="edit">Edit Button</button>

<ul id="content"></ul>

Comments