Get info and change with javascript

javascript change text on page
innerhtml javascript
onclick javascript
javascript change text in div
javascript innertext
javascript get element by class
javascript innerhtml append
innerhtml jquery

I have a problem. I have object name: 'Коля', age: 30, I need to create ul where this info will be. After that I need to edit this information onclcik. On edit (span) I want to create one input and one button. Input should have this information name and age. Currently I am getting it After I get it, I should have an option to change it. So when I click on the change button, it should save my changes and this should be for each line of li.

var products = [
	{name: 'Коля', age: 30},
	{name: 'Вася', age: 40},
	{name: 'Петя', age: 50},
];

var ul = document.createElement("ul");

for( var i = 0; i < products.length; i++ ){
	var li = document.createElement("li");
	var span = document.createElement("span");
	span.innerHTML = products[i].name + " " + products[i].age + " " + "Edit";
	span.classList.add("newClass");

	li.addEventListener("click", editInfo);
	li.appendChild(span);
	ul.appendChild(li);
	document.body.appendChild(ul);
}

	var inputAge = document.createElement("input");

function editInfo(){
	var button = document.createElement("button");
	button.innerHTML = "Change";

	inputAge.value = this.children.innerHTML;

	document.body.appendChild(inputAge);
	document.body.appendChild(button);

}

Here's one example of how to do what you need.

I've added comment in detail.

If I've misunderstood your question or any question, please let me know.

// preparation
var products = [
    { name: 'Коля', age: 30 },
    { name: 'Вася', age: 40 },
    { name: 'Петя', age: 50 },
];

var ul = document.createElement("ul");
document.body.appendChild(ul);

var inputAge = document.createElement("input");
// set input type as number
inputAge.setAttribute("type", "number");
var button = document.createElement("button");
button.innerHTML = "Change";
inputAge.style.display = "none";
button.style.display = "none";

document.body.appendChild(inputAge);
document.body.appendChild(button);
// preparation done

// set products to li
for (var i = 0; i < products.length; i++) {

    var li = document.createElement("li");
    setContent(li, products[i])
    ul.appendChild(li);
}

// function to set one li's content
function setContent(el, obj) {
    // rebuild the span
    var span = document.createElement("span");
    span.innerHTML = obj.name + " " + obj.age + " " + "Edit";
    // bind edit event handler
    span.addEventListener("click", editInfo);
    // reset li's content
    el.innerHTML = '';
    el.appendChild(span);
}

// what edit do
function editInfo(e) {
    // retrieve name&age
    var arr = e.target.innerHTML.split(' ');
    var name = arr[0].trim();
    var age = parseInt(arr[1]);
    // set text value to input
    inputAge.value = age;
    // show input and change button
    inputAge.style.display = "block";
    button.style.display = "block";
    
    // set change button here for easily get name
    button.onclick = function() {
      setContent(e.target, {
          name: name,
          age: inputAge.value
    })
    // hide input and button
    inputAge.style.display = "none";
    button.style.display = "none";
};
}

HTML DOM innerHTML Property, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  In the search box, search for javascript.enabled Toggle the "javascript.enabled" preference (right-click and select "Toggle" or double-click the preference) to change the value from "false" to "true". Click on the "Reload current page" button of the web browser to refresh the page. 1.


Use Jquery for DOM Manipulation:

var products = [{
        name: 'Коля',
        age: 30
    },
    {
        name: 'Вася',
        age: 40
    },
    {
        name: 'Петя',
        age: 50
    }
];

loadList();

function loadList() {
    var listItem = '';

    for (var key in products) {
        listItem +=
            "<li onClick=editListData('" +
            products[key].name +
            "','" +
            products[key].age +
            "','" +
            key +
            "')>" +
            products[key].name +
            ' ,' +
            products[key].age +
            '</li>';
    }
    $('.userDataList').html(listItem);
}

function editListData(name, age, key) {
    var inputContainer = $('.inputContainer');
    var in_put = `<div>
                      <div class="form-group">
                        <label for="usr">Name:</label>
                    <input type="text" value='${name}' class="form-control" id="usr" name="usr">
                      </div><br/>
                      <div class="form-group">
                       <label for="age">Age:</label>
                  <input type="text" value='${age}' class="form-control" id="age" name="age">
                      </div><br/>
                      <button type="button" onClick="updateData('${key}')"class="btn btn-primary">Primary</button>
                       </div>`;
    inputContainer.html(in_put);
}

function updateData(key) {
    var name = $('#usr').val();
    var age = $('#age').val();
    products[key] = {
        name: name,
        age: age
    };
    loadList();
    $('.inputContainer').html('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myListData">
<ul class="userDataList"></ul>
</div>
<div class="inputContainer">
</div>

JavaScript DOM Document, getElementsByTagName(name), Find elements by tag name. document. element.attribute = new value, Change the attribute value of an HTML element. When the "Internet Options" window opens, select the Security tab. On the "Security" tab, select the Trusted sites zone and then click the Sites button. For the website(s) you would like to allow scripting, enter the address within the Add this website to the zone text box and click Add.


Knowing I'm late to the party,

I have used jQuery to achieve what you want.

Instead of manipulating the DOM to edit, the user edits the object in the background and then upon pressing Change button, the view gets updated.

I have used data-product-index to keep track of the index within the array on the element itself.


var products = [{
    name: 'Коля',
    age: 30
  },
  {
    name: 'Вася',
    age: 40
  },
  {
    name: 'Петя',
    age: 50
  },
];

showProducts();

function showProducts() {
  // Remove old #product UL if exists
  $('#products').remove();
  // Append UL
  $('body').append('<ul id="products"></ul>');
  // Iterate over products
  products.forEach((elem, i) => {
    // Using ES6 Template Literals
    $('ul').append(`<li><span data-product-index="${i}" onclick='editInfo(this);'>${elem.name} ${elem.age} Edit</span></li>`);
  });
}

function editInfo(elem) {
  // Remove old edit field
  $('#editField').remove();
  // Append an edit div
  $('body').append(`<div id="editField">Editing Item: ${$(elem).data('product-index')}<br>Name:<br><input type="text" id="editInputName"/><br>Age:<br><input type="number" id="editInputAge"/><br><button id="editButton">Change</button></div>`);

  $('button').on('click', (e) => {
    products[$(elem).data('product-index')].name = $('#editInputName').val();
    products[$(elem).data('product-index')].age = $('#editInputAge').val();

    console.log(products[$(elem).data('product-index')]);
    // Remove click event
    $('button').off('click');
    // Remove edit field
    $('#editField').remove();

    // Show updated object
    showProducts();
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JavaScript HTML DOM - Changing CSS, While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2020 by Refsnes Data. All Rights Reserved  A JavaScript handler can call preventDefault on that event to prevent the submission from happening. Form field elements do not have to be wrapped in <form> tags. When the user has selected a file from their local file system in a file picker field, the FileReader interface can be used to access the content of this file from a JavaScript program.


You dont need to add UL to the document each time.

document.body.appendChild(ul) - should be outside the for loop.

li.addEventListener("click", editInfo) - should be changed, also study about event loops concepts in javascript

Find the proper code below and write your own 'change' function.

var products = [
{name: 'Коля', age: 30},
{name: 'Вася', age: 40},
{name: 'Петя', age: 50},
];

var ul = document.createElement("ul");

for( var i = 0; i < products.length; i++ ){
var li = document.createElement("li");
var span1 = document.createElement("span");
var span2 = document.createElement("span");
span1.innerHTML = products[i].name + " " + products[i].age;
span2.innerHTML = " Edit";
span1.classList.add("newClass");

li.addEventListener("click", function(){return editInfo(this);});
li.appendChild(span1);
li.appendChild(span2);
ul.appendChild(li);
}

document.body.appendChild(ul);

var inputAge = document.createElement("input");

function editInfo(el){
var button = document.createElement("button");
button.innerHTML = "Change";
console.log(el)
inputAge.value = el.children[0].innerHTML;

document.body.appendChild(inputAge);
document.body.appendChild(button);

}

Using data attributes, The new data value; this can be any Javascript type except undefined . The object can be used directly to get data values (but note that property names originally A string is only converted to a number if doing so doesn't change its  Event: change. The change event triggers when the element has finished changing. For text inputs that means that the event occurs when it loses focus. For instance, while we are typing in the text field below – there’s no event.


.data(), To get the contents of the attribute data-id (like in <a data-id="123">link</a> ) you have to use If we want to retrieve or update these attributes using existing, native JavaScript, then we can this will change the data-id -> a2 setValue() also allows to suppress the change event. By default, using setValue() will lead to the same sitation as if the end user had manually modified the item value. So the browser will fire the change event, Dynamic Actions for that change event will be fired and their functionality will be executed.


How to get the data-id attribute?, Changes to raw JavaScript objects. When properties get added, changed, deleted. When arrays have elements spliced in and out of them. To change the content of an HTML element, use this syntax: document.getElementById( id ).innerHTML = new HTML This example changes the content of a <p> element:


Data-binding Revolutions with Object.observe(), Ideally, the JavaScript should be configurable without changing its code — so we define the user's ID in the class attribute, e.g. <div id="msglist"  The “integer property” term here means a string that can be converted to-and-from an integer without a change. So, “49” is an integer property name, because when it’s transformed to an integer number and back, it’s still the same.