Create a new line when user presses "Enter" key (HTML & Javascript) - javascript

I'm creating a Chrome Extension such that the user can create a todo list. I want to make it so that once a user types out a task, the user can press the "Enter" key to submit it. This will cause the task to go down to the next line. I'm having trouble allowing the user to make the task go onto the next line.
HTML:
<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
<li>test</li>
</ul>
Javascript:
$(() => {
$('#newtask').on('keydown', (e) => {
if(e.keyCode == 13){
???
}
});
});

Attach keypress eventlistener to input element, not to ul. If the key pressed is enter, get the content of input element, create new li element and set it's text with the inputted value, append to ul and then clear the input element.
$(() => {
$('input').on('keypress', function(e) {
if (e.keyCode == 13) {
const newTask = $(this).val();
if (newTask) {
$('#tasksUL').append(`<li>${newTask}</li>`);
$(this).val("");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
<li>test</li>
</ul>

With vanilla javascript you just add an eventListener to the actual input element
listening for keydown events.
let tasks = document.getElementById('tasksUL');
document.getElementById('newtask').addEventListener('keydown', (e) => {
if(e.key == 'Enter'){
let new_item = document.createElement('li');
new_item.innerText = e.target.value;
tasks.appendChild(new_item);
}
});

I think you want your list to contain the text entered by user? You can use the jQuery append method to achieve that.
$('#newtask').keydown(function(e){
if (e.which == 13) {
//Construct some html to append:
var newLi = "<li>" + $('#newtask').val() + "</li>";
$('#tasksUL').append(newLi);
}
});
Try my JS Fiddle implementation

Related

How to manipulate list element on Enter key press

I want to allow the editing of an ordered list using contenteditable.
When the user changes or adds in a new element in the list I want to be able to manipulate the text (e.g. wrap in span tag, replace text etc).
I've created a listener for the Enter key and can get the last list element value.
I've tried to change this and replace with the new value. However this populates the new list element created on the enter press.
<div>
<ol contenteditable=true class="editor">
<li><br></li>
</ol>
</div>
$('.editor' ).on('keydown .editable', function(e){
if ( e.keyCode === 13 ) {
var insertText = "<span>"+e.target.lastElementChild.innerText+"</span>";
e.target.lastElementChild.innerHTML = insertText;
return true
}
});
What is the best way to implement this functionality for new entries anywhere in the list not just the end? Open to Jquery solutions
example jsfiddle
You could use a MutationObserver to detect when a child is added to your list, and then update the previousSibling to wrap it in a <span>:
function subscriber(mutations) {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
const prev = node.previousSibling;
if (prev) {
prev.innerHTML = `<span>${prev.innerHTML.replace(/<br>$/, '')}</span>`;
}
});
});
}
const observer = new MutationObserver(subscriber);
observer.observe(document.querySelector('ol[contenteditable]'), { childList: true });
.editor span::after {
content: '😀';
}
<ol contenteditable class="editor">
<li>First li</li>
</ol>
You could bind your logic to the last li, and perform your logic from the events it emits.
$('.editor .last-item')
.on('click', function(e){
// clear out the html so the user can just type
e.target.innerHTML = '';
})
.on('keydown', function(e){
if (e.keyCode === 13) {
// ignore the enter key so it doesn't insert a new like
e.preventDefault();
// create the new li before the last one
$('<li>'+ e.target.innerHTML.trim() +'</li>').insertBefore(e.target);
// clear out the html so the user can keep entering items
e.target.innerHTML = '';
}
})
.on('blur', function(e){
// if the user leaves the field, change it back to the instructional text
e.target.innerHTML = 'Click to enter New List Item';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<ol class="editor">
<li class="last-item" contenteditable=true>Click to enter New List Item</li>
</ol>
</div>
Instead of taking action when an edit happens, you could set an interval that will modify the html of the li elements as desired.
setInterval(function(){
$('.editor' ).find('li').each(function(){
if ($(this).html().indexOf('span')==-1){
$(this).html('<span>' + $(this).html() + '</span>');
}
});
}, 200);
hello you might wanna check this let me give you a heads up. instead of using the
lastchild.innerHTML
replace it with
nextSibling.innerHTML
like this
$('.editor' ).on('keydown .editable', function(e){
if ( e.keyCode === 13 ) {
var insertText = "<span>"+e.target.lastElementChild.innerText+"</span>";
e.target.nextSibling.innerHTML = insertText;
return true
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<ol contenteditable=true class="editor">
<li><br></li>
</ol>
</div>
$('.editor' ).on('keydown .editable', function(e){
if ( e.keyCode === 13 ) {
var insertText = "<span>"+e.target.lastElementChild.innerText+"</span>";
e.target.nextSibling.innerHTML = insertText;
return true
}
});

Change variable from input field

I've been learning some jQuery and using w3schools. My intention is to allow the user to bind any key on their keyboard to the currently hardcoded key. I tried creating a variable and having that changed based on the input of the text field to change the keycode but haven't had any luck (Just like how you see in some games when they allow you to map a key to another). I was researching on w3schools and I believe I could use switch case, but I believe that would be too long and not tidy?
Here is what I have so far. (Alert doesn't seem to work here, going to the actual JSFiddle via the hyperlink works though)
$('input').bind("binding", function(e) {
alert("Backspace"); //Pop up to see
});
$('input').keyup(function(e) {
if (e.keyCode == 8) { // 8 = backspace
$(this).trigger("binding"); //will allow the message to be displayed
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try it here <input type="text"> Change the input <input class type="text">
Any suggestions are grateful. Thank you
You can try this for binding one key to backspace. It takes input from the first input element and the key pressed is then bounded to the backspace and only that key will function as a backspace key
$('#try').bind("binding", function(e) {
alert("Backspace"); //Pop up to see
});
var a;
$('#change').keyup(function(e) {
a = e.keyCode;
$(this).prop('disabled', true);
});
$('#try').keyup(function(e) {
if (e.keyCode == a) {
$(this).trigger("binding"); //will allow the message to be displayed
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Press the key you want to bind to backspace <input type="text" id="change"><br> Change the input <input id="try" type="text">
By default the binded key will be Backspace. You can change the key by typing something in the first input. It will take only one character.
Then when that key is input in the second input field the message will be triggered.
Explanation:
The keycode of the key entered in the first input is saved in the key_code variable and used later on in the other key_up event to check whether it matches
var key_code = 8
$('#changekey').keyup("input", function(e) {
key_code = e.keyCode;
});
$('input').on("binding", function(e) {
alert("Backspace"); //Pop up to see
});
$('#text').keyup(function(e) {
if (e.keyCode == key_code) //8 = backspace
{
$(this).trigger("binding"); //will allow the message to be displayed
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try it here <input type="text" id="changekey" maxlength = 1 > Change the input <input class type="text" id="text">

Calling a function when enter key is pressed with JavaScript

I am using addEventListener to bind an event to a node. The addEventListener adds addItem function to node. But when I press enter the function is not running.
Here is the JavaScript:
document.getElementById('add-item').addEventListener('keypress', function (e) {
if (e.keyCode == 13) {
addItem();
}
}, false);
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
//1. Empty the Input field once the item
document.getElementsByTagName('input')[0].value = '';
}
Here is the HTML:
<li class='todo-new'>
<input id='new-item-text' type='text'/>
<a id='add-item' href='#'>+</a>
</li>
On other hand the function runs with click
document.getElementById('add-item').addEventListener('click', addItem, false);
I want to do this with JavaScript only not using jQuery library.
Edited:
I want to attach the event to input field.
I'm willing to place a bet that the add-item element isn't in focus when you press enter. Instead, try changing the trigger to be the input field.
document.getElementById('new-item-text').addEventListener('keypress', function (e) {
if (e.keyCode == 13) {
addItem();
}
}, false);

Lock tab key with javascript?

How to lock or disable and again the tab key with javascript?
$(document).keydown(function(objEvent) {
if (objEvent.keyCode == 9) { //tab pressed
objEvent.preventDefault(); // stops its action
}
})
You can do it like this:
$(":input, a").attr("tabindex", "-1");
That will disable getting focus with tab in all links and form elements.
Hope this helps
Expanding on Naftali aka Neal's answer, here's how you'd do it with vanilla JS and both start and stop Tab behavior buttons:
let stopTabFunction = function(e) {
if (e.keyCode == 9) {
e.preventDefault();
}
};
document.getElementById('stopTabButton').onclick = function() {
document.addEventListener('keydown', stopTabFunction);
};
document.getElementById('resumeTabButton').onclick = function() {
document.removeEventListener('keydown', stopTabFunction);
};
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<br/><br/>
<input type="button" id="stopTabButton" value="Stop Tab!"/>
<input type="button" id="resumeTabButton" value="Resume Tab!"/>
Note that this also works for Shift + Tab (reverse direction).
JSFiddle
However, in my case, I wanted slightly different behavior: I wanted to basically lock down Tab focus to a single div. To do this, I placed a div before and after it, gave them both tabindex="0" (document-defined tab order on the div's themselves), to make the outer edges of the div focusable, like so:
<div id="beforeMyDiv"></div>
<div id="myDiv">
<!-- Only want Tab indexing to occur in here! -->
</div>
<div id="afterMyDiv"></div>
Then, I changed the function from earlier to this:
//Get the div's into variables etc.
//...
let forceTabFocusFunction = function (e) {
if (e.keyCode == 9) {
//Force focus onto the div.
if (!myDiv.contains(document.activeElement)) {
if (e.shiftKey) {
afterMyDiv.focus();
} else {
beforeMyDiv.focus();
}
}
}
};
That did the trick nicely.
On Neal answer, I'd only add:
if (objEvent.keyCode == 9) { //tab pressed
return;
}
Because when you finish typing CPF and press TAB, it counts as a character and changes to CNPJ mask.
Complete code:
<script type="text/javascript">
$(document).ready(function() {
$("#cpfcnpj").keydown(function(objEvent){
if (objEvent.keyCode == 9) { //tab pressed
return;
}
try {
$("#cpfcnpj").unmask();
} catch (e) {}
var size= $("#cpfcnpj").val().length;
if(size < 11){
$("#cpfcnpj").mask("999.999.999-99");
} else {
$("#cpfcnpj").mask("99.999.999/9999-99");
}
});
});
</script>

How to press a button with Enter Key

How to bind click(from Button1's click event) event in textbox When I pressed the enter key
$('#idoftextbox').keypress(function (e) {
var code = e.keyCode || e.which;
if (code === 13) {
//enter has been pressed
};
});
<input type="text" name="textbox" id="textbox" />
$("#textbox").bind('keypress', function(e)
{
if(e.which == 13)
{
// enter key was hit, do what you need to do here
}
});
Since you didn't say what "textbox" means to you (as it can be textarea too), I assumed some dummy markup that I posted and then I bound the event to it.
I don't see the reason for binding an event to click and then bind event after that to the element.

Categories

Resources