Call a function with the enter key in all browsers - javascript

I’ve been trying to make the enter key call a function for a specific text field. Getting it to work with IE is no problem.
Chrome and Firefox are another story, they trigger another function. The code on the text box is:
<input name="Phone" type="text" onkeydown="if (event.keyCode==13 || event.keyDown==13 || event.charCode==13){get2();preventDefault();}">
The code for the function called instead is:
<script type="text/javascript">
$(function() {
$(".button").on("click",function(e) {
e.preventDefault();
location=this.id+".php?"+$('form[name="reportform"]').serialize();
});
});
</script>
I tried modifying that function to:
<script type="text/javascript">
$(function() {
$(".button").on("click",function(e) {
if (event.keyCode==13 || event.keyDown==13 || event.which==13){get2();e.preventDefault();
}else{
e.preventDefault();
location=this.id+".php?"+$('form[name="reportform"]').serialize();}
});
});
</script>
I even tried swapping that function out for:
<script type="text/javascript">
$('#reportform').submit(function(e){
get2();
e.preventDefault();
return false;
});
</script>
I found (keyCode, keyDown, charCode)==13 though numerous google searches and most of the functions on this site, but I have not been able to get it to work. Any insight would be appreciated.

I have tried similar approaches that you describe, for the task, but I have found a better way to deal with it. Simply use forms (and hide the submit button if desired).
<form onsubmit="myFunction();return false;">
<input type="text">
<input type="submit" style="display:none">
</form>
[Enter] key will then cause the form to be submitted, i.e your function to be invoked.
JSFiddle example

Related

Element.focus() doesn't work when called within a function handler for addEventListener()

Here is my code. For some reason, this code does not give focus to the textbox with the id "dude" even though the paragraph tag with id "answer" does get the key code of the button that I clicked. It is like the line with the focus() command gets completely ignored.
document.getElementById("thing").addEventListener("keypress", function() {
myFunction(event);
});
function myFunction(event) {
document.getElementById("answer").innerHTML = event.keyCode;
document.getElementById("dude").focus();
}
<!DOCTYPE html>
<html>
<body>
<input type="text" id="thing">
<input type="text" id="dude">
<p id="answer"></p>
</body>
</html>
However, if I were to make a slight modification and put the line with the focus() outside of the addEventListener(), then the focus() would work. For example, the following code works:
document.getElementById("dude").focus();
document.getElementById("thing").addEventListener("keypress", function() {
myFunction(event);
});
function myFunction(event) {
document.getElementById("answer").innerHTML = event.keyCode;
}
<!DOCTYPE html>
<html>
<body>
<input type="text" id="thing">
<input type="text" id="dude">
<p id="answer"></p>
</body>
</html>
The above code would actually start by giving the "dude" textbox focus.
Is there any reason for this and anything that I can do about this?
The keypress event handler fires too early - the user hasn't finished pressing the key down and entering in the value at that point, so the focus reverts to the initial input field. See how if you change the focus after a setTimeout it'll work:
document.getElementById("thing").addEventListener("keypress", function() {
myFunction(event);
});
function myFunction(event) {
document.getElementById("answer").innerHTML = event.keyCode;
setTimeout(() => document.getElementById("dude").focus());
}
<input type="text" id="thing">
<input type="text" id="dude">
<p id="answer"></p>
Or watch for the keyup event instead:
document.getElementById("thing").addEventListener("keyup", function() {
myFunction(event);
});
function myFunction(event) {
document.getElementById("answer").innerHTML = event.keyCode;
document.getElementById("dude").focus();
}
<input type="text" id="thing">
<input type="text" id="dude">
<p id="answer"></p>
For example, the following code works:
Not exactly, because with that code, you're focusing the dude input on pageload, rather than when the thing input has stuff typed into it.
You also should avoid using keypress in modern code, it's deprecated:
This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
Since this event has been deprecated, you should look to use beforeinput or keydown instead.
keyCode is too, technically, but the replacement for it - .code - isn't compatible everywhere.
Use the keyup event instead of keypress, because the default action of the keypress event sets the focus back to that input element.
document.getElementById("thing").addEventListener("keyup", function() {
myFunction(event);
});
function myFunction(event) {
document.getElementById("answer").innerHTML = event.keyCode;
document.getElementById("dude").focus();
}
<!DOCTYPE html>
<html>
<body>
<input type="text" id="thing">
<input type="text" id="dude">
<p id="answer"></p>
</body>
</html>
It seems like you are trying to shift focus from input "thing" to input "dude" after you complete a "keypress" or "keyup" on input "thing".
I don't understand the use case for this. But, IMO if you are trying to change the focus state after you input a value, I would recommend placing an event listener on the "change" event. You could simply press your "TAB" key on your keyboard after you are done inputting data into input "thing" and focus will be shifted to the input "dude" and the function will execute. Both achieved!
document.getElementById('thing').addEventListener('change', function (event) {
myFunction(event.target.value)
})
function myFunction(answer) {
document.getElementById('answer').innerText = answer
}
<input type="text" id="thing" />
<input type="text" id="dude" />
<p id="answer"></p>

Input with submit wont execute If/else statement

This looks very simple but I cant get it working. Im not experianced in web design but here is the following:
I am trying to make input bar(like search box) that when entered specific text it redirects you to other page or makes somethign else.
Here is what I have so far.
<!DOCTYPE html>
<html>
<body>
<form method="post">
<input id="search" type="text"/>
<button onclick="return abc()">test</button>
</form>
<script>
function abc() {
var textt = document.getElementById("search");
if (textt.value == "test") {
window.location.assign("http://www.google.com")
}
}
</script>
</body>
</html>
http://jsfiddle.net/uvnyd8vz/1/
this just refreshes page and thats it. Any ideas? thanks!
Compare the value as string
Like
textt.value =="test";
Also inside the function write
event.preventDefault();
This will stop the submit action of submit button
Also specify the else condition i.e.
else{return false;}
Adding event.preventDefault(); to function fixed my problem! thanks

jQuery how to get input from a form?

<script>
$(function() {
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
})
</script>
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name"><input type="submit" id="button">
</form>
</div>
Does not print name in console, what am I doing wrong here?
The problem right now is that the code you've written is executed immediately when the page loads.
From the way your code looks, it looks like you actually want the form's button to do the console log.
I've altered your code a bit, but here's how you'd:
Select the Form and the Input
Declare the variable out of the scope
Bind onto the form's submit event
Prevent it from actually submitting
And logging to console per your example
Altered code below:
<script>
$(function() {
// Save a reference to the input
var input = $("input[name=first_name]"),
// Get the form itself
form = $("form[name=info]"),
// Storage for your first_name outside of the scope
first_name = false;
// Bind to the submit event on the form
form.bind('submit', function() {
// Set the first_name to the input's value
first_name = input.val();
// Log it out (per your example)
console.log(first_name);
// Return false to prevent the form from posting
return false;
});
});
</script>
<div id="content">
<form name="info">
First Name:
<input type="text" id="first_name" name="first_name">
<input type="submit" id="button">
</form>
</div>
I'm not saying this is the best way to handle whatever you're attempting to do with the form, realistically you shouldn't need an ID on the button, and probably would want to replace the NAME on the form with an ID for the selector. Also using an ID selector to get the input would be recommended as well, as ID selectors are faster than [name=something] selectors. (Thanks gnarf for the comment!)
The variable scoping is also probably somewhat strange in your example, but the above code should be good for learning :)
The method as you've written it only runs once, after the page loads. At that point the input element doesn't contain a value (i.e. $("#first_name").text() == ''). You can bind the logging statement to the keyup event of the element, to see the text that's being entered into it.
$(function() {
// this code only runs once
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
$('#first_name').keyup(function() {
// this code fires everytime a key is released on the element
console.log($(this).val());
});
})
Demo on plnkr
Here is the JSFiddle for your code.
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name" value="something">
<input type="submit" id="button">
</form>
</div>
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val());
});
'Something' is the default value.' Try other words in the text box and you will see the new value in console.
As per your code, you are getting correct results.
Your defined function is never called because you have not attached any events to it.
I have modified your code and you can check it working here
$(document).ready(function(){
$("#first_name").focusout(function(){
var first_name = $(this).val();
alert(first_name);
});
});
$('#content form').on('submit', function () {
console.log(
$(this).find('input[name="first_name"]').val()
);
return false;
});
edit: you must run your jQuery selection after you have inputted something into the input field. Right now when you run it, it is empty
edit: try using this 'on' from the jQuery docs
http://api.jquery.com/on/
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val(););
}

alert when user attempts to enter key into textbox

So I've been searching for a bit now for code that will alert a user with a message (I know how to do an alert) when they try to enter any sort of text into a blank textbox.
Here is my code. What do I add to cause the sendMsg() function to be called?
<script>
function sendMsg()
{
alert ("change msg content here");
}
</script>
here is the HTML:
<body>
<input type="text" name="">
</body>
This might work:
<input type="text" name="foo" onKeyUp="sendMsg()" />
i.e. if I understood your question.
Cheers.
Use the onchange event.
<input type="text" name="" onchange="inputChanged();">
Have you tried giving your input an ID:
<input id="testing" type="text" name="" />
And then your javascript would be:
document.getElementById('testing').onfocus = function() {
// alert("change msg content here");
}
The first thing you'll need to do is attach an event listener to the focus event of the text box (which is triggered when you "focus" on a text box), to do that you'll need some way of locating it in the DOM. The simplest way to do that would be to add an id attribute like so:
<body>
<input type="text" name="" id="msgContent">
</body>
Now you can use the document.getElementById method to find the element:
var textBox = document.getElementById('msgContent');
Then you can attach an event listener:
textBox.addEventListener('focus', function () {
alert('change msg content here');
});
Keep in mind that the addEventListener method isn't available in some older versions of IE, instead there are other fallbacks which are detailed here.
Finally if you're using a library like jQuery, YUI, etc you normalize the browser differences for attaching event handlers:
//jQuery example
$('#msgContent').on('focus', function () {
alert('change msg content here');
});

jQuery prevent input default action

I have an ajax form I would like to prevent from preforming an action when submitted and have tried numerous methods and nothing works. My first method was:
return false;
and then I tried
event.preventDefault();
event being the callback name or whatever you call it.
function(event) {
event.preventDefault();
};
Heres the HTML I am using right now:
<form class="main_search" method="POST" action="ajaxsearch.php">
<input type="text" class="editable" placeholder="Search">
</form>
Heres the test javascript I set up:
$('.main_search').submit(function(event) {
event.preventDefault(console.log(event)); //Log the event if captured
});
Neither method works but the weird part is that they work on different things like buttons but they don't work on this one form. Am I missing something here? Thanks!
To deal with your specific problem (ie, inserting dynamically generated form), use $.on(). You're better off not using document.body as the parent observer (as $.live() essentially does) with $.on(), so the following would be appropriate (considering your actual markup):
<div id="searches">
<form class="main_search" method="POST" action="ajaxsearch.php">
<input type="text" class="editable" placeholder="Search">
</form>
</div>
var $main_search = $('.main_search'),
$searches = $('#searches');
$searches.on('submit', '.main_search', function(event) {
event.preventDefault();
console.log(event); //Log the event if captured
});
setInterval(function(){
$searches.append($main_search.clone());
}, 5000);
http://jsfiddle.net/5TVGn/2/
I set up a JSfiddle:
http://jsfiddle.net/XM679/
Could it be you forgot to wrap it into $(document).ready(function() {} ?
If this didn't solve the problem: Since the fiddle is working - we would need your context to help more.

Categories

Resources