focus function working in console but in through the code - javascript

I am trying to create a webpage which allows you to enter an IP address(IPv4). I want that whenever user has added 3 numbers in the textbox the focus should automatically be transferred to the next textbox. For that I have given onkeypress event to the textbox and called a JS function and sent an argument to it. Have a look at my code.
<input onkeypress="check(this)" type="text"
id="<?php if($i==1){echo "5";} else {echo "1";} ?>"
class="form-control" placeholder="First Octate"/>
Here is the check function
function check(element){
if(element.value.length==2){
newId= parseInt(element.id) + 1
document.getElementById(newId.toString()).focus()
}
}
Now if I log the document.getElementById(newId.toString()) to the console, it is giving me a valid element and if I use focus method with the logged element I am actually able to change the focus. What I can't understand is it is not doing the same thing if done using this function. I am not able to change the focus according to the condition

Problem with your code is the focus is not moving because of the action it takes. You need to add a slight delay
function check(element) {
if (element.value.length == 2) {
var newId = parseInt(element.id) + 1
setTimeout(()=>document.getElementById(newId.toString()).focus(),1);
}
}
<input onkeypress="check(this)" type="text" id="1" />
<input onkeypress="check(this)" type="text" id="2" />
<input type="text" id="3" />
You would be better off with keyup event
function check(element) {
if (element.value.length == 3) {
var newId = parseInt(element.id) + 1
document.getElementById(newId.toString()).focus();
}
}
<input onkeyup="check(this)" type="text" id="1" />
<input onkeyup="check(this)" type="text" id="2" />
<input type="text" id="3" />
Now this code is fine if they are typing, if they paste in a value, you have a whole new problem to solve.

Try adding a setTimeout command to your code:
function check(element){
if(element.value.length==2){
newId= parseInt(element.id) + 1
setTimeout(function() {
document.getElementById(newId.toString()).focus()
});
}
}
<input onkeydown="check(this)" type="text"
id="1"
class="form-control" placeholder="First octet"/>
<input onkeydown="check(this)" type="text"
id="2"
class="form-control" placeholder="Second octet"/>
<input onkeydown="check(this)" type="text"
id="3"
class="form-control" placeholder="Third octet"/>
<input onkeydown="check(this)" type="text"
id="4"
class="form-control" placeholder="Fourth octet"/>
Key events seem to refocus their targets' inputs after they have been fired. This tries to resolve that by waiting until the event has finished being fired, from which it will then focus the next input.
Also, I suggest you use keydown instead of keypress — the latter is deprecated.

You can set your events up in a window.load script and use data-attributes to inform your input listener on how many numbers to listen for. Also, if you use type='number' you can ensure you'll get numbers
window.addEventListener('DOMContentLoaded', () => {
let q = document.querySelectorAll('.autofoc');
q.forEach(el => {
el.addEventListener('input', e => {
let l = +e.target.dataset.len
if (e.target.value.length >= l) {
e.target.value = e.target.value.slice(0, l)
e.target.nextElementSibling.focus()
}
})
})
})
<input type="number" data-len='3' class="form-control autofoc" placeholder="Area code" />
<input type="number" data-len='3' class="form-control autofoc" placeholder="First 3" />
<input type="number" data-len='4' class="form-control autofoc" placeholder="Last 4" />

Related

Display value in input in html

I have the following code for html:
<label for="">Input</label>
<input type="text" name="" id="input_01" placeholder="Enter some text">
<label for="">Output</label>
<input type="text" name="" id="ouput_01">
<script>
var input_01 = document.getElementById("input_01")
var output_01 = document.getElementById("output_01")
input_01.addEventListener('keyup',function(){
output_01.value = input_01.value
})
</script>
I want to display the input value as the output. However, I found that the command "output_01.value = input_01.value" doesn't work and there is nothing displayed. I do not know why and do not know how to solve this problem. How can I display the content of an input in 'ouput_01'? Thank you.
make sure you don't have typo in your code.
change from
<input type="text" name="" id="ouput_01">
to
<input type="text" name="" id="output_01">
your INPUT tag output ID does not match the one on your javascript DOM and this output_01.value = input_01.value is wrong, instead you should add event to your function parameter in your Event Listener then assign your event.target.value to your output DOM value
<label for="">Input</label>
<input type="text" name="" id="input_01" placeholder="Enter some text">
<label for="">Output</label>
<input type="text" name="" id="output_01">
<script>
var input_01 = document.getElementById("input_01")
var output_01 = document.getElementById("output_01")
input_01.addEventListener('keyup', function(event) {
output_01.value = event.target.value
})
</script>

How can I detect when user clicks outside of input box (cursor goes away)?

blur does the job on Safari, but on Firefox it is causing problems. It seems that blur on Firefox fires when the mouse is moved outside of the input box, not when the cursor is actually removed (like when a user clicks somewhere outside of the box). This is a problem for me because I don't want my code to fire just because the user's cursor is moved outside of the box... I only want it to fire when the user clicks outside of the box as to indicate they are done typing. I have even tried event focusout but the same problem happens. Here is my code:
<div class="form-group">
<label for="min-reward-amount-input">Minimum reward amount</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="number" step="0.1" min="0" class="form-control" id="min-reward-amount-input" placeholder="0.00">
</div>
</div>
$("#min-reward-amount-input").blur(function(){
var initialValue = parseFloat($("#min-reward-amount-input").val());
if(!isNaN(initialValue) && initialValue>=0) {
var processedValue = initialValue.toFixed(2);
$("#min-reward-amount-input").val(processedValue);
} else {
$("#min-reward-amount-input").val("0.00");
}
});
Using jQuery, I'd do something like this using eventListeners:
document.addEventListener("click", function (event) {
if (event.target.className !== "textBox") {
window.alert("Clicked outside input field");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="textBox_1" class="textBox" placeholder="Field 1" />
<input type="text" name="textBox_2" class="textBox" placeholder="Field 2" />
<input type="text" name="textBox_3" class="textBox" placeholder="Field 3" />
<input type="submit" name="submit" class="submit" value="Next" />
</form>
Though there might, and probably is more elegant solutions instead of looking at the className.

I would like just recover the value of the field that I have just entered in jquery

I would like just recover the value of the field that I have just entered in jquery.
Thank you for your help
function test()
{
//????????
}
<form>
<label>Price</label>
<input type="text" name="price[]" onchange="test();"><br>
<label>Price</label>
<input type="text" name="price[]" onchange="test();"><br>
<label>Price</label>
<input type="text" name="price[]" onchange="test();">
</form>
For starters, if you're using jQuery, then use jQuery. Remove the inline onclick attributes:
<input type="text" name="price[]">
And attach a single event handler to your inputs:
$(function () {
$('input[type="text"]').change(function () {
var value = $(this).val();
// etc.
});
});
Within that handler, you can refer to the input raising the event as this and get its value accordingly as in the code above.
Example

Change $(this) input field color based on class effecting all classes in div

I have this HTML that occurs multiple times on a page:
<div class="canteen-item">
<div class="col-l">
<h4>Chicken Sandwich</h4>
<p>$<span class="canteen-price">3.50</span></p>
</div>
<div class="col-r">
<div class="qty-days">
<input name="Mon" class="qty-input" value="0" maxlength="2" />
<input name="Tue" class="qty-input" value="0" maxlength="2" />
<input name="Wed" class="qty-input" value="0" maxlength="2" />
<input name="Thu" class="qty-input" value="0" maxlength="2" />
<input name="Fri" class="qty-input" value="0" maxlength="2" />
</div>
</div>
</div>
I have this JQuery to detect when the input field is changed and if the value is greater than 0, change the color to red.
$(".qty-input").change(function(){
var qty = parseInt($(this).val());
if(qty > 0){
$(this).css('color','red');
}
else{
$(this).css('color','black');
}
});
It is behaving very unpredictably. When I change the value of the first input field (Monday), it makes all 5 inputs red. Then sometimes it is changing the colors back to black in completely different rows sets of days. Seems like a simple problem to fix, but having trouble figuring it out.
The problem is that this code:
var qty = $(this).val();
Returns a string. And this code compares that string to a Number
if(qty > 0){
Try changing the first line of code to:
if ($(this).val()) {
var qty = parseInt($(this).val(), 10);
}
And it should start to work more consistently but you will also want to validate that the input is all numbers.
Thanks for all the responses. It prompted me to dig deeper at which point I discovered another piece of code in a different JS file that was trying (incorrectly!) to do the same thing. The code I have above is in fact sound and works perfectly. I apologize for wasting anyone's time here. I didn't realize that my client had a developer who had already attempted to do this (and who also put the code in the wrong file).
Use change event target to get to the element
$(document).ready(function() {
$(".qty-input").change(function(e) {
var target = e.target;
var qty = $(target).val();
if (qty > 0) {
$(target).css('color', 'red');
} else {
$(target).css('color', 'black');
}
alert("value is " + qty)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="canteen-item">
<div class="col-l">
<h4>Chicken Sandwich</h4>
<p>$<span class="canteen-price">3.50</span>
</p>
</div>
<div class="col-r">
<div class="qty-days">
<input type="text" name="Mon" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Tue" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Wed" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Thu" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Fri" class="qty-input" value="0" maxlength="2" />
</div>
</div>
</div>

Slow JavaScript

I've got an HTML form where the maximum field value is set to 1 character. As a result, the JavaScript needs to be super-fast. But upon testing, it appears I am too fast for the script, so it misses characters unless I type slowly.
<script type="text/javascript">
function formfocus() {
document.getElementById('element').focus();
}
window.onload = formfocus;
function moveOnMax(field,nextFieldID){
if(field.value.length >= field.maxLength){
document.getElementById(nextFieldID).focus();
}
}
</script>
<input class="text" type="text" name="1" id="element" maxlength="1" onkeyup="moveOnMax(this,'2')"><input class="text" id="2" onkeyup="moveOnMax(this,'3')" type="text" name="2" maxlength="1">
Anyone know a way to speed this up, or am I stuck with having to instruct visitors to type slowly?
As you have mentioned maxlength of all fields are 1 character, then why to check length of the values of each field just in onkeyup event handler of every field make the focus to next field.
<script type="text/javascript">
function formfocus() {
document.getElementById('element').focus();
}
window.onload = formfocus;
function moveOnMax(nextFieldID){
document.getElementById(nextFieldID).focus();
}
</script>
<input class="text" type="text" name="1" id="element" maxlength="1" onkeyup="moveOnMax('2')">
<input class="text" id="2" onkeyup="moveOnMax('3')" type="text" name="2" maxlength="1">
<input class="text" id="3" onkeyup="moveOnMax('4')" type="text" name="2" maxlength="1">

Categories

Resources