简体   繁体   中英

set focus on input and change li background color

This function allows me to create new li elements and append it to my current todo list.

 var newListElement = "<li>" + '<input type="checkbox"/>' + "<label>" + '<input [type="text"] placeholder="Insert your new task here"/>' + "</label>" + '<div class="arrow-btn"></div>' + "</li>"; $("ul.todo-list").append(newListElement);

In this function I want to set the cursor to my input text field and want to change the background of the li element to grey when it is newly created. But whenever I am creating a new li element the color of the li element is not going to change nor can't i set the cursor automatically to the input field. Only if I am clicking manually with my mouse in the newly created input field on the li element the background of the li element is changing.

 //change last added list element to grey $('input:text').focus(function () { setEditModeItem($(this).closest('ul.todo-list > li')); });

My question is there a way to set the focus dynamically to a input field and check if it has focus?

You can trigger focus in jQuery by calling .focus() method on the selected element, I added CSS background red to highlight the input on focus, note that you can use Template literals to concatenate string, here is a working snippet:

 var newListElement = `<li> <input type="checkbox"/> <label> <input [type="text"] placeholder="Insert your new task here"/> </label> <div class="arrow-btn"></div> </li>`; $("ul.todo-list").append(newListElement); // this is how to trigger focus on input: $("ul.todo-list li:last-child").find("input").focus(); //change last added list element to grey $("input:text").focus(function () { //setEditModeItem($(this).closest('ul.todo-list > li')); });
 ul.todo-list input:focus { background-color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="todo-list"></ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM