i'm sorry if this question is answered already but i don't find it in the search. :-)
I'm trying to access a li text value to set an id for this. I tried the following.
Below my jquery code
$(document).ready(function() {
$("#hinzubutton").click(function(){
$("#MyUL").append('<li> </li>');
$("li").append(Eingabe.value).attr("id", "Eingabe");
console.log($(Eingabe).text());
});
this is the body of my HTML Code (jquery file in the head)
<body>
<h1> Das ist eine Überschrift!</h1>
<ul id="MyUL">
</ul>
<input type="text" id="Eingabe">
<button id="hinzubutton"> Hinzu </button>
<button id="loeschbutton"> Löschen </button>
<script src="/js/test.js"> </script>
</body>
the console.log shows me my entered value correctly but i can't figure out how to get the value to set an own id. Is this possible?
If i check the Code on my Browser it looks like this after add an value with the inputfield for example input is 1.
<li id="Eingabe">
::marker
"1" (i want to set an id here if its possible)
" "
</li>
Thanks a lot.
I tried to access the value text but i cant append an id. My first try was to set the .attr("id", "li1") but it doesn't work for me.
CodePudding user response:
Try using jQuery appendTo because then you can set the text and any other attributes you want before finally appending it to your list:
$("<li></li>").text(Eingabe.value).appendTo("#MyUL");
Snippet
$("#hinzubutton").click(function() {
$("<li></li>").text(Eingabe.value).appendTo("#MyUL");
debug.innerHTML = MyUL.outerHTML;
});
<ul id="MyUL"></ul>
<input type="text" id="Eingabe">
<button id="hinzubutton"> Hinzu </button>
<button id="loeschbutton"> Löschen </button>
<hr>
HTML:
<xmp id="debug"></xmp>
<!-- the xmp tag is depreciated, but still useful for debugging -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CodePudding user response:
Thanks for you answer, unfortunately i'm not able to set a id for my input value. I try it this way
$(document).ready(function() {
$("#hinzubutton").click(function(){
$("<li></li>").text(Eingabe.value).attr("id", "testid").appendTo("#MyUL");
});
But this still set my id on my li tag not on the value. It looks like
<li id="testid">
::marker
"1" (is it possible to set the id for this value? or can i set it only for my li tag)
</li>
The Problem is i want to input a todo task but append an delete and edit button. (I have a working project but without jquery only javascript) but if i want to edit the input i can edit the whole li tag inclue the buttons.
I thought this is the right way to solve my problem to edit only the input value.
I use contenteditable for this and this allows the user to edit the whole li tag.