ie8 update value event - javascript

I have been staring at this for 2 hours. The purpose is for when a user tabs out of a field, the value will be converted in to two digits.
For some reason IE8 Chokes on this the first time you try it but it works the second time. After that it occasionally breaks.
// backbone snippit
events: {
'blur [name=month], [name=day], [name=year]': 'sanitizeAge'
},
'sanitizeAge': function(e) {
var view = this;
var $el = $(e.target);
var $val = $el.val();
if($val.length === 1){
$el.val('0'+$val);
}
},
// html snippet
<div class="padded grid-quarter">
<input name="month" type="text" placeholder="MM" class="grid-whole text-field month" data-validate="month" data-min="2" maxlength="2" tabindex="3">
</div>
<div class="padded grid-quarter">
<input name="day" type="text" placeholder="DD" class="grid-whole text-field day" data-validate="day" data-min="2" maxlength="2" tabindex="4">
</div>
<div class="padded grid-half">
<input name="year" type="text" placeholder="Year of Birth" class="text-field grid-whole year" data-validate="year" data-min="4" maxlength="4" tabindex="5">
</div>
</fieldset>

Here's a simplified version of your answer:
'sanitizeAge': function(e) {
var val = e.target.value;
if (val.length === 1){
e.target.value = '0'+val;
}
},

I was able to get it to work only by getting the value via javascript instead of jquery.
'sanitizeAge': function(e) {
var view = this;
var $el = $(e.target);
var $val = $el[0].value; // <---- FIX
if($val.length === 1){
$el.val('0'+$val);
}
},

Related

Prevent double on.click event Javascript

i'm still new in using java script, i try to make trigger time when first input field get click, then the function trigger will active, the problem every time i click input field, the triggger always active again, i try using
event.preventDefault();
but it's didn't work, please help me where i do it wrong ?
this my code
$('#trigger').on("click", function(e) {
e.preventDefault();
var timeleft = 1;
var downloadTimer = setInterval(function(){ document.getElementById('countdown').value = `${timeleft} seconds`;
timeleft += 1;
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="trigger" class="form-control" required>
<input type="text" id="countdown" class="form-control" required>
edit : i try it like this, but its still haunt me if is this the best method?
function myFunction() {
var timeleft = 1;
var downloadTimer = setInterval(function() {
document.getElementById('countdown').value = `${timeleft} seconds`;
timeleft += 1;
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="trigger" onclick="myFunction(); this.onclick=null;" class=" form-control" required>
<input type="text" id="countdown" class="form-control" required>
You can use focusout event of Textbox
$( "#trigger" )
.focusout(function() {
myFunction();
});
and after focusout you can disable Textbox

How to disable submit button for multiple inputs (jQuery Homework) [duplicate]

This question already has answers here:
Disabling submit button until all fields have values
(11 answers)
Closed 1 year ago.
I'm trying to setup a jQuery function to keep a submit button disabled until all the fields are filled. I got to a point when I can get it to work with 1 field filled. I've tried to change my call statement various ways I can think of, but I've locked myself to only one field... so I'm obviously missing something... I'm still very new to javascript so I'd appreciate some simple basic help. Thanks
My jQuery:
$(document).ready(function () {
$("#valueInput").on("input", function () { // << only for one field
if ($(this).val() != "") {
$("#addCarToGarage").prop("disabled", false);
} else {
$("#addCarToGarage").prop("disabled", true);
}
});
});
My HTML:
<input type="number" placeholder="Year" id="yearInput" required/>
<input type="text" placeholder="Make" id="makeInput" required/>
<input type="text" placeholder="Model" id="modelInput" required/>
<input type="number" placeholder="Est Value" id="valueInput" required/>
<input type="submit" id="addCarToGarage" value="Add to Garage" disabled="disabled">
You can try following code.
Instead of using id of last input, following approach can be better
$(document).ready(function () {
$('form > input').keyup(function() {
var empty_inputs = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty_inputs = true;
}
});
if (empty_inputs) {
$('#addCarToGarage').attr('disabled', 'disabled');
} else {
$('#addCarToGarage').removeAttr('disabled');
}
});
});
Try something like that
$(document).ready(function () {
let areAllValid = false;
const fields$ = jQuery('input[type="text"], input[type="number"]');
function checkValues() {
areAllValid = true;
for(const field of fields$) {
if(!$(field).val()) {
areAllValid = false
}
}
}
$("input").on("input", function () {
checkValues()
$("#addCarToGarage").prop("disabled", !areAllValid);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" placeholder="Year" id="yearInput" required/>
<input type="text" placeholder="Make" id="makeInput" required/>
<input type="text" placeholder="Model" id="modelInput" required/>
<input type="number" placeholder="Est Value" id="valueInput" required/>
<input type="submit" id="addCarToGarage" value="Add to Garage" disabled="disabled">

Auto Selecting the next Input field and going Back

Once inputed, a user can't go back to change their input.
$("form").on("keyup change paste", function(e) {
e.preventDefault();
var a = $(this).find("input[type='text'].a");
var b = $(this).find("input[type='text'].b");
var c = $(this).find("input[type='text'].c");
var d = $(this).find("input[type='text'].d");
var e = $(this).find("input[type='text'].e");
var f = $(this).find("input[type='text'].f");
a.val(a.val().replace(/[^0-9]/g, ""));
b.val(b.val().replace(/[^0-9]/g, ""));
c.val(c.val().replace(/[^0-9]/g, ""));
d.val(d.val().replace(/[^0-9]/g, ""));
e.val(e.val().replace(/[^0-9]/g, ""));
f.val(f.val().replace(/[^0-9]/g, ""));
if (a.val().length == a.attr('maxlength')) {
a.next("input").focus();
}
if (b.val().length == a.attr('maxlength')) {
b.next("input").focus();
}
if (c.val().length == a.attr('maxlength')) {
c.next().next("input").focus();
}
if (d.val().length == a.attr('maxlength')) {
d.next("input").focus();
}
if (e.val().length == a.attr('maxlength')) {
e.next("input").focus();
}
if (f.val().length == a.attr('maxlength')) {
f.next("input").focus();
}
});
input {
width: 20px;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="code" action="*" method="post" autocomplete="off">
<input type="text" name="code" maxlength="1" autocomplete="off" class="a">
<input type="text" name="code" maxlength="1" autocomplete="off" class="b">
<input type="text" name="code" maxlength="1" autocomplete="off" class="c">
<span>—</span>
<input type="text" name="code" maxlength="1" autocomplete="off" class="d">
<input type="text" name="code" maxlength="1" autocomplete="off" class="e">
<input type="text" name="code" maxlength="1" autocomplete="off" class="f last">
</form>
How can that be done?
And is there a more elegant approach to mine above?
Live: jsFiddle
Any time you find yourself finding very repetitious code, always think LOOP.
The below will allow the user to edit their values. It also greatly reduces your code.
$('form').on('input', e => {
var letters = ['a', 'b', 'c', 'd', 'e', 'f'];
letters.forEach(letter => {
let field = $(e.target);
field.val(field.val().replace(/[^0-9]/g, ''));
if(field.val().length == field.attr('maxlength')) { field.nextAll('input').first().focus(); }
});
});
Fiddle.
Notes:
Listen for the input event; it has the advantage of covering all the events you were listening for, and, crucially, fires after keypress (meaning you can be sure of grabbing the latest, complete value from the field)
avoid repetitious code; the loop allows us to write the business logic once rather than repeatedly
there is no need to prevent the event's default action
by using nextAll('input').first(), we can be sure of getting the next input, whether it's the next sibling or, as is the case with the third input, separated by another type of element
My idea would be to focus next, and loop when arriving at the last one. Replace the number in case of a new entry.
// init the html
const nbInput = 6;
let html = '';
for (let i = 0; i < nbInput; i += 1) {
html += `<input type="text" name="code" maxlength="1" autocomplete="off" number="${i}">`;
}
$('form').html(html);
$('form input').on('keypress', function(e) {
e.preventDefault();
// Ignore bad values
if (/^[^0-9]$/g.test(String.fromCharCode(e.which))) {
return;
}
// Replace the actual value with the keypressed one
$(this).val(String.fromCharCode(e.which));
// Reset & focus next
if ($(this).val() !== '' && Number($(this).attr('number')) < (nbInput - 1)) {
$(`input[number=${Number($(this).attr('number')) + 1}]`).focus();
} else {
// Focus the first item when we finished
$('input[number="0"]').focus();
}
});
input {
width: 20px;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="code" action="*" method="post" autocomplete="off">
</form>
Clearing the inputs on focus would do it. (I don't use jQuery much, so apologies if I have any incorrect syntax.)
$("form").focus(function() {
var a = $(this).find("input[type='text'].a")
var b = $(this).find("input[type='text'].b") // ...etc
a.val("");
b.val(""); // ...etc
});
That said, Utkanos is 100% correct that a loop is the right way to handle both issues (auto-advancing and allowing edits).

Input tag type number for credit card

I have 4 input tags.
<input type="number" class="br1" name="first">
<input type="number" class="br1" name="secound">
<input type="number" class="br1" name="third">
<input type="number" class="br1" name="fourth">
I want to set maxlength (4 numbers) for every input tag. I tried to set maxlength but it doesn't work. Also, when I enter 4 numbers in one input tag, I want to automaticlly input in next input tag.
Thanks.
If you want to use maxlength change type of input to text. Then you can parse all you your inputs strings to a number.
$(".br1").keyup(function () {
if (this.value.length == this.maxLength) {
var $next = $(this).next('.br1');
if ($next.length)
$(this).next('.br1').focus();
else
$(this).blur();
}
});
$(".btn").click(function() {
var string = "";
$(".br1").each(function() {
string += this.value;
});
number = parseInt(string);
console.log(number);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="br1" name="first" maxlength=4>
<input type="text" class="br1" name="secound" maxlength=4>
<input type="text" class="br1" name="third" maxlength=4>
<input type="text" class="br1" name="fourth" maxlength=4>
<button class="btn">toNumber</button>
Use max="9999" and min="0000" to set the maximum value for input type number.
As per http://w3c.github.io/html/sec-forms.html#the-maxlength-and-minlength-attributes maxlength is not valid for input of type number.
You can use input event attached to .br1 elements, .slice() with parameters 0, -1 to remove character if .length of .value is greater than 4
var inputs = document.querySelectorAll(".br1");
for (let input of inputs) {
input.oninput = () => {
if (input.value.length > 4) {
input.value = input.value.slice(0, -1)
}
}
}
<input type="number" class="br1" name="first">
<input type="number" class="br1" name="secound">
<input type="number" class="br1" name="third">
<input type="number" class="br1" name="fourth">
You can do this using only javascript. Also note the maxLength attribute don't work on number, so you may need to use input type='text'
Here is snippet
// get the input
var inputBox = document.getElementsByClassName("br1")
// loop through the array of input
for (var i = 0; i < inputBox.length; i++) {
// creating a closure
(function(x) {
// adding event listener to each of the input
inputBox[x].addEventListener('keydown', function(x) {
// checking value of maxLength
var maxLength = parseInt(this.attributes["maxlength"].value, 10);
// length of the input value
var myLength = this.value.length;
// if both are equal then find the next sibling
if (myLength >= maxLength) {
var next = this.nextElementSibling
// if the next sibling is input, set focus to it
if (next.tagName.toLowerCase() === "input") {
next.focus();
}
}
})
}(i))
}
It as simple as posible, Try this:
$("input[type=number]").keypress(function (e) {
var el = $(this);
var currentValue = el.val();
var char = String.fromCharCode(e.keyCode || e.which);
if (currentValue.length === 3) {
el.val(currentValue + char);
e.preventDefault();
el.next().focus();
} else if (currentValue.length >= 4) {
e.preventDefault();
}
})
input[type=number]{
width:60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" class="br1" name="first">
<input type="number" class="br2" name="first">
<input type="number" class="br3" name="first">
<input type="number" class="br4" name="first">

Getting values from multiple text boxes on keypress in javascript

I have 8 different text fields in my form, it's a part of customer bill.
Here it is
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty">
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation">
......
up to 8
From this I want to show the sum of all the values as total value
<span>Total extra cost:1678</span>
It should be changed when the values of any text field is changed, so how can I do it perfectly using keyup event?
UPDATE
I have attached an onkeyup event to each textfield
`onkeyup="findSum(this.value)"'
and i am using a global array for store the input values var extras=[]
function findSum(value)
{
if(value!=''){
console.log(value);
extras.push(parseInt(value));
if(extras!='')
$('#extratotal').text(extras.reduce(getSum));
else $('#extratotal').text('0');
}
}
But its not worked well
You can get SUM of all inputs that have form-control class on keyup event like this:
$('input.form-control').on('keyup',function() {
var total = 0;
$('input.form-control').each(function(){
if (this.value == ''){
total += parseInt(0);
}else{
total += parseInt(this.value);
}
});
$('#total').val(total);
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty" >
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation" >
<input type="text" name="other" class="form-control" placeholder="other" >
Total extra cost: <input id="total" >
You can use the target.value property of the event passed to the key listener - this will give you the value of the input field:
document.addEventListener('input', 'keyup', function(e) {
// use e.target.value here
}
Just add this to a running total and update the text inside the listener function.
I have defined in JavaScript instead of jQuery. Try it..
<script>
function sum()
{
var sum = 0;
var array_field = document.getElementsByClassName('sum_field');
for(var i=0; i<array_field.length; i++)
{
var value = Number(array_field[i].value);
if (!isNaN(value)) sum += value;
}
document.getElementById("total").innerHTML = sum;
}
</script>
<body>
<input type="text" name="txtcustomduty" class="form-control sum_field" placeholder="Customs Duty" onkeyup="sum()">
<input type="text" name="txtlcltranspotation" class="form-control sum_field" placeholder="Local Transportation" onkeyup="sum()">
<p>Total:<span id="total">0</span></p>
</body>

Categories