I would like to make a li inputable after the page being execute. I want the li function close to word office format. I mean, when we write on first list then ENTER it, it would focus on second list and ect. and this is my code I've made before:
<div class="writeform">
<label class="subtitle">ingredients</label>
<ol>
<li><input class="formxyz globalwrite" id="ingred" name="ingred" placeholder="ingredients"></input>
</li>
</ol>
</div>
and this is the script in ajax
$('input#ingred').on('keydown',function(e){
if(e.which == 13) {
$('ol').append('<li><input class="formxyz globalwrite" id="ingred" name="ingred" placeholder="ingredients"></input></li>');
$('input#ingred').focus();
}
});
when I run this code, and write in the 1st line then I press ENTER, the second li shows up. But when I write in 2nd li and press enter, nothing appended. How can I make this append function work continously when I press ENTER key?
You cannot have duplicate uses of ID values - it is not valid HTML, and your selector for the input element would not work properly. The same thing would be true with using a class, even though it is valid to have multiple uses of a class, the selection would select all matching elements. You would need to generate a unique ID, or use a different selector to select the last input element, such as the jquery .last() selector.
If there are two ID selectors of the same name , jQuery only select the first one.
You should bind the keydown event using delegation method, like this:
Change this:
$('input#ingred').on('keydown',function(e) {
Into this:
$(document.body).on('keydown','input#ingred',function(e) {
Because the first syntax will not bind to elements which are created later (dynamically).
UPDATE
For more correct way, you should make it bind to class or name attribute rather than id, because id id originally for naming elements and should be unique.
I think this is what you need in correct way: :D
$(document.body).on('keydown','input.formxyz',function(e) {
or:
$(document.body).on('keydown','input[name="ingred"]',function(e) {
Good luck!