alert when user attempts to enter key into textbox - javascript

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');
});

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>

How can I set focus on an element in an HTML form using JavaScript?

I have a web form with a text box in it. How do I go about setting focus to the text box by default?
Something like this:
<body onload='setFocusToTextBox()'>
so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.
<script>
function setFocusToTextBox(){
//What to do here
}
</script>
Do this.
If your element is something like this..
<input type="text" id="mytext"/>
Your script would be
<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>
For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. Works even on IE as of version 10.
<input name="myinput" value="whatever" autofocus />
Usually when we focus on a textbox, we should also scroll into view
function setFocusToTextBox(){
var textbox = document.getElementById("yourtextbox");
textbox.focus();
textbox.scrollIntoView();
}
Check if it helps.
If your code is:
<input type="text" id="mytext"/>
And If you are using JQuery, You can use this too:
<script>
function setFocusToTextBox(){
$("#mytext").focus();
}
</script>
Keep in mind that you must draw the input first $(document).ready()
For plain Javascript, try the following:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
I used to just use this:
<html>
<head>
<script type="text/javascript">
function focusFieldOne() {
document.FormName.FieldName.focus();
}
</script>
</head>
<body onLoad="focusFieldOne();">
<form name="FormName">
Field <input type="text" name="FieldName">
</form>
</body>
</html>
That said, you can just use the autofocus attribute in HTML 5.
Please note: I wanted to update this old thread showing the example asked plus the newer, easier update for those still reading this. ;)
As mentioned earlier, document.forms works too.
function setFocusToTextBox( _element ) {
document.forms[ 'myFormName' ].elements[ _element ].focus();
}
setFocusToTextBox( 0 );
// sets focus on first element of the form
window.onload is to put focus initially
onblur is to put focus while you click outside of the textarea,or avoid text area
blur
<textarea id="focus"></textarea>
<script>
var mytexarea=document.getElementById("focus");
window.onload=function()
{
mytexarea.focus();
}
</script>
If your <input> or <textarea> has attribute id=mytext then use
mytext.focus();
function setFocusToTextBox() {
mytext.focus();
}
<body onload='setFocusToTextBox()'>
<form>
<input type="text" id="mytext"/>
</form>
</body>
this example worked for me
$(document).ready(function () {
document.getElementById('TextBox').focus();
}
Try This:
$('.modal').on('shown.bs.modal', function () {
setTimeout(function() {
$("input#yourFieldId").addClass('modal-primary-focus').focus();
},
500);
});
Thought of sharing some edge cases for this subject.
If your content is reloading (example dynamic DOM loading results from API and setting focus on first item of results) adding attribute autofocus will not be your solution, it works only on first load, second DOM change will not work but works fine in static DOM or single page load. If you have Dynamic component loading data simple .focus() will fail due to triggering focus on element not created yet by the time focus() is or blur not complete yet by DOM. For this case expected is to add delay time (setTimeout function) to give a time for focus to apply to new created or recreated element in DOM. My case was to load data from API and get focus on first result.
Adding var el = document.getElementById(focusId); el.focus(); solved the issue so DOM completes blur without adding delay.
<input type="text" class="word"> //html code
let theinput = document.querySelector(".word"); //Get the input
theinput.focus(); // focus on input

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(););
}

JavaScript: Clear search-field when enter with mouse?

I have a textfield () in my homepage for a searchstring.
Normaly I have a text like "enter here to searach..." in it.
Now I will clear the box from the text when a user click into it.
How to solve?
JavaScript?
This can be done by using the placeholder attribute in HTML. Example:
<input type="text" placeholder="e.g. John Doe">
For browsers who don’t support this attribute natively, you could use JavaScript.
If you’re using jQuery, you could consider using my placeholder plugin for jQuery, which is the most robust solution I’ve seen. Here’s a demo page: http://mathiasbynens.be/demo/placeholder
create a JavaScript file or use a current one then write in it:
Function function_name()
{
document.getEelementByName("Control_Name").setAttribute("Value", '');
}
then in the page head:
<script id="js1" type="text/javascript" src="dir/file_name.js"></script>
The Control Tag become:
<input type="text" name="Control_Name" onClick="return js1/function_name();" />
Yes you need javascript to achieve this. You could subscribe for the onclick event and when this event is triggered set the text to empty and then unsubscribe from the onclick event to avoid clearing the text every time a user clicks:
var foo = document.getElementById('foo');
foo.onfocus = function() {
foo.value = '';
foo.onfocus = null;
};
Live demo.
And if you are using jquery there is a really nice watermark plugin which allows you to do this.
I would suggest writing an onfocus Javascript handler; that will be triggered whether you’ve clicked it or tabbed into it.
<input type="text" name="..." value="" onfocus="this.value = '';" />
You can use onfocus and onblur javascript methods
<input type="text" name="searchinput" onblur="this.value='enter here to search...';" onfocus="this.value = '';" />

How to get the new value of an HTML input after a keypress has modified it?

I have an HTML input box
<input type="text" id="foo" value="bar">
I've attached a handler for the 'keyup' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be!
I've tried picking up 'keypress' and 'change' events, same problem.
I'm sure this is simple to solve, but at present I think the only solution is for me to use a short timeout to trigger some code a few milliseconds in the future!
Is there anyway to obtain the current value during those events?
EDIT: looks like I had a caching problem with my js file as I checked the same code later on and it worked just fine. I would delete the question, but not sure if that loses rep for the kind folk who posted ideas :)
Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:
function showMe(e) {
// i am spammy!
alert(e.value);
}
....
<input type="text" id="foo" value="bar" onkeyup="showMe(this)" />
To give a modern approach to this question. This works well, including Ctrl+v. GlobalEventHandlers.oninput.
var onChange = function(evt) {
console.info(this.value);
// or
console.info(evt.target.value);
};
var input = document.getElementById('some-id');
input.addEventListener('input', onChange, false);
There are two kinds of input value: field's property and field's html attribute.
If you use keyup event and field.value you shuld get current value of the field.
It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).
<html>
<head>
<script>
function callme(field) {
alert("field:" + field.value);
}
</script>
</head>
<body>
<form name="f1">
<input type="text" onkeyup="callme(this);" name="text1">
</form>
</body>
</html>
It looks like you can use the onkeyup to get the new value of the HTML input control. Hope it helps.
Here is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers.
As you will see from the table, the keypress and change event do not have uniform support whereas the keyup event does.
Also make sure you attach the event handler using a cross-browser-compatible method...
You can try this code (requires jQuery):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#foo').keyup(function(e) {
var v = $('#foo').val();
$('#debug').val(v);
})
});
</script>
</head>
<body>
<form>
<input type="text" id="foo" value="bar"><br>
<textarea id="debug"></textarea>
</form>
</body>
</html>

Categories

Resources