OnClick on element populate an array with JS

javascript onclick push to array
javascript button onclick array
onclick javascript
how to take array input from user in javascript
how to store textbox value in array in javascript
push user input to array javascript
html input array javascript
store prompt input in array javascript

So, I have different elements like this:

<div data-action="change_status" data-date="2019-03-02" data-roomid="45" data-status="Close">Change status</div>
<div data-action="change_status" data-date="2019-03-02" data-roomid="46" data-status="Open">Change status</div>
<div data-action="change_status" data-date="2019-03-03" data-roomid="46" data-status="Close">Change status</div>
<div data-action="change_status" data-date="2019-03-03" data-roomid="47" data-status="Open">Change status</div>

For each click on element, I put the id of the element and some other informations in an array.

var arr = [];

$('[data-action="change_status"]').click(function(event) {
    $(this).data('status', 'newValue');

    arr.push({
        current_status: $(this).data('status'),
        current_date: $(this).data('date'),
        current_roomid: $(this).data('roomid')
    });
});

My problem is if the user click two times on the same element, it creates two rows in this array.

How can I check that an id already exists into the array and how can I update it with the last clicked value ?

Finally, I would like to pass this array in Ajax to a PHP page.

Thanks a lot.

We can easily do this using your roomid and Array.prototype.find

Array.prototype.find loops over the array and checks if any value is found. If so it returns the array item.

If you click change status it will say undefined the first time and the array entry the second and after.

var arr = [];

$('[data-action="change_status"]').click(function(event) {
    $(this).data('status', 'newValue');

    const arrElement = arr.find( (element) => {
      return element.current_roomid == $(this).data('roomid')
    });
    if (isInArray == undefined)
    {
      
      arr.push({
          current_status: $(this).data('status'),
          current_date: $(this).data('date'),
          current_roomid: $(this).data('roomid')
      });
    }
    else
    {
      //update
      arrElement["current_status"] = $(this).data('status');
      arrElement["current_date"] = $(this).data('date');
      arrElement["current_roomid"] = $(this).data('roomid');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-action="change_status" data-date="2019-03-02" data-roomid="45" data-status="Close">Change status</div>
<div data-action="change_status" data-date="2019-03-02" data-roomid="46" data-status="Open">Change status</div>
<div data-action="change_status" data-date="2019-03-03" data-roomid="46" data-status="Close">Change status</div>
<div data-action="change_status" data-date="2019-03-03" data-roomid="47" data-status="Open">Change status</div>

JavaScript array: Add items in a blank array and display the items , Write a JavaScript program to add items in an blank array and display the items. Sample Screen: add elements in an blank array. Sample� The array spread syntax allows you to expand an array or string and create a new array from the expanded elements. By using the array spread syntax, we avoid the need to use the fill method but we

This is simpler. Gather the data when you submit

$('[data-action="change_status"]').on("click", function(event) {
  $(this).data('status', 'newValue');
  $(this).text('newValue');
  $(this).toggleClass("newValue")
});

$("#send").on("click", function() {

  let changes = [];
  $('[data-status]').each(function() {
    if ($(this).data("status") === "newValue") changes.push({
      "id": $(this).data("roomid"),
      "date": $(this).data("date")
    })
  })
  console.log(changes)
});
.newValue {
  background-color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-action="change_status" data-date="2019-03-02" data-roomid="45" data-status="Close">Change status</div>
<div data-action="change_status" data-date="2019-03-02" data-roomid="46" data-status="Open">Change status</div>
<div data-action="change_status" data-date="2019-03-03" data-roomid="46" data-status="Close">Change status</div>
<div data-action="change_status" data-date="2019-03-03" data-roomid="47" data-status="Open">Change status</div>

<button type="button" id="send">Send</button>

onclick Event, 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� The property name is onclick. onClick even though being valid HTML, does not exist in JS as it is case-sensitive. Also you have to assign it a function reference or expression as David answered (+1).

you can try next stuff:

if (arr.filter(e => e.current_roomid === $(this).data('roomid')).length === 0) {
  arr.push({
     current_status: $(this).data('status'),
     current_date: $(this).data('date'),
     current_roomid: $(this).data('roomid')
   });
}

Attaching event handlers to dynamically created JavaScript elements, I've then looped through the array of links, attaching the an onclick event handler to each static item on the page,� Here Mudassar Ahmed Khan has explained with an example, how to dynamically populate DropDownList i.e. HTML Select element on Button click from JSON Array using JavaScript. The JSON Array will be read and parsed and then one by one the each JSON object from the JSON Array will be added as Items (Options) to DropDownList using plain JavaScript.

js populate a o on click Code Example, Get code examples like "js populate a o on click" instantly right from your google search results with the <button onclick="myFunction()">Click me</button>. 2. Adding Array Elements. The easiest way to add a new element to an array is using the The typeof operator returns object because a JavaScript array is an object.

javascript onclick event Code Example, How to insert an element after another element in JavaScript without using a library? How to insert an item into an array at a specific index JavaScript � how to � // Get the button, and when the user clicks on it, execute myFunction document.getElementById("myBtn").onclick = function() {myFunction()}; /* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */

Handling Checkboxes Onclick with JavaScript, JavaScript checkbox onclick examples. How to access to its onclick property: // get reference to element containing toppings checkboxes var el = document. Definition and Usage. The forEach() method calls a function once for each element in an array, in order.. Note: the function is not executed for array elements without values.

Comments
  • Have you tried with inArray ?
  • you can disable each parameter after a click.
  • You could avoid the problem by simply putting a class on the elements to be used in the array, but only actually create the array at the point it's going to be used - in your case when the AJAX request is sent.