jquery masking number input - javascript

I am using a function to mask the number input into my textbox but i want to assign the value prior to masking it to a knockout observable. I am unsure of where in my function i can grab and store that value since when you enter a value in the textbox and tab out the values are replaced by "*" as intended only for display. So where my textbox displays ***111 my observable should have a value of 1111111.
var viewModel = function () {
$(".textboxsemimedium").on("keydown keyup",
function (e) {
$(this).prop("value",
function (i, o) {
if (o.length < 6) {
return o.replace(/\d/g, "*");
}
});
});
self.theMemberNo = ko.observable();
}
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="textboxsemimedium" data-bind="value:theMemberNo" data-val="true" data-val-length="Member Number be of 9 characters!" data-val-length-max="9" data-val-length-min="9" data-val-required="Member Number is required!" id="MemberNumber" maxlength="10" name="MemberNumber" title="Member Number is Required!" type="text" value="">
<span data-bind="text:theMemberNo"></span>

Try using this https://css-tricks.com/better-password-inputs-iphone-style/
Then you implement it like so $('#user-password-2').dPassword();
It works similar to iphone password.

You are binding the theMemberNo to the input value. So that, if value changes from 1 to * the observable changes too.
I wouldn't bind the value of the input text to an observable I would just bind the event keyup and then, I would have an observable to keep the original value. Obviously, you will have to keep up to date this observable every time there is a keyup event.

Related

Keep phone area code in input

What I am trying to achieve is the input type text with initial area code added as a value
<input type="text" value="+1" id="phone" name="phone">
when user starts adding his/her phone number - this first +1 remains.
Here is how I have solved this:
$('#phone').keyup( function(){
var phone = $('#phone').val().substr(3); // copy phone number without the code
$('#phone').val(''); // emptying the value
$('#phone').val('+1-'+ phone); // adding the area code + entered number
});
but I guess it is rather silly and could be way better.
Here is Fiddle:
https://jsfiddle.net/gjzv6aph/
How can I make it better?
Use val() method with a callback function to generate new value with old value, the callback holds index as the first argument and old value as the second argument.
$('#phone').val(function(i, v){
return '+1-' + v.substr(3);
});
$('#phone').on('input', function() {
$(this).val(function(i, v) {
return '+1-' + v.substr(3);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="phone" value="+1-">

forcing focus to remain on a form text element until the value is numeric

I have a form which has input fields that expect numbers only.
I'm using javascript to validate the form when the value of the field changes.
If the value is numeric, do nothing.
If the value is not numeric, set it to zero and put focus in that text field. Essentially, I'm trying to trap the cursor in that field until a numeric value is entered. For some unknown reason, focus is not being placed on that form element. cell.focus() does not work. I've even tried document.getElementById(cel.getAttribute("ID")).focus(); What might I be doing wrong?
<html>
<head>
<script>
function NAN(cell){
if (cell.value != "") {
var re = /^(0|[1-9][0-9]*)$/;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = "0";
cell.focus();
}
}
}
</script>
</head>
<body>
<input type="text" name="num" value="" onchange="NAN(cell)"/>
</body>
</html>
Your problem is in the onchange attribute:
<input type="text" name="num" value="" onchange="NAN(cell)"/>
The value is executed as JavaScript code directly. You're passing code, not just a generic signature or prototype.
Inside those event handler snippets, there's a special object this defined, referring to the current DOM element (the input tag in this example).
(Just to mention it, there is also a second predefined object event, which most likely caused your confusion.)
As a simple fix for your issue, replace cell with this in the call and it should work:
<input type="text" name="num" value="" onchange="NAN(this)"/>
It's also important to note that you should keep in mind that this verification requires JavaScript to be executed. If it's disabled, the user might still pass any values, so you should check the value server side as well (assuming this isn't just client-only code).
As an alternative to using JavaScript, you could just use HTML5 to force a specific pattern on inputs. In this case this would be trivial to do:
<input type="text" name="num" value="" pattern="(?!0)\d+" title="Quantity">
The user won't be able to submit the form unless the pattern is validated, so there's no need to force the input focus. The pattern always has to match the full value, from beginning to the end. The title attribute is typically used to provide more information in the error popup.
There are two things done:
You have to change cell to this with onchange.
According to this question at least with Firefox setTimeout has to wrap this focus-method so that it works as expected.
And a more user-friendly approach is inserted as well at the second input-field.
Hope this example helps you:
function NAN(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
}, 0);
}
}
}
/*
* a more user friendly approach
*/
function NAN2(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
markElement(cell);
}, 0);
}
else{
tickElement(cell);
}
}
}
function tickElement(cell){
cell.setAttribute('style','border: 1px solid green');
}
function markElement(cell){
cell.setAttribute('style','border: 1px solid red');
}
<p>
Your approach(onchange):
<input type="text" name="num" value="" onchange="NAN(this)"/>
</p>
<p>
Or you can use a more user friendly approach to notify an user right now when they are tipping something wrong (onkeyup):
<input type="text" name="num" value="" onkeyup="NAN2(this)"/>
</p>

Custom Validation on HTML Number Input Misbehaving

In putting together a small webapp, I'm trying to ensure that end users are unable to place invalid characters in a number field that can hold signed floats. I'm using Dojo to search on an applied CSS class (in this case, ogInputNumber) and set events on input, keyup, and blur.
Ideally, I would like the input to be type="number" and to only allow digits, a hyphen (for signed floats), and a period character to act as a decimal place. If a user includes more than one hyphen or period character, the JS should truncate that second invalid character and everything thereafter in the input. Unfortunately, the JS behaves differently depending on whether the input is type="number" or type="text".
For type="text", if I attempt to enter the text 2.6a, 2.6 is fine, but the a is caught on the input event and prevented from appearing in the input. This is the desired behavior, but I would like to have the input as type="number" so the number spinners appear and for ease of use with mobile devices (so the number keyboard is brought up by default).
For type="number", if I attempt to enter the text 2.6a, the 2.6 is allowed to remain, but as soon as a is typed, the entire field is cleared out. That will prevent any invalid characters, but it's annoyingly overzealous. I've replicated this behavior on Chrome, Firefox, IE11, and Opera.
Can anyone offer any suggestions as to why the JS operates differently between inputs with type="text" and those with type="number"?
HTML:
<p>
<label for="numberInput1">Text Input</label>
<input id="numberInput1" class="ogInputNumber" type="text" />
</p>
<p>
<label for="numberInput2">Number Input</label>
<input id="numberInput2" class="ogInputNumber" type="number" />
</p>
JS:
// Checks number input fields for proper formatting
require(["dojo/domReady!", "dojo/on", "dojo/query"],
function (ready, on, query) {
query(".ogInputNumber").forEach(function (node) {
// Replace all the non-numeric, non-period, and non-hyphen characters with nothing while the user is typing
on(node, "input, keyup", function () {
this.value = this.value.replace(/[^\d\.-]/g, '');
});
// When the user leaves the input, format it properly as a signed float (or zero if it's something weird)
on(node, "blur", function () {
try {
if (this.value) {
this.value = parseFloat(this.value).toString();
} else {}
} catch (error) {
this.value = 0;
}
});
});
});
Working JSFiddle: http://jsfiddle.net/etehy6o6/1/
I think that's the default behavior of number input type, but I'm not sure. It's logical to think the input should not let the user put anything that is not a number, so it clears all the value before you can fire your keyup event.
So to keep the last valid value declare a variable outside the scope of your event and set it to the replaced value that was not cleared because invalid key input.
Using the code in your Fiddle:
Edited because addressed bug in comments
HTML
<!-- I asigned default values to test other scenarios -->
<p>
<label for="numberInput1">Text Input</label>
<input id="numberInput2" class="ogInputNumber" type="text" value="3.1416" />
</p>
<p>
<label for="numberInput">Number Input</label>
<input id="numberInput" class="ogInputNumber" type="number" value="3.1416" />
</p>
Javascript
// Checks number input fields for proper formatting
require(["dojo/domReady!", "dojo/on", "dojo/query"],
function (ready, on, query) {
query(".ogInputNumber").forEach(function (node) {
var validValue = this.value;
// Replace all the non-numeric, non-period, and non-hyphen characters with nothing while the user is typing
on(node, "input, keyup", function () {
if (this.value == '' && validValue.length > 1) {
this.value = validValue;
}
this.value = this.value.replace(/[^\d\.-]/g, '');
validValue = this.value;
});
// When the user leaves the input, format it properly as a signed float (or zero if it's something weird)
on(node, "blur", function () {
try {
if (this.value) {
this.value = parseFloat(this.value).toString();
} else {}
} catch (error) {
this.value = 0;
}
});
});
});

How to make simplier the jquery code

Aim is to detect if after page load input values are changed.
Input fields (19 fields) for example
<input type="text" name="date_day1" id="date_day1" value=" >
<input type="text" name="date_month1" id="date_month1" value=" >
<input type="text" name="date_year1" id="date_year1" value=" >
<input type="text" name="amount1" id="amount1" value=" >
Then hidden input field like this
<input type="text" name="is_row_changed1" id="is_row_changed1" value="">
<script>
$("#date_day1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
$("#date_month1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
If in any of input fields (19 fields) value is changed, then I need to reflect it in this hidden input field (I decided to set the hidden input field value to 1).
After that ajax with php where I check if the hidden input field value is 1. If 1, then update mysql. Aim is to reduce usage of server resources.
Question
Javascript code for the hidden input field would be long. May be some way (code) to make is shorter (simplier)?
Add a row_changed class to each input then you can target them all with one call:
$(".row_changed").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
(you can also simplify it even more with QuickSilver's comment.)
You could use JQuery selectors in order to set the same "input changed" callback for all input elements declared in your HTML code:
var anyFieldChanged = false; //Global variable
function changedCallBack()
{
anyFieldChanged = true;
alert('Fields changed');
}
allInputs = $('input');
allInputs.each(function() { this.onchange = yourCallBack(); });
I don't know if it's just in your example code, but you have several elements with the same ID, which is not valid. Each ID should be unique (which is the purpose of any ID). You can either add a class to each input you want to track and select on that like Shawn said or if you want to track every input except the hidden on the page you can use
$("input:[type!=hidden]").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
Use like this.
<script>
$("#date_day1").on("change", function () {
$('#is_row_changed1').val(1);
});
$("#date_month1").on("change", function () {
$('#is_row_changed1').val(1);
});
// etc
</script>

Validate Date input with Javascript

I have a input field date in my form and would like to add Javascript validation to ensure that its always greater than today's date. I tried the following but the function doesnt seem to be called when the user clicks on the input field and makes a change.
<input type="text" name="InsertRecordGuestOrders_Delivery_date" id="InsertRecordGuestOrders_Delivery_date" value=""/>
<script type="text/javascript">
function validateDate()
{
var del_date = document.getElementById('InsertRecordGuestOrders_Delivery_date').value;
if (Date.parse(del_date) < Date.now()) {
document.getElementById('InsertRecordGuestOrders_Delivery_date').value = '';
alert("Delivery date has to be later than today");
}
}
document.getElementById('InsertRecordGuestOrders_Delivery_date').onChange = validateDate();
</script>
Any suggestions on what I'm doing wrong?
Thanks in advance.
You want to assign the validateDate function to the onchange property, not execute the function and assign its return value. Change this:
document.getElementById('...').onChange = validateDate();
to this:
document.getElementById('...').onChange = validateDate;
This line:
document.getElementById('InsertRecordGuestOrders_Delivery_date').onChange = validateDate();
Should be:
document.getElementById('InsertRecordGuestOrders_Delivery_date').onchange = validateDate;
Notice the parentheses are gone. If you invoke it immediately, you're assigning the return value of validateDate() as the onchange handler. You want to assign the function itself as the handler, not the return value of the function.
In addition, it should be onchange, not onChange.

Categories

Resources