I am learning JavaScript and and am working on a To Do list type of application.
Idea: "Add" button is set to disabled in the HTML and only to be enabled when there is at least one character.
My code only works when there is at least 2 characters and can't workout why it doesn't detect the first character.
The other realted question is how do I set the "add" button back to disable if the input box content has been deleted.
HTML
<input id="addToListInput" onkeydown="buttonStatus()" value="" type="text"><input id="addToListButton" disabled type="submit" Value="Add to list" onClick="addToList(this)">
JS
function buttonStatus() {
var input = document.getElementById('addToListInput');
var submit= document.getElementById('addToListButton');
if (input.value.trim() ==""){
submit.disabled=true;
}else{
submit.disabled=false;
}
}
Use keyup instead. By using keydown you are detecting when the key is down, but the textbox value has not changed at that point...
<input id="addToListInput" onkeyup="buttonStatus()" value="" type="text">
onkeydown is fired before the input control is actually fired, if you use onkeyup it should work as you expect.
Related
I'm trying to figure out how to know when an input is clicked and when it is unclicked. Let me explain:
When ever you want to type something on an input field, you click on the input box and when you don't want to type, you click somewhere else and the input field is disabled.
<input type='text'>
Here as you can see, when you click on it, the field is enabled, and when you click somewhere else other than the field, it disables.
I just want to know when the field is disabled/unclicked.
When you click on the input field focus event is fired. When you lose focus blur event is fired.
var elem = document.getElementById("fname")
elem.addEventListener("blur", myFunction);
function myFunction() {
alert("Input field lost focus.");
}
<input type="text" id="fname">
I believe you're just looking for onFocus.
<input type='text' onFocus={/* do something */} />
Read more about React events here.
lets say we have two text boxes textbox1 and textbox2
I have my cursor inside textbox1 and I then press tab key. The cursor moves to textbox2. How can I control the tab key behavior in javascript or jQuery. What I want to do is the moment the textbox1 throws focus out event, I want to check for some condition (business condition) and based on it I want to allow the default tab key behavior or point the cursor to where I want to.
Can anybody guide me how we can do it?
What I am assuming is the below flow of event
: tab key press in textbox1-> textbox1 focusout event-> textbox2 selected. Basically I want some control after focusout event and before textbox2 selection. I earlier used jQuery focusout event but what it does is , it fires focusout event and also selects the textbox2 , defeating the purpose where I want to check for some condition before textbox2 is selected
first you need to find the Keycode tab
$( "#findKey" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
<input id="findKey" value="type something">
<div id="log"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Then you can set a click function then set condition
$(document).on('keydown', function(event){
if( event.which == 9){
alert("now you are clicked tab");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Or may be you need to change the tab order thats what you need you can use tabindex property
All elements (except hidden elements) in the HTML form are part of the form's tab order. When the user presses the Tab key, the browser shifts the input focus from element to element in order the elements appear in the HTML code. However, sometimes you want the tab order to flow a little differently. In that case, you can number the fields using tabindex attribute.
Have a look at the example:
<form>
Field 1 (first tab selection):
<input type="text" name="field1" tabindex=1 /><br />
Field 2 (third tab selection):
<input type="text" name="field2" tabindex=3 /><br />
Field 3 (second tab selection):
<input type="text" name="field3" tabindex=2 /><br />
</form>
The tabbing order begins with elements with explicit tabindex values, starting from the lowest to the highest numbers. Same-valued tags get tab-selected in the order in which they appear in the document. To exclude an element from the tab order, set the value of tabindex to 0. In that case the element is skipped when the user tabs around the form.
The tabindex attribute can also be used with <a> <textarea> <select> and elements.
please refer these links
https://msdn.microsoft.com/en-us/library/aa733550(v=vs.60).aspx
https://www.paciellogroup.com/blog/2014/08/using-the-tabindex-attribute/
In your question, you mention both pressing tab and "the moment textbox1 throws focusout event".
You can do this with blur event, check your condition and, if failed, refocus the control.
By adding a class, you can apply the same event to any control:
$(".required").blur(function(e) {
if ($(this).val() == "")
$(this).focus(); // or redirect to any other input
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='textbox1' class='required'>
<input id='textbox2' class='required'>
<input id='textbox3' class='notrequired'>
The scenario is that I have a modal with a multi-step process that I show one at a time, but not every step has a form field.
So when I'm ready to move on from Step 1 (which has a form field) and I click the next helper icon in the keyboard's toolbar (a function of iOS) it forwards me to an unavailable/translucent field in Step 4.
Step 1: Ask for age
Step 2: Choose a gender (these are LI elements)
Step 3: Choose interests (these are also LI elements)
Step 4: Enter a name
I've tried tabIndex, but that doesn't have any affect.
I'm not certain this is even possible since this is really an iOS control. If it's not possible can you hide that?
The undesirable fix would be to do a check when the user has focused on the Step 4 field and if the elements in Step 3 and Step 4 have not been chosen focus the user on the applicable previous step.
As far as I know,it's a same order of html structure.
So if you want to change the order, change html.
If you can't or You can't avoid the issue by changing the html file for some reason such as complicated html structure causing the issue or something.
Below code is how to disable <prev> <next> buttons of IOS keyboard.
html
<input type="text" />
<input type="number" />
<input type="date" />
<input type="time" />
<input type="tel" />
javascript(jquery)
$("input").on("touchstart",function(e){
_$activeElem = $(this);
//readonly disables next/prev buttons. so when user tap input field,turns any other input into readonly
//You cannot use focus here because keyboard shows up before focus fired,you need to use touchstart instead.
$("input").each(function(){
if($(this).get(0) === _$activeElem.get(0)){
_$activeElem.removeAttr("readonly");
$(this).one("blur",function(){
$(this).attr("readonly","readonly");
});
return;
}else{
$(this).attr("readonly","readonly");
}
});
//remove readonly property on blur
$("input").on("blur",function(){
if($("input:not([readonly])").length === -1){
$("input").removeAttr("readonly");
}
});
});
and make readonly input look like normal input field by CSS.
I am trying to do some experiment. What I want to happen is that everytime the user types in something in the textbox, it will be displayed in a dialog box. I used the onchange event property to make it happen but it doesn't work. I still need to press the submit button to make it work. I read about AJAX and I am thinking to learn about this. Do I still need AJAX to make it work or is simple JavaScript enough? Please help.
index.php
<script type="text/javascript" src="javascript.js"> </script>
<form action="index.php" method="get">
Integer 1: <input type="text" id="num1" name="num1" onchange="checkInput('num1');" /> <br />
Integer 2: <input type="text" id="num2" name="num2" onchange="checkInput('num2');" /> <br />
<input type="submit" value="Compute" />
</form>
javascript.js
function checkInput(textbox) {
var textInput = document.getElementById(textbox).value;
alert(textInput);
}
onchange is only triggered when the control is blurred. Try onkeypress instead.
Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.
For static and dynamic inputs:
$(document).on('input', '.my-class', function(){
alert('Input changed');
});
For static inputs only:
$('.my-class').on('input', function(){
alert('Input changed');
});
JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/
HTML5 defines an oninput event to catch all direct changes. it works for me.
Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.
Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().
Let's say that your input field has an id and name of "city":
<input type="text" name="city" id="city" />
Have a global variable named "city":
var city = "";
Add this to your page initialization:
setInterval(lookForCityChange, 100);
Then define a lookForCityChange() function:
function lookForCityChange()
{
var newCity = document.getElementById("city").value;
if (newCity != city) {
city = newCity;
doSomething(city); // do whatever you need to do
}
}
In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.
If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.
onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.
if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc
Read more about the change event here
Read more about the input event here
use following events instead of "onchange"
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
Firstly, what 'doesn't work'? Do you not see the alert?
Also, Your code could be simplified to this
<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />
function checkInput(obj) {
alert(obj.value);
}
I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event
$('.inputClassToBind').bind('textchange', function (event, previousText) {
alert($(this).attr('id'));
});
A couple of comments that IMO are important:
input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.
The event you want to use is "input" ("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input
The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)
Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...
jQuery has nothing to do with this. This is all in HTML standard.
If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.
My two cents.
onkeyup worked for me. onkeypress doesn't trigger when pressing back space.
It is better to use onchange(event) with <select>.
With <input> you can use below event:
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
when we use onchange while you are typing in input field – there’s no event. But when you move the focus somewhere else, for instance, click on a button – there will be a change event
you can use oninput
The oninput event triggers every time after a value is modified by the user.Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.
<input type="text" id="input"> oninput: <span id="result"></span>
<script>
input.oninput = function() {
console.log(input.value);
};
</script>
If we want to handle every modification of an <input> then this event is the best choice.
I have been facing the same issue until I figured out how to do it. You can utilize a React hook, useEffect, to write a JS function that will trigger after React rendering.
useEffect(()=>{
document.title='fix onChange with onkeyup';
const box = document.getElementById('changeBox');
box.onkeyup = function () {
console.log(box.value);
}
},[]);
Note onchange is not fired when the value of an input is changed. It is only changed when the input’s value is changed and then the input is blurred. What you’ll need to do is capture the keypress event when fired in the given input and that's why we have used onkeyup menthod.
In the functional component where you have the <Input/> for the <form/>write this
<form onSubmit={handleLogin} method='POST'>
<input
aria-label= 'Enter Email Address'
type='text'
placeholder='Email Address'
className='text-sm text-gray-base w-full mr-3 py-5 px-4 h-2 border border-gray-primary rounded mb-2'
id='changeBox'
/>
</form>
Resulting Image :
Console Image
try onpropertychange.
it only works for IE.
I have a form field that starts out disabled and has an onClick to enable it. The onClick doesn't fire (at least in FF) nor does a simple alert(1);.
The hacky version is to show a fake form field in its place that "looks" like it's disabled (grayed out style) and onClick, hide it and show the correct field enabled, but that's ugly.
Example Code
This works:
<input type="text" id="date_end" value="blah" onClick="this.disabled=true;">
This works:
<label for="date_end_off" onClick="document.getElementById('date_end').disabled=false">Test</label>
<input type="text" id="date_end" value="blah" onClick="alert(1);" disabled>
This fails:
<input type="text" id="date_end" value="blah" onClick="alert(1);" disabled>
This fails:
<input type="text" id="date_end" value="blah" onClick="document.getElementById('date_end').disabled=false" disabled>
I came across this thread in another forum so I assume I'll have to go about it a different way.
http://www.webdeveloper.com/forum/showthread.php?t=186057
Firefox, and perhaps other browsers,
disable DOM events on form fields that
are disabled. Any event that starts at
the disabled form field is completely
canceled and does not propagate up the
DOM tree. Correct me if I'm wrong, but
if you click on the disabled button,
the source of the event is the
disabled button and the click event is
completely wiped out. The browser
literally doesn't know the button got
clicked, nor does it pass the click
event on. It's as if you are clicking
on a black hole on the web page.
Work around:
Style the date fields to look as if
they are disabled.
Make a hidden "use_date" form field
with a bit value to determine
whether to use the date fields during processing.
Add new function to onClick of the date fields which will
change the style class to appear
enabled and set the "use_date" value
to 1.
Use readonly instead of disabled
For checkboxes at least, this makes them look disabled but behave normally (tested on Google Chrome). You'll have to catch the click and prevent the default action of the event as appropriate.
Using jQuery, I attach an event handler to the parents of my input controls.
<script type="text/javascript">
$(function() {
// disable all the input boxes
$(".input").attr("disabled", true);
// add handler to re-enable input boxes on click
$("td:has(.input)").click(function() {
$(".input", this).removeAttr("disabled");
});
});
</script>
All of my input controls have the class "input" and they exist in their own table cells. If you at least wrapped your input tags in a div, then this should work without a table as well.
Citing Quirksmode.org:
"A click event on a disabled form field does not fire events in Firefox and Safari. Opera fires the mousedown and mouseup events, but not the click event. IE fires mousedown and mouseup, but not click, on the form. All these implementations are considered correct."
Quirksmode's compatibility table is great to find out more about such problems.
I recently had a very similar problem and solved it by placing the input in a div and moving the onClick to the div.
<div onClick="myEnableFunction('date_end');">
<input type="text" id="date_end" value="blah" disabled>
</div>
Enabling a disabled element on click kind of defeats the purpose of disabling, don't you think? If you really want the behavior you're describing, just style it 'disabled' and remove those styles on click.
Don't implement the logic of the onClick event in the onClick's value of the input field. That's probably why it's not working in Firefox. Instead define a function as the onClick's value. For example:
<input type="text" id="date_end" value="blah" onClick="doSomething()" disabled>
<script type="text/javascript">
function doSomething()
{
alert("button pressed");
}
</script>
It will also be worth looking into JQuery. You can use it to add or remove attributes from elements and all kinds of other stuff. For instance you can remove the disabled from the the input field by writing a function like this:
<script type="text/javascript">
function doSomething()
{
alert("button pressed");
$("#date_end").removeAttr('disabled'); //removes the disabled attribut from the
//element whose id is 'date_end'
}
</script>
OR you can add it as follows:
$("#date_end").attr('disabled','true');
The Jquery site is here
You can add a div over the input that is disabled: check it out
<div onclick="javascript:document.forma.demo1.disabled=false;" style="border:0px solid black; padding:00px;">
<input type=text name="demo1" disabled style="width:30;">
</div>
In order to enable a disabled element on the client side, lets say in response to a checkbox checked or something, I ended up having to use a combination of JS and jQuery, see below:
//enable the yes & no RB
function enable()
{
var RBNo = "rbnBusinessType";
var RBYes = "rbnBusinessType";
//jQuery approach to remove disabled from containing spans
$("#" + RBYes).parent().removeAttr('disabled');
$("#" + RBNo).parent().removeAttr('disabled');
//enable yes and no RBs
document.getElementById(RBYes).disabled = false;
document.getElementById(RBNo).disabled = false;
}
After postback then, you'll need to access the request like the following in order to get at the values of your client side enabled elements:
this._Organization.BusinessTypeHUbZoneSmall = Request.Params["rbnBusinessTypeHUbZoneSmall"] == rbnBusinessTypeHUbZoneSmallYes.ID;
Inspiration taken from:
https://stackoverflow.com/questions/6995738/asp-javascript-radiobutton-enable-disable-not-included-in-postback-ajax for more information
If you simply want to prevent the user from typing data in your field, but instead want the field to populate on an event, my hack solution was to not disable the input field at all, but instead after running my onclick or onfocus functions, to call blur() so the user can not edit the field.