0

I have a javascript where I can create list items in HTML. At the moment I can drag and remove the items with another script. Now I would like to store some information within every list item created, for an example a JSON-object. Then afterwards I save the data in the right order in the database.

Is it possible, or should I go another way?

4 Answers 4

1

As Nikhita says you can add values as data-values attributes to the list items. For example if you want to store the id and name atributes you can do as follow, and recover the values with jquery:

<li data-id="1" data-name="name" class="listItemClick"> List item </li>;
$(".listItemClick").click(function(){
     var id=  $(this).attr("data-id");
     var name = $(this).attr("data-name");
    //TODO

 });
Sign up to request clarification or add additional context in comments.

Comments

1

@Javier's answer works if you are using jQuery.

Those attributes can be accessed through regular Javascript as well.

// Make sure you have a valid reference
var el = getElementBySomeMeans();

// Set the value
el.setAttribute("data-test-this", "10");

// Get the value
var v = el.getAttribute("data-test-this");
console.log(v);

// Clear the attribute
el.removeAttribute("data-test-this");

I should mention, for completeness, that there is an HTML5 dataset method that also works on the data attributes, but I personally don't use it since we have to support older browsers at work.

IF you have the luxury, might be worth looking into.

Comments

0

1 - save data in html in any hidden div 2- add data in any unique attribute

Comments

0
<li data-name="' + data-value + '"> List item </li>;

This should do the trick. Append whatever data value and data name you see fit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.