How can I focus the next input once the previous input has reached its maxlength value?
a: <input type="text" maxlength="5" />
b: <input type="text" maxlength="5" />
c: <input type="text" maxlength="5" />
If a user pastes text that is greater than the maxlength, ideally it should spill into the next input.
jsFiddle: http://jsfiddle.net/4m5fg/1/
I must stress that I do not want to use a plugin, as I'd much rather learn the logic behind this, than use something that already exists. Thanks for understanding.
No jQuery used and is a very clean implementation:
Reads from the maxlength attribute.
Scales to any number of inputs inside of your container.
Automatically finds the next input to focus.
No jQuery.
http://jsfiddle.net/4m5fg/5/
<div class="container">
a: <input type="text" maxlength="5" />
b: <input type="text" maxlength="5" />
c: <input type="text" maxlength="5" />
</div>
..
var container = document.getElementsByClassName("container")[0];
container.onkeyup = function(e) {
var target = e.srcElement || e.target;
var maxLength = parseInt(target.attributes["maxlength"].value, 10);
var myLength = target.value.length;
if (myLength >= maxLength) {
var next = target;
while (next = next.nextElementSibling) {
if (next == null)
break;
if (next.tagName.toLowerCase() === "input") {
next.focus();
break;
}
}
}
// Move to previous field if empty (user pressed backspace)
else if (myLength === 0) {
var previous = target;
while (previous = previous.previousElementSibling) {
if (previous == null)
break;
if (previous.tagName.toLowerCase() === "input") {
previous.focus();
break;
}
}
}
}
You can watch for input in the fields and test its value:
$("input").bind("input", function() {
var $this = $(this);
setTimeout(function() {
if ( $this.val().length >= parseInt($this.attr("maxlength"),10) )
$this.next("input").focus();
},0);
});
Working demo.
The setTimeout is there to ensure the code will only run after the input is completed and the value updated. Binding input ensures most types of input will trigger the event, including key presses, copy/paste (even from mouse) and drag & drop (though in this case, the latter won't work, since the focus was on the draggable, not the droppable).
Note: on some older browsers, you might also need to bind propertychange.
If a user pastes text that is greater than the maxlength, ideally it should spill into the next input.
To do that, you might need to remove the maxlength attribute using JavaScript (to be able to capture the full input), and implement that functionality yourself. I made a small example, relevant parts below:
$("input").each(function() {
var $this = $(this);
$(this).data("maxlength", $this.prop("maxlength"));
$(this).removeAttr("maxlength");
})
This removes the attribute, but saves it in data, so you can access it later.
function spill($this, val) {
var maxlength = $this.data("maxlength");
if ( val.length >= maxlength ) {
$this.val(val.substring(0, maxlength));
var next = $this.next("input").focus();
spill(next, val.substring(maxlength));
}
else
$this.val(val);
}
Here the max length logic is reintroduced in JavaScript, as well as getting the "discarded" part and using it in a recursive call to spill. If there's no next element, the call to data will return undefined and the loop will stop, so the input will be truncated in the last field.
You can use plain JavaScript:
See DEMO.
Check the character length with el.value.length. If it is equal to the maximum value, move to the next field by using focus(). Bind this function to the keyup event with onkeyup so that the function fires every time after the user keys in a character.
var a = document.getElementById("a"),
b = document.getElementById("b"),
c = document.getElementById("c");
a.onkeyup = function() {
if (this.value.length === parseInt(this.attributes["maxlength"].value)) {
b.focus();
}
}
b.onkeyup = function() {
if (this.value.length === parseInt(this.attributes["maxlength"].value)) {
c.focus();
}
}
if you are going to have many fields you can do something like this.
basically on keyup get the length of the input and then compare it to the maxlength, if matches, then focus onto the next input field.
http://jsfiddle.net/btevfik/DVxDA/
$(document).ready(function(){
$('input').keyup(function(){
if(this.value.length==$(this).attr("maxlength")){
$(this).next().focus();
}
});
});
let otp = document.querySelector('#otp-screen');
for(let pin of otp.children) {
pin.onkeyup = function() {
if(pin.nextElementSibling) {
pin.nextElementSibling.focus();
}
}
}
<div class="otp-screen" id="otp-screen">
<input type="text" placeholder="0" maxlength="1"/>
<input type="text" placeholder="0" maxlength="1"/>
<input type="text" placeholder="0" maxlength="1"/>
<input type="text" placeholder="0" maxlength="1"/>
</div>
Updated btevfik code, Onkeyup or onkeydown will create issue as you won't be able to delete the previous input on tab navigation. It will be tough to edit or change the text inside the input box as it will be limited to maxlength. So we can use oninput event to achieve the task.
DEMO
HTML
<ul>
<li>a: <input type="text" maxlength="5" /></li>
<li>b: <input type="text" maxlength="3" /></li>
<li>c: <input type="text" maxlength="5" /></li>
<li>d: <input type="text" maxlength="3" /></li>
<li>e: <input type="text" maxlength="6" /></li>
<li>f: <input type="text" maxlength="10" /></li>
<li>g: <input type="text" maxlength="7" /></li>
</ul>
Javascript
$(document).ready(function(){
$('input').on("input", function(){
if($(this).val().length==$(this).attr("maxlength")){
$(this).next().focus();
}
});
});
CSS
ul {list-style-type:none;}
li {padding:5px 5px;}
Other answers do give some idea how this can be implemented, but I find that they do not consider some minor things among which are:
The fact, that you do not want to auto-focus any elements across whole page, but rather within specific form.
Input elements can be wrapped in some other elements (for example I wrap them in span or div to allow floating labels through CSS, and I've seen forms that use table to for structure).
Validity of the field, when spilling over or moving to next one automatically.
Input events when spilling over.
Cursor position when returning to previous field (it looks like it can be saved by browser, thus backspacing can focus not in the end of the field, but, for example, in the middle).
Below code is trying to account to all of this, at least. Most of it can be tested on codepen: paste-spilling does not work there, looks like because of Clipboard API (other codepens with it do not work for me either).
Let me know if anything is unclear in the code, I'll update my answer and the code. If you find some edge case that is not covered - let me know as well.
For paste-spilling test using form from codepen, you can use something like this: 123456789123456789012345678903454353434534
Video sample of how it works in a more "live" envitonment on youtube
//List of input types, that are "textual" by default, thus can be tracked through keypress and paste events. In essence,
// these are types, that support maxlength attribute
const textInputTypes = ['email', 'password', 'search', 'tel', 'text', 'url', ];
formInit();
//Add listeners
function formInit()
{
document.querySelectorAll('form input').forEach((item)=>{
if (textInputTypes.includes(item.type)) {
//Somehow backspace can be tracked only on keydown, not keypress
item.addEventListener('keydown', inputBackSpace);
if (item.getAttribute('maxlength')) {
item.addEventListener('input', autoNext);
item.addEventListener('change', autoNext);
item.addEventListener('paste', pasteSplit);
}
}
});
}
//Track backspace and focus previous input field, if input is empty, when it's pressed
function inputBackSpace(event)
{
let current = event.target;
if ((event.keyCode || event.charCode || 0) === 8 && !current.value) {
let moveTo = nextInput(current, true);
if (moveTo) {
moveTo.focus();
//Ensure, that cursor ends up at the end of the previous field
moveTo.selectionStart = moveTo.selectionEnd = moveTo.value.length;
}
}
}
//Focus next field, if current is filled to the brim and valid
function autoNext(event)
{
let current = event.target;
//Get length attribute
let maxLength = parseInt(current.getAttribute('maxlength'));
//Check it against value length
if (maxLength && current.value.length === maxLength && current.validity.valid) {
let moveTo = nextInput(current, false);
if (moveTo) {
moveTo.focus();
}
}
}
async function pasteSplit(event)
{
let permission = await navigator.permissions.query({ name: 'clipboard-read',});
//Check permission is granted or not
if (permission.state === 'denied') {
//It's explicitly denied, thus cancelling action
return false;
}
//Get buffer
navigator.clipboard.readText().then(result => {
let buffer = result.toString();
//Get initial element
let current = event.target;
//Get initial length attribute
let maxLength = parseInt(current.getAttribute('maxlength'));
//Loop while the buffer is too large
while (current && maxLength && buffer.length > maxLength) {
//Ensure input value is updated
current.value = buffer.substring(0, maxLength);
//Trigger input event to bubble any bound events
current.dispatchEvent(new Event('input', {
bubbles: true,
cancelable: true,
}));
//Do not spill over if a field is invalid
if (!current.validity.valid) {
return false;
}
//Update buffer value (not the buffer itself)
buffer = buffer.substring(maxLength);
//Get next node
current = nextInput(current);
if (current) {
//Focus to provide visual identification of a switch
current.focus();
//Update maxLength
maxLength = parseInt(current.getAttribute('maxlength'));
}
}
//Check if we still have a valid node
if (current) {
//Dump everything we can from leftovers
current.value = buffer;
//Trigger input event to bubble any bound events
current.dispatchEvent(new Event('input', {
bubbles: true,
cancelable: true,
}));
}
}).catch(err => {
//Most likely user denied request. Check status
navigator.permissions.query({ name: 'clipboard-read',}).then(newPerm => {
if (newPerm.state === 'granted') {
console.log('Failed to read clipboard', err);
} else {
console.log('Request denied by user. Show him some notification to explain why enabling permission may be useful');
}
}).catch(errPerm => {
console.log('Failed to read clipboard', errPerm);
});
});
}
//Find next/previous input
function nextInput(initial, reverse = false)
{
//Get form
let form = initial.form;
//Iterate inputs inside the form. Not using previousElementSibling, because next/previous input may not be a sibling on the same level
if (form) {
let previous;
for (let moveTo of form.querySelectorAll('input')) {
if (reverse) {
//Check if current element in loop is the initial one, meaning
if (moveTo === initial) {
//If previous is not empty - share it. Otherwise - false, since initial input is first in the form
if (previous) {
return previous;
} else {
return false;
}
}
} else {
//If we are moving forward and initial node is the previous one
if (previous === initial) {
return moveTo;
}
}
//Update previous input
previous = moveTo;
}
}
return false;
}
If you are adding input text fields dynamically then you can try this.
This will re-inject the script into the DOM and works Perfectly.
$('body').on('keyup', '#num_1',function(){
if (this.value.length === parseInt(this.attributes["maxlength"].value)) {
$('#num_2').focus();
}
})
$('body').on('keyup','#num_2', function(){
if (this.value.length === parseInt(this.attributes["maxlength"].value)) {
$('#num_3').focus();
}
})
<input type="text" class="form-control" name="number" maxlength="3" id="num_1">
<input type="text" class="form-control" name="number" maxlength="3" id="num_2">
<input type="text" class="form-control" name="number" maxlength="4" id="num_3">
If you're focused on creating card(debit/credit) number input type. Then clean an easily manageable jQuery version as follows:
/*..............................................................................................
* jQuery function for Credit card number input group
......................................................................................................*/
// make container label of input groups, responsible
$('.card-box').on('focus', function(e){
$(this).parent().addClass('focus-form-control');
});
$('.card-box').on('blur', function(e){
$(this).parent().removeClass('focus-form-control');
});
$('.card-box-1').on('keyup', function(e){
e.preventDefault();
var max_length = parseInt($(this).attr('maxLength'));
var _length = parseInt($(this).val().length);
if(_length >= max_length) {
$('.card-box-2').focus().removeAttr('readonly');
$(this).attr('readonly', 'readonly');
}
if(_length <= 0){
return;
}
});
$('.card-box-2').on('keyup', function(e){
e.preventDefault();
var max_length = parseInt($(this).attr('maxLength'));
var _length = parseInt($(this).val().length);
if(_length >= max_length) {
$('.card-box-3').focus().removeAttr('readonly');
$(this).attr('readonly', 'readonly');
}
if(_length <= 0){
$('.card-box-1').focus().removeAttr('readonly');
$(this).attr('readonly', 'readonly');
}
});
$('.card-box-3').on('keyup', function(e){
e.preventDefault();
var max_length = parseInt($(this).attr('maxLength'));
var _length = parseInt($(this).val().length);
if(_length >= max_length) {
$('.card-box-4').focus().removeAttr('readonly');
$(this).attr('readonly', 'readonly');
}
if(_length <= 0){
$('.card-box-2').focus().removeAttr('readonly');
$(this).attr('readonly', 'readonly');
}
});
$('.card-box-4').on('keyup', function(e){
e.preventDefault();
var max_length = parseInt($(this).attr('maxLength'));
var _length = parseInt($(this).val().length);
if(_length >= max_length) {
return;
}
if(_length <= 0){
$('.card-box-3').focus().removeAttr('readonly');
$(this).attr('readonly', 'readonly');
}
});
/*..............................................................................................
* End jQuery function for Credit card number input group
......................................................................................................*/
/* Hide HTML5 Up and Down arrows. */
input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none; margin: 0;
}
input[type="number"] { -moz-appearance: textfield; }
.card-box {
width: 20%; display: inline-block; height: 100%; border: none;
}
.focus-form-control {
border-color: #66afe9; outline: 0;-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="form-control" style="padding: 0; max-width: 300px; ">
<input class="card-box card-box-1" type="number" id="CreditCard_CardNumber1" required step="1" minlength="4" maxlength="4" pattern="[0-9]{4}" value="" placeholder="0000"
onClick="this.setSelectionRange(0, this.value.length)" oninput="this.value=this.value.slice(0,this.maxLength||'');this.value=(this.value < 1) ? ('') : this.value;"/>
<input class="card-box card-box-2" type="number" id="CreditCard_CardNumber2" readonly required step="1" minlength="4" maxlength="4" pattern="[0-9]{4}" value="" placeholder="0000"
onClick="this.setSelectionRange(0, this.value.length)" oninput="this.value=this.value.slice(0,this.maxLength||'');this.value=(this.value < 1) ? ('') : this.value;" />
<input class="card-box card-box-3" type="number" id="CreditCard_CardNumber3" readonly required step="1" minlength="4" maxlength="4" pattern="[0-9]{4}" value="" placeholder="0000"
onClick="this.setSelectionRange(0, this.value.length)" oninput="this.value=this.value.slice(0,this.maxLength||'');this.value=(this.value < 1) ? ('') : this.value;" />
<input class="card-box card-box-4" type="number" id="CreditCard_CardNumber4" readonly required step="1" minlength="4" maxlength="4" pattern="[0-9]{4}" value="" placeholder="0000"
onClick="this.setSelectionRange(0, this.value.length)" oninput="this.value=this.value.slice(0,this.maxLength||'');this.value=(this.value < 1) ? ('') : this.value;" />
</div>
Verified Answer have one issue which focus previous field if previous field have valid length
I have Modified Above Answer to fix complete length of previous tag
var container = document.getElementsByClassName("container")[0];
container.onkeyup = function(e) {
var target = e.srcElement || e.target;
var maxLength = parseInt(target.attributes["maxlength"].value, 10);
var myLength = target.value.length;
if (myLength >= maxLength) {
var next = target;
while (next = next.nextElementSibling) {
if (next == null)
break;
if (next.tagName.toLowerCase() === "input") {
next.focus();
break;
}
}
}
// Move to previous field if empty (user pressed backspace)
else if (myLength === 0) {
var previous = target;
// Move to previous field if backspace is pressed
if (code == 8) {
previous = previous.previousElementSibling;
if (previous != null) {
if (previous.tagName.toLowerCase() === "input") {
previous.focus();
}
}
} else {
while (previous = previous.previousElementSibling) {
if (previous == null)
break;
if (previous.tagName.toLowerCase() === "input") {
var mLength = parseInt(previous.attributes["maxlength"].value, 10);
var pMyLength = previous.value.length;
// Move to previous field if it does not have required length
if (mLength == pMyLength) {
break;
} else {
previous.focus();
break;
}
}
}
}
}
}
I think this is a shorter way. As long as you use a specific structure in HTML
const inputHandler = (event) => {
if (event.target.nodeName == "INPUT" && event.target.nextElementSibling != null) {
event.target.nextElementSibling.focus();
}
}
<div class="enter-code">
<input type="text" maxlength="1" #keyup="inputHandler">
<input type="text" maxlength="1" #keyup="inputHandler">
<input type="text" maxlength="1" #keyup="inputHandler">
<input type="text" maxlength="1" #keyup="inputHandler">
</div>
I haven't found the right answer in any similar questions, so I hope someone may be able to point me in the right direction.
I have a simple script that updates some text based on a range slider selection. I have noticed this works in everything except Edge, and having little experience with Javascript I'm wondering how to fix it.
The HTML:
<input type="range" min="1" max="3" step="1" id="pick_fruit" onchange="updateTextInput(this.value);" oninput="amount.value=rangeInput.value">
<p id="fruit_value">Pick a fruit</p>
The script:
<script type="text/javascript">
function updateTextInput() {
var fruit_range = Number(document.getElementById("pick_fruit").value);
var fruit_value = "";
if (
fruit_range === 1 ) {
fruit_value = "Apples";
}
else if (
fruit_range === 2 ) {
fruit_value = "Oranges";
}
else if (
fruit_range === 3 ) {
fruit_value = "Pears";
}
document.getElementById('fruit_value').innerHTML = fruit_value;
}
</script>
Any help would be much appreciated.
Thanks in advance
Use the oninput event to trigger the function. An object that maps ints to strings cleans up the conditional a little...
const fruitMap = { 1:'Apples', 2:'Oranges', 3:'Pears' }
function updateTextInput() {
const v = +document.getElementById("pick_fruit").value
document.getElementById('fruit_value').innerHTML = fruitMap[v];
}
<input type="range" min="1" max="3" step="1" id="pick_fruit"
oninput="updateTextInput()">
<p id="fruit_value">Pick a fruit</p>
You don't need to add
var fruit_range = Number(document.getElementById("pick_fruit").value);
because you are already getting value from the your function (updateTextInput()), you need to provide an argument inside the function to get the onchange value. I tried to simplify the code you can test it.
<html>
<body>
<input type="range" min="1" max="3" step="1" id="pick_fruit" onchange="updateTextInput(this.value)">
<p id="fruit_value">Pick a fruit</p>
</body>
<script type="text/javascript">
var fruit_value = "";
function updateTextInput(value) {
if (value == 1 ) {
this.fruit_value = "Apples";
}
else if (value == 2 ) {
this.fruit_value = "Oranges";
}
else if (value == 3 ) {
this.fruit_value = "Pears";
}
document.getElementById('fruit_value').innerHTML = fruit_value;
}
</script>
</html>
Update
Also you need to change the conditions from "===" to "==" or change the min & max to number type, as in input tag the values are in string and "===" checks both and its type but as in condition you were comparing string type to number type it will always give a empty string .
I am trying to change how value displayed using slider. I have made a label that display the value as below.
Course Duration : 1 day
the value displayed in here is changing according to the slider value.
so, when the slider value is in 1, it should be displayed as "day" and when the slider value greater than 1, it should be displayed as "days".
I have used if/else statement within my javascript to change the name displayed according to the slider value. The coding I used as below.
JS file :
// method used to get value from slider and display.
function slider_value() {
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function () {
output.innerHTML = this.value;
}
}
// method used to change name according to slider value
function value_name() {
var count = document.getElementById("myRange");
var outname = document.getElementById("dname");
if (parseInt(count.value) == 1) {
outname.innerHTML = "Day";
}
else {
outname.innerHTML = "Days";
}
}
HTML file:
<label for="duration">
Course Duration :
<span id="demo"></span>
<span id="dname"></span>
</label>
<div class="slidecontainer">
<input type="range" min="1" max="15" value="1" class="slider" id="myRange">
</div>
I have called the functions to the view as below:
<script>
slider_value();
value_name();
</script>
Coding won't show any errors while debugging but it only shows day or days and won't change according to the slider value. so I am expecting some help and ideas to rectify this.
Thanks a bunch.
You need to use the oninput and onchange events of the input element, such as:
oninput="slider_value(this.value)" onchange="slider_value(this.value)" .
Use both for full compatibility, since oninput is not supported in IE10.
Small example here, to get you started:
https://codepen.io/anon/pen/ewBNGj
Notice that the function that sets the day/days string ( value_name() ) is called from within the slider_value() function.
No need for complex js calculations, you could easily do this with the change event. add event listener to the input and then add you logic there, checkout the snippet
var el = document.getElementById('myRange');
el.addEventListener('change', function(event){
var value = event.target.value;
var _container = document.getElementById('demo');
value == 1 ? _container.innerText = value+' Day' : _container.innerText = value+' Days'
})
<label for="duration">
Course Duration :
<span id="demo"></span>
<span id="dname"></span>
</label>
<div class="slidecontainer">
<input type="range" min="1" max="15" value="1" class="slider" id="myRange">
</div>
Wrap the formatting of the slider's text in a function
function updateSlider(e) {
if (parseInt(e.value) == 1) {
output.innerHTML = parseInt(e.value) + " Day";
} else {
output.innerHTML = parseInt(e.value) + " Days";
}
}
This way you can call it once initially and populate the text properly. To update the contents of the slider as something changes add the input event listener and call this function from there.
Here's an example:
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
slider.oninput = function(e) {
updateSlider(e.target);
}
function updateSlider(e) {
if (parseInt(e.value) == 1) {
output.innerHTML = parseInt(e.value) + " Day";
} else {
output.innerHTML = parseInt(e.value) + " Days";
}
}
updateSlider(slider);
<label for="duration">
Course Duration :
<span id="demo"></span>
<span id="dname"></span>
</label>
<div class="slidecontainer">
<input type="range" min="1" max="15" value="1" class="slider" id="myRange">
</div>
How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.
How to make sure that every field has greater value than the value of previous input? If condition is true, then I can submit a form.
$('#add').on('click', function() {
$('#box').append('<div id="p1"><input required type="number" min="1" max="120" name="val" ></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
You need to loop through all the inputs, keeping the value of the previous one to compare it. Keep in mind, your current "add input" code will give all the inputs the same name, which will make it problematic to use on your action page. You can use an array for that.
$("#add").on("click", function() {
$("#box").append('<div id="p1"><input required type="number" min="1" max="120" name="val[]" ></div>');
});
$("form").submit(function(e) {
return higherThanBefore(); //send depending on validation
});
function higherThanBefore() {
var lastValue = null;
var valid = true;
$("input[name^=val]").each(function() {
var val = $(this).val();
if (lastValue !== null && lastValue >= val) { // not higher than before, not valid
valid = false;
}
lastValue = val;
});
return valid; // if we got here, it's valid
}
<a id="add" href="javascript:void(0);">Add </a>
<form action="test">
<div id="box"></div>
<input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
One line added, one line changed. Simply get the last input's value, and use that as the min value for the new input.
$('#add').on('click', function() {
// get the current last input, save its value.
// This will be used as the min value for the new el
var newMin = $("#box").find(".p1 input").last().val() || 1;
// Append the new div, but set the min value to the
// value we just saved.
$('#box').append('<div class="p1"><input required type="number" min="'+newMin+'" max="120" name="val" ></div>');
$(".p1 input").on("keyup mouseup", function(){
var triggeringEl = $(this);
if (triggeringEl.val() >= triggeringEl.attr("min") ) {
triggeringEl.removeClass("error");
}
triggeringEl.parent().nextAll(".p1").children("input").each(function(){
if($(this).attr("min") < triggeringEl.val() )
$(this).attr("min", triggeringEl.val() );
if ($(this).val() < $(this).attr("min")){
$(this).addClass("error");
} else {
$(this).removeClass("error");
}
})
})
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
So I made changes, to reflect the comments (great catch, by the way), but there is a challenge here. If I set the minimum value when the current el's value changes, works great. But I can't assume that the current el is the highest value in the collection, so if the current el is being decremented, I haven't figured the logic to decrement all subsequent minimums. Sigh...
At any rate, the section that creates the new input and sets the minimum remains the same. Then I had to add a listener to handle changes to the input. If the input is changed, by either keyboard or mouse, all subsequent minimums (minima?) are checked against this value. Those that are lower are set to this value, and then all elements are checked, minimum vs. value, and an error signal is set if needed. Still needs work, as I can't figure how to handle decrementing a value, but it's a start.
You can use .filter(): for each input field you can test if the next one has a value greater then the current one.
$('#add').on('click', function() {
var idx = $('#box').find('div[id^=p]').length;
$('#box').append('<div id="p' + idx + '"><input required type="number" min="1" max="120" name="val' + idx + '" ></div>');
});
$('form').on('submit', function(e) {
var cachedValues = $('form [type=number]');
var noOrderRespected = cachedValues.filter(function(idx, ele) {
var nvalue = cachedValues.eq(idx + 1).val();
return (+ele.value < (+nvalue||+ele.value+1)) ? false : true;
}).length;
console.log('noOrderRespected: ' + noOrderRespected);
if (noOrderRespected > 0) {
e.preventDefault();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>