I have a text box that takes input and when i hit enter it stores the output and displays in an unordered list format. The function without IIFE works when i use onclick event. However, with IIFE its not functioning. Please help.
<html>
<head>
<title>messagewithenter</title>
</head>
<body>
Message:
<input type="text" name="message" id="message">
<input type="submit" value="add" id="submitenter" style="display: none">
<ul id="list"></ul>
<script>
(function () {
var link = document.getElementById("submitenter");
link.addEventListener("click", function () {
document.onkeypress = enter;
function enter(e) {
if (e.which == 13 || e.keyCode == 13) {
addMessage();
}
}
});
function addMessage() {
var message = document.getElementById("message").value;
var output = "<li>" + message + "<li" + "<br>";
document.getElementById("list").innerHTML += output;
}
}());
</script>
</body>
</html>
You were binding the event on click event of an invisible element, simply make it
document.onkeypress = enter;
function enter(e) {
if (e.which == 13 || e.keyCode == 13) {
addMessage();
}
}
Demo
document.onkeypress = enter;
function enter(e) {
if (e.which == 13 || e.keyCode == 13) {
addMessage();
}
}
function addMessage() {
var message = document.getElementById("message").value;
var output = "<li>" + message + "<li" + "<br>";
document.getElementById("list").innerHTML += output;
}
Message:
<input type="text" name="message" id="message">
<input type="submit" value="add" id="submitenter" style="display: none">
<ul id="list"></ul>
link.addEventListener("click", function () {
document.onkeypress = enter;
...
This code is flawed because if it works, it would reset the document.onkeypress event handler every time you click in the input box.
It's also unnecessary, as you can set that onkeypress handler without needing the click event. The whole thing can be written like this:
document.onkeypress = function(e) {
if (e.which == 13 || e.keyCode == 13) {
addMessage();
}
}
No need for the click handler at all.
Related
I have multiple input fields that have the same class name, such as:
<input type="text" class="input-name" value="John">
<input type="text" class="input-name" value="Maria">
When someone presses ENTER in any field, the text !!! is automatically appended to the value. This works great.
$(document).on('keypress', '.input-name', function(event)
{
if (event.which != 13)
return;
$(this).val($(this).val() + '!!!');
});
The problem is that I'd like to press a button and change the value of all fields, by simulating the ENTER keypress event and for some reason, it only triggers in the first input!
This only triggers in the first input:
var e = $.Event('keypress', { which: 13 });
$('.input-name').trigger(e);
This also only triggers in the first input:
$('.input-name').each(function(i, input)
{
$(input).trigger(e);
});
You can see the problem in this JSFiddle.
Define jquery Event object inside the each function callback as follows.
$('.input-name').each(function (i, input) {
var e = $.Event('keypress', {
which: 13
});
$(input).trigger(e);
});
I would just make a function that does the work and not deal with event handlers
//function alterInps(inps) {
// inps.val(function () { return this.value + "!!!"; });
//}
function alterInps(inps) {
var re = /!!!$/;
inps.val(function () {
return this.value + (re.test(this.value) ? '' : '!!!');
});
}
$(document).on('keypress', '.input-name', function(event) {
if (event.which != 13) return;
alterInps($(this));
});
$('button').on("click", function () {
alterInps($('.input-name'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input-name" value="John">
<input type="text" class="input-name" value="Maria">
<button type="buton">All</button>
$('.input-name').on('keypress', function(event)
{
if (event.which != 13)
return;
$(this).val($(this).val() + '!!!');
});
$(document).on('click', '#btn-submit', function()
{
var e = $.Event('keypress', { which: 13 });
//$('.input-name').trigger(e);
$('.input-name').each(function(i, input)
{
$(input).trigger(e);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn-submit">
Click me
</button>
<input type="text" class="input-name" value="Maria">
<input type="text" class="input-name" value="John">
Pressing the enter button on the keyboard, the HTML button (id="botonCorregir") should be pressed automatically, but does nothing.
HTML:
<form id="theFormID" class="text-center">
<input autofocus id="respuestaUsuario" type="text">
<button id="botonCorregir" onclick="corregir()">Responder</button>
</form>
JAVASCRIPT:
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
</script>
<script>
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
For example if y try that, and push enter, doesn´t show alert "hello!". Why?
<script>
if (event.keyCode == 13) {
alert("hello!");
}
</script>
The usual way to do it in html/js is this one:
HTML
<form id="my-form">
<!-- creating a form, we use the on-submit event -->
<input type="text" autofocus id="respuestaUsuario" />
<button type="submit">Responder</button>
</form>
JS
// submit event runs when the user click the submit button or press enter on the input-text
document.getElementById('my-form').addEventListner('submit', evt => {
evt.preventDefault();
corregir();
});
Let me know if it's not clear enough and I'll try to explain it better.
the keyup event listener is for when you release the enter key
plus you can call the corregir function directly instead of triggering a click on the button
try :
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}
});
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
also, a submit would be more addapted to this situation since the submit triggers itself on enter if an element of it's form is selected
Try to call the function direktly without clicking the button.
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}
I'm trying to add a functionality to textarea which will add <br> tag to innerHTML of textarea when Enter is pressed.
Here is my codepen.
I've tried this with texareaElement.val(); but it adds directly to textarea, but it shouldn't be seen by user. It should be on the background.
function textAreaNewLine(element, event) {
// 13 is the keycode for "enter"
if (event.keyCode == 13) {
var elVal = element.val();
element.val(elVal + '<br>');
}
}
$('#ta').on('keypress', function(event) {
var el = $(this);
textAreaNewLine(el, event);
$('.main').html($('#ta').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="4" cols="50" id="ta"></textarea>
<div class="main"></div>
If I understand your question correctly, You can add an empty line like:
Introduce another variable
var emptyLine = "\n";
and then append this to the value.
Check the fiddle below
function textAreaNewLine(element, event) {
// 13 is the keycode for "enter"
if (event.keyCode == 13) {
var elVal = element.val();
var emptyLine = "\n";
element.val(elVal + emptyLine );
}
}
$('#ta').on('keypress', function(event) {
var el = $(this);
textAreaNewLine(el, event);
$('.main').html($('#ta').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="4" cols="50" id="ta"></textarea>
<div class="main"></div>
every time time when i pressed the enter key in input field then it should alert some thing but facing problem in doing that here is the code.
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)" onkeyup="ajxsrch(this.value)">
Here is the js code
<script>
function ajxsrch(str)
{
var keycod;
if(window.event)
{
keycod = str.getAscii();
}
if(keycod==13){alert("You pressed Enter");}
}
</script>
I think it is because you aren't passing e to the function and only using window.event which does not work in all browsers. Try this code instead.
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)">
<script>
function ajxsrch(e)
{
e = e||event;
var keycod;
if(e)
{
keycod = e.keyCode||e.which;
}
if(keycod==13){alert("You pressed Enter");}
}
document.getElementById("input").onkeyup=ajxsrch;
</script>
Try this..
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)" onkeyup="ajxsrch(event)">
<script>
function ajxsrch(e)
{
if (e.which === 13) {
alert("You pressed Enter");
}
return false;
}
</script>
Pass the event object to the function call
<input type="text" class="searchfld" id='input' onkeyup="ajxsrch(event)">
Use the event object in the JS and get the key value.
function ajxsrch(ev) {
var ch = ev.keyCode || ev.which || ev.charCode; // Proper way of getting the key value
if(ch == 13) {
alert("You pressed enter");
}
}
I have a mvc3 application. and on one page i have a textbox that will allow a user to search for a client, now i am struggling with some functionality, as i am a windows form and widows phone 8 developer. i want this text box i have here to execute as i press enter, i have a button that the user can click on to search, but i know most users just click enter! i am using JavaScript to hit function!
Html for button and textbox:
<td>
<input value="Search..." id="SearchText" style="color:GrayText" onchange="SearchText" onfocus="javascript:this.value=''" onblur="javascript: if(this.value==''){this.value='Search...';}" />
<input id="searchbutton" type="button" value="Search" class="button"/>
</td>
Here is the Javascript :
<script type="text/javascript">
$('#searchbutton').click(function(){
var client = document.getElementById('SearchText').value;
var textbox = document.getElementById('SearchText');
var edittext = ", is not available!";
var result = client + edittext;
if (textbox.value == 'Search...') {
alert('Please enter a Client Name to search for ');
textbox.focus();
}
else {
alert(result);
};
});
</script>
how would i get the textbox to also trigger the function as i hit enter on the textbox!
here is how it looks on the form :
very new to this kind of coding, any help will do!
thanks!
$('#searchbutton').click(search);
$('#SearchText').keypress(function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
search()
}
});
function search(){
var client = document.getElementById('SearchText').value;
var textbox = document.getElementById('SearchText');
var edittext = ", is not available!";
var result = client + edittext;
if (textbox.value == 'Search...') {
alert('Please enter a Client Name to search for ');
textbox.focus();
}
else {
alert(result);
};
}
$('#SearchText').on('keypress', function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//write your code for search here..like searchbutton on click
}
});
I dont know the exact answer to your question but you could use a tabindex
to press tab to jump to your button and then you can press enter to submit.
try this..
<input type="text" placeholder="Search" id="txtSearch" />
<input type="button" value="Search" id="btnsearch" onclick="return Search();" />
<script type="text/javascript">
$("#txtSearch").keyup(function (event) {
if (event.keyCode == 13) {
$("#btnsearch").click();
}
});
function Search(){
// do Something here.......
}
</script>