Search code examples
jqueryarrayscustom-data-attribute

How to insert a new value into a data-attribute array via text input which is wrapped by square bracket?


I have an element contain array like the code below
<div class="home_team" data-home='["10","20","30"]'></div>

When I enter value from input below, I want the value to be inserted into the array above.
<input type="text" /><button class="update_home_timeline">update</button>\

I manage to insert the value (let's say I entered 100) but some how it remove the square bracket and semi-colon around each of the data in the array and become like code below
<div class="home_team" data-home="10,20,30100"></div>

The JS

   $('.update_home_timeline').on('click', function () {
        newInput = $(this).prev().val();
        $('.home_team').attr('data-home', dataHome + newInput);
    });

How to make it not to remove the square bracket and semi colon like the code sample below?
<div class="home_team" data-home='["10","20","30","100"]'></div>


Solution

  • var arr = [];
    var total = [];
    $('.update_home_timeline').on('click', function() {
      arr = [];
      newInput = $(this).prev().val();
      var str = $('.home_team').attr('data-home')
      var res = str.split(",");
      arr.push(newInput);
      var total = res.concat(arr);
        var x = total.toString();
      $('.home_team').attr('data-home', x);
      console.log('updated-data-in-element-data-home', $('.home_team').attr('data-home'))
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="home_team" data-home="10,20,30,100"></div>
    <input type="text" /><button class="update_home_timeline">update</button>

    You can do it like this. Did a fiddle for you: https://jsfiddle.net/bogatyr77/h9rktxuz/21/