I have a phone mask 9999-9999. But, I want it to be 99999-9999 if the user inputs another number. It is working, but the input happens in the penultimate place instead of the last one. Here is an example:
input: 123456789
expected result: 12345-6789
actual result: 12345-6798
I tried .focus() but it only works when debugging. I think it is something related to it having time to execute since the code is stopped, but i'm not sure.
$(document).ready(function () {
$('#TelContato').unmask();
$('#TelContato').prop('placeholder', '9999-9999');
$('#TelContato').mask('0000-0000');
mask2 = false;
var masks = ['0000-0000', '00000-0000'];
$("#TelContato").keypress(function(e){
var value = $('#TelContato').val().replace(/-/g, '').replace(/_/g, '');
//changes mask
if (value.length == 8 && mask2 == false) {
$('#TelContato').unmask(masks[0]);
$('#TelContato').mask(masks[1]);
mask2 = true;
}
})
//this is a keyup method because detects backspace/delete
$("#TelContato").keyup(function (e) {
var value = $('#TelContato').val().replace(/-/g,'').replace(/_/g, '');
//changes mask back
if (value.length <= 8 && mask2 == true) {
$('#TelContato').unmask(masks[1]);
$('#TelContato').mask(masks[0]);
mask2 = false;
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script>
<input asp-for="TelContato" class="form-control" maxlength="9" id="TelContato" />
It seems your problem is that you are unmasking, right before masking. You do not need to unmask, just updating mask (reconfiguring) should work.
$(document).ready(function() {
const masks = ['0000-0000', '00000-0000'];
const maskedElem = $('#TelContato');
maskedElem.prop('placeholder', '9999-9999');
maskedElem.mask(masks[0]);
maskedElem.on('propertychange input', function(e) {
var value = maskedElem.cleanVal();
//changes mask
maskedElem.mask(value.length >= 8 ? masks[1] : masks[0]);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script>
<input asp-for="TelContato" class="form-control" maxlength="9" id="TelContato" />
Here's the solution i found using the mask properties
$(document).ready(function () {
$('#TelContato').unmask();
$('#TelContato').prop('placeholder', '9999-9999');
$('#TelContato').mask('0000-0000');
var SPMaskBehavior = function (val) {
return val.replace(/\D/g, '').length === 9 ? '00000-0000' : '0000-00009';
},
spOptions = {
onKeyPress: function (val, e, field, options) {
field.mask(SPMaskBehavior.apply({}, arguments), options);
}
};
$('#TelContato').mask(SPMaskBehavior, spOptions);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script>
<input asp-for="TelContato" class="form-control" maxlength="9" id="TelContato" />
Related
<label> Telugu</label>
<input type="text" onkeyup="return isNumber(event)" name="telugu" id="telugu" maxlength="3"/> <br> <br>
JS
<!DOCTYPE html>
<html>
<head>
<script>
function isNumber(event){
var k= event.keyCode;
console.log(k);
if((k>47 && k<58)) /// THIS IS NOT WORKING
{
console.log("entered");
var s1 = document.getElementById("telugu").value;
var s2= document.getElementById("hindi").value;
var s3= document.getElementById("english").value;
var s4= document.getElementById("maths").value;
var s5= document.getElementById("science").value;
if(s1<0 || s1>100){
console.log("tel")
document.getElementById("telugu").value = 0;
}
I want to input only numbers in a textbox. the condition is not working. If the value in the textbox is less than 0 or greater than 100. then I am resetting the value to 0. Resetting is working but the characters are also entering.
You could use a regex to remove everything that is not a digit. I also change to the input event which fires whenever the input changes.
If you want to force numbers you could also just set the type to type="number". The benefit for this is that it will automatically show the number keyboard on phones and tablets, though you can show this as well with the inputmode="numeric" attribute
// Get the textbox
const telugu = document.getElementById("telugu");
// Add event that fires whenever the input changes
telugu.addEventListener("input", () => {
// Replace everything that is not a digit with nothing
const stripped = telugu.value.replace(/[^\d]/g, "");
// If the value is below 0 or above 100 set it to 0, else enter the stripped value
stripped < 0 || stripped > 100
? telugu.value = 0
: telugu.value = stripped;
});
<label for="telugu">Telugu</label>
<input type="text" name="telugu" id="telugu" maxlength="3"/>
Without comments:
const telugu = document.getElementById("telugu");
telugu.addEventListener("input", () => {
const stripped = telugu.value.replace(/[^\d]/g, "");
stripped < 0 || stripped > 100
? telugu.value = 0
: telugu.value = stripped;
});
<label for="telugu">Telugu</label>
<input type="text" name="telugu" id="telugu" maxlength="3"/>
Simplified:
function validateValue(event) {
var input = event.target;
var stripped = input.value.replace(/[^0-9]/g, ""); /* Everthing that is not (^) in the range of 0 through 9 */
if(stripped < 0 || stripped > 100) {
input.value = 0;
} else {
input.value = stripped;
}
}
<label for="telugu">Telugu</label>
<input type="text" oninput="validateValue(event)" name="telugu" id="telugu" maxlength="3"/>
You should do s1 variable parsed integer with parseInt() function.
function isNumber(event){
var k = event.keyCode;
console.log(k);
if(k>47 && k<58){
console.log("entered");
var s1 = parseInt(document.getElementById("telugu").value);
console.log('s1', s1);
if(s1<0 || s1>100){
console.log("tel")
document.getElementById("telugu").value = 0;
}
}else{
document.getElementById("telugu").value = null;
}
}
<label> Telugu</label>
<input type="text" onkeyup="return isNumber(event)" name="telugu" id="telugu" maxlength="3"/>
There are different ways to to this.
input: Fires when the value of the input has changed.
change: Fires when the value of the input has changed and the element loses its focus (it is no more selected).
blur: Fires when the input losed its focus.
Which event you use, depend on when you want to check the input. Use input if you want to check it instantly after the change of the value. Otherwise use blur or change.
Example:
let input = document.querySelector('#telegu');
input.addEventListener('input', () => {
// Your check
});
input.addEventListener('change', () => {
// Your check
});
input.addEventListener('blur', () => {
// Your check
});
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.
The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.
JS
var inp1 = document.getElementById("input1");
inp1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("input2").disabled = true;
}
}
HTML
<input type="text" id="input1">
<input type="text" id="input2">
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )
So:
var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
document.getElementById("input2").disabled = this.value != "";
});
<input type="text" id="input1">
<input type="text" id="input2">
...and then of course if you want it to be mutual, the same for input2.
You can achieve this using focus and blur. Below it is done with JQuery.
$(function() {
$('#input1').focus(function(){
$('#input2').prop('disabled', 'disabled');
}).blur(function(){
$('#input2').prop('disabled', '');
});
$('#input2').focus(function(){
$('#input1').prop('disabled', 'disabled');
}).blur(function(){
$('#input1').prop('disabled', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
How about using keyup?
Like this;
var inp1 = document.getElementById("input1");
var inp2 = document.getElementById("input2");
inp1.onkeyup = function() { inputValidation(this, inp2); }
inp2.onkeyup = function() { inputValidation(this, inp1); }
function inputValidation(origin, lock) {
var response = hasValue(origin.value);
lock.disabled = response;
}
function hasValue(value) {
return value != "" && value.length > 0;
}
https://jsfiddle.net/8o3wwp6s/
Don't make it harder than it is, this is simple.
var one = document.getElementById('one');
var two = document.getElementById('two');
//checks instantly
var checker = setInterval(function() {
if(two.value !== '') {
one.disabled = true;
} else {
//when its clear, it enabled again
one.disabled = false;
}
if(one.value !== '') {
two.disabled = true
} else {
two.disabled = false;
}
}, 30);
<input id="one">
<input id="two">
I am trying to run a simple if-statement that checks if the input's value (what is typed in) is at least 5 and then to show the submit button. I tried using the keyup function to detect the value as it is being typed in.
Does anyone see what I am doing wrong?
jQuery.fn.fadeBoolToggle = function(bool) {
return bool ? this.fadeIn(400) : this.fadeOut(400);
}
$('#submit-package').hide();
$('#package-name-input').on('keyup', function() {
var nameInput = $(this).val().length;
if (nameInput => 5) {
$('#submit-package').fadeBoolToggle();
}
//$('#package-name-input').val().fadeBoolToggle(length > 5);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="gen-input" id="package-name-input">
<div class="proceed-btn sans-pro" id="submit-package">
<span class="proceed-btn-text">SUBMIT</span>
</div>
You can pass condition as your function parameter, also you should change => to >=
jQuery.fn.fadeBoolToggle = function(bool) {
return bool ? this.fadeIn(400) : this.fadeOut(400);
}
$('#submit-package').hide();
$('#package-name-input').on('keyup', function() {
var nameInput = $(this).val().length;
$('#submit-package').fadeBoolToggle(nameInput >= 5);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="gen-input" id="package-name-input">
<div class="proceed-btn sans-pro" id="submit-package">
<span class="proceed-btn-text">SUBMIT</span>
</div>
Do it like:
use keyup() method
var i = 0;
$('#target').hide();
$('#text').keyup(function(event) {
i++;
if(i == 5)
{
$('#target').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="text">
<div id="target">
<input type="button" value="submit">
</div>
This looks like a syntax error. Greater than or equal to is expressed as >=, not =>.
Please do not give a negative vote if I am wrong with asking this question. I have a TextBox like this:
<input class="login-inpt" runat="server" name="loginName" type="text" value="User Name" />
It currently holds a default value. I want the default value to be cleared and replaced with a cursor when I click on the TextBox.
For newer browsers (IE>9):
<input type="text" id="userName" placeholder="User Name" />
For older:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Placeholder support</title>
</head>
<body>
<input type="text" id="userName" placeholder="User Name" />
<script src="../js/vendor/jquery-1.10.2.min.js"></script>
<script src="../js/vendor/jquery-migrate-1.2.1.js"></script>
<script src="../js/vendor/modernizr-latest.js"></script>
<script src="../js/placeholder.js"></script>
</body>
</html>
placeholder.js (jQuery, Modernizr)
var Placeholder = (function ($, document) {
/* Static Content */
var _$document = $(document);
/* Events */
var _initPlaceholders = function () {
_$document.find('input:text').each(function () {
var $this = $(this);
$this.css({ color: '#888' }).val($this.attr('placeholder'));
});
};
var _placeholderEvent = function () {
var $input = $(this), placeholderValue = $input.attr('placeholder');
if ($input.val() === placeholderValue) {
$input.css({ color: '#000' }).val('');
return;
}
if ($input.val() === '') {
$input.css({ color: '#888' }).val(placeholderValue);
}
};
var _bindEvents = function () {
if (!Modernizr.input.placeholder) {
_initPlaceholders();
_$document.on('focus blur', 'input:text', _placeholderEvent);
}
};
var init = function () {
_bindEvents();
};
return {
init: init
};
})(jQuery, document);
Placeholder.init();
You can try this
<input type="text" value="user name" onfocus="if(this.value=='user name') this.value='';">
HTML:
<input type="text" value="user name" id="userName" />
With jQuery:
$(function() {
$('#userName').click(function() {
$(this).val('').unbind('click');
});
});
EDIT: Here's a demo
add the following as an attribute to your input tag:
onfocus="if(this.value=='A new value') this.value='';"
From: How to clear a textbox using javascript
I got the solution Thanks.
input type="text" id="userName" onfocus="inputFocus(this)" onblur="inputBlur(this)"
function inputFocus(i) { if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; } } function inputBlur(i) { if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; } }
You already got good answers but if you are newbie it might interest you how it could work without libraries.
Here is HTML:
<input id="textBox" class="textBox phrase" type="text" value="Enter Your Text..">
you don't need to set class and id you could pick one of them
Here is JavaScript:
var textBox = document.getElementById('textBox'), //probably the fastest method
/**************************additionally possible****************************
var textBox = document.getElementsByTagName('input')[0], //returns HTMLInputElement list (since we've got only one we chose the first one)
or
var textBox = document.querySelectorAll('textBox'), //works almost the same way as jquery does except you don't get all jquerys functionality
or
var textBox = document.getElementsByClassName('textBox')[0], //i guess its a least supported method from the list
***************************************************************************/
//text you want to choose for you input
phrase = "Enter Your Text..";
function addEvent(el, ev, fn) {
//checking method support
//almost every browser except for ie
if(window.addEventListener) {
el.addEventListener(ev, fn, false);
}
//ie
else if(window.attachEvent) {
el.attachEvent('on' + ev, fn);
el.dettachEvent('on' + ev, fn);
}
}
addEvent(textBox, 'focus', function (){
//cross browser event object
var e = e || window.event,
target = e.target;
//if the text in your text box is your phrase then clean it else leave it untouched
target.value = target.value === phrase ? "" : target.value;
});
addEvent(textBox, 'blur', function (){
//cross browser event object
var e = e || window.event,
target = e.target;
//if your text box is not empty then leave it else put your phrase in
target.value = target.value ? target.value : phrase;
});
$('.login-inpt').focus(function() {
$(this).val('');
});
$('.login-inpt').focusout(function() {
$(this).val('User Name');
});
check out here http://jsfiddle.net/TDUKN/
I want to add to this code a "window.onbeforeload" event to show a message that prevent the user from quitting the current page without adding the products to cart.
I have to show only when the quantity in > than 0 and with respecting the code below.
How can I do that ?
<form> <p><input class="qty"
type="text" maxlength="1" value="0" /></p>
<p><input class="qty" name="text"
type="text" value="0" /></p> <p><input
class="qty" name="text2" type="text"
/></p> </form>
<script type="text/javascript">
$(".qty").change(function(e) {
if(this.value != '3' && this.value != '6' && this.value != '9') {
this.value = 0;
alert('You can buy only 3, 6, or 9 pieces fromn this product');
} }); </script>
Thanks for help :)
Not sure why everyone is suggesting globals. This method requires no globals and no change() listener (which you may still need if you want that alert there). Based on MDC, assuming support for [].indexOf:
window.onbeforeunload = function (e) {
var e = e || window.event;
if (['3','6','9'].indexOf($(".qty").val())>=0) {
return;
}
else {
var msg = 'You can buy only 3, 6, or 9 pieces from this product';
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = msg;
}
// For Safari
return msg;
}
};
With multiple inputs you will need to change the condition slightly:
var valid = true;
$('.qty').each(function(){ valid = valid && ['3','6','9'].indexOf($(this).val())>=0; });
if (valid) {
return;
}
else { ... }
You would need to set some "global" variable. GLobal does not necessarily mean global to the window, just enough it's global in your own namespace (which you hopefully got).
if(this.value != '3' && this.value != '6' && this.value != '9') {
NotifyTheUser = true;
}
else {
NotifyTheUser = false;
}
window.onbeforeunload = function() {
if( NotifyTheUser ) {
return 'Check your input.. foo bar yay!';
}
};
you can save the value in some global variable and then onbeforeunload look for that value, whether it's greater than 0 or not.
var valueContainer = 0;
$(".qty").change(function(e) {
valueContainer = this.value;
//rest of your code
});
window.onbeforeunload = function() {
if( valueContainer == 0) {
return 'Please Don't go away without selecting any product :(';
} };