jQuery input mask with two different user inputs - javascript

I'm trying to create an input mask, which collects two different values from the user. In the end the input mask should look like this:
[X.XXX$ for X years]
Where the X is an input by the user. Ist that possible? I've tried by using the jQuery Plugin inputmask and the code above:
$(document).ready(function(){
$('.query').inputmask({
mask: '9.999$ for 9?9 years',
placeholder: '1.000$ for 2 years'
});
});
The input mask doesn't work like I expected. It mixes the placeholder with the input values, what doesn't make sense to me. Can anybody help me with that issue?
Thanks a lot!

I see you're using this inputmask
The mask is getting into a funky state because there are some out-of-the-box definitions for y and a, which are being interpreted since they aren't being escaped. If you want to look at all the other default definitions, then open up your debugger and take a look at $.inputmask.defaults.definitions, or just take a look at the script.
You can escape a definition in the mask by using \\
update your script to the following and you should be good to go.
Here's a link to a fiddle if you want to experiment with it.
$('.query').inputmask({
mask: '9.999$ for 9 \\ye\\ar',
placeholder: 'X'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>
<input class='query' type='text' />

Related

Display tooltip/message while input is invalid HTML/JS/CSS/Angularjs

I have an HTML input field where certain characters shouldn't be allowed. The functional part is solved, but I would like to display a tooltip/message next to the input field while it contains illegal characters.
I have a boolean which keeps track of this, but I've been unable to make a satisfactory tooltip/message.
I've tried tweaking uib-tooltip, but It requires the user to hover over the input area. I've tried making a span/div/label that's hidden/displayed based on the boolean, but my CSS skills aren't strong enough.
The app uses Angularjs and Bootstrap 3.
The input field is not part of a form.
where you catch that boolean just say to display the div next to input like
myDiv.visible = true;
Without knowing your exact Javascript, I can't really answer it directly.
I would do something like
function invalid() {
if (invalid = true) {
document.getElementById("alert").style.visibility = 'visible'
}
}
make sure the error message is set to hidden,
then have the checker function run on focus..
<input type="text" onfocus="invalid()">
https://jsfiddle.net/we67geke/1/
This comment by user Lex solved the problem.
You can manually set the visibility of the uib-tooltip using the
tooltip-is-open attribute. Simply use the same boolean you are using
to keep track of the invalid characters.
As you mentioned
The app uses Angularjs and Bootstrap 3.
I suggest that you should use Boostrap tooltip. Use $('#element').tooltip('show') and $('#element').tooltip('hide') with your flag to handle status of Tooltip.
I don't know how your codes work, my idea seems like:
HTML:
<input type=text (keypress)="eventHandler()"> // angular >= 2
<input type=text ng-keypress="eventHandler()"> // angular 1
Angular code:
eventHandler() {
if (isIllegal) {
$('#element').tooltip('show');
} else {
$('#element').tooltip('hide');
}
}
Something like that.
Bootstrap Tooltip: https://getbootstrap.com/docs/3.3/javascript/#tooltips

Warn on non-ASCII Characters in Django Form

I'm trying to add some client-side Ajax validation of my Django form. I want to warn users, as they are typing in a field, if any of the characters they just inputted are not ascii.
I originally put the basic python to check for ascii characters in my form's clean method. I don't want to do that, though, as I don't want to produce an error but rather just give a warning message and let the user continue with the rest of the form.
try:
field_value.decode('ascii')
except UnicodeEncodeError:
#raise forms.ValidationError("Non-ASCII characters may cause issues in registering your data. Consider removing these characters. You may still submit at your own risk.")
# Just want to show a warning so the user can still submit the form if they wish
I want to show a small warning under the field as the user is typing. I've tried using django-dajax, but am not sure. How can I do this?
EDIT:
To clarify, I want to show the warning before the user submits the form. So, as they are filling out the form...
Use
> <input type="text" pattern="^[\x20-\x7F]+$" id ....>
in html
Use JavaScript to validate that form field.
Example (using jQuery):
<form>
<input name="whatever" id="fieldId">
...
</form>
<script type="text/javascript">
/* Define a function to check the form field value */
function containsAllAscii(str) {
return /^[\000-\177]*$/.test(str); // returns true if all are ASCII characters. false otherwise.
}
/* Now a little jQuery */
$('#fieldId').on('change', function() {
str = $(this).val();
is_valid = containsAllAscii(str);
if (!is_valid) {
window.alert("There are Non-ASCII characters in the input field");
}
});
</script>
The above code will check the given field's value whenever it changes (i.e. loses focus). You can use .on('keyup', ... instead of .on('change', ... which will check the field's value as the user is typing.
Finally, the error message that is shown is just a browser alert. Which is crappy. You can display a beautiful error message, you just need to learn a little more of jQuery. But I hope I've given you a good starting point.
Credits:
The code for containsAllAscii function is taken from this answer by Juan Mendes.
In your django form, create a custom field and take advantage of the media class.
from django import forms
class MyWidget(forms.TextInput):
class Media:
css = {
'all': ('pretty.css',)
}
js = ('animations.js', 'actions.js')
and set the js to the javascript file you will use for validation. something along the lines of the the other answer
https://docs.djangoproject.com/en/1.9/topics/forms/media/

Working With Dynamically Created Inputs

I have a dynamic form that you can add elements. Like, you type a name, and then if you have to write a new name, you click on 'Add Name', and another textbox appears.
Their names are names[]. I can process those inputs with PHP on the server-side. However, I want to make a calculation with those inputs, like writing all of them on the page as the user types.
However, because those inputs, those textboxes are created dynamically, Javascript only selects the first textbox with the name name[].
Let me make it clear. This way it'll be better. I got a textbox. I input age in there. If I want to enter a new age, I click 'Add Age' button, and a new input box pops out. I write the new age value. And as I type, on a 3rd textbox, the average of those age values get printed. But because of those input boxes, with names ages[] are created on the execution time (not the compile time, I'm not sure these are the appropriate words for those. Probably not, because nothing is compiling? - or is it?), I can't process them.
What must I do to solve this problem?
I used both
$('input[name=ages\\[\\]]').change(function(){
console.log('1');
});
and
$('input[name=ages\\[\\]]').on('input', function() {
console.log('2');
});
but it didn't work.
Thanks in advance.
There's no need to escape the square brackets (though you should enclose the whole field name in double quotes). This works for me:
$('input[name="names[]"]').on('change', function(){
console.log($(this).val());
});
Here's a jsfiddle demonstrating: http://jsfiddle.net/t7J5t/
Your problem is actually probably related to the fact that you're adding the fields dynamically. The way you're using your selector will only work on the fields that already exist. Fields that are added after that selector will not be picked up. What you want to do, then, is put the selector inside the .on, like this:
$('.container').on('change', 'input[name="names[]"]', function(){
console.log($(this).val());
});
This will bind the listener to the container, not the fields (just make sure your fields get added inside of the container; you can call it whatever you want).
Incidentally, there's no reason you have to restrict yourself from using the name attribute of fields when using jQuery selectors. For example, you could use a class:
<div class="container">
<input class="age" name="ages[]">
<input class="age" name="ages[]">
<!-- ... as many more as needed, added dynamically is OK ... -->
</div>
<script>
$(document).ready(function(){
$('.container').on('change', 'input.age', function(){
console.log($(this).val());
});
});
</script>
Here's a sample of it in action, where you can dynamically add fields, and it calculates the average:
http://jsfiddle.net/t7J5t/1/
Try to use:
$(document).on('change', 'input[name=ages\\[\\]]', function() {
console.log('2');
});

How to change jQuery inputmask mask based on dropdown context?

I'm presently using jQuery inputmask for the following effect:
It's fairly simple for US & Canada phone number formatting using something like:
$("#user_phone").inputmask("mask", { "mask": "(999) 999-9999" });
I would, however, like to change this formatting context based on the "Country code" dropdown such that when it is United Kingdom, it uses another mask, etc. How would I implement this such that the mask will change context based on dropdown in js/jQuery?
Here's an example of the working source as it is now: http://jsfiddle.net/j9aNh/1/
UPDATE: Okay, I think I've got it working satisfactorily now and would appreciate any advice in terms of drying this up properly: http://jsfiddle.net/j9aNh/3/
I do not know if that what you are looking for but it could be as simple as that I think.
$('select').change(function() {
var country=$(this).val() //or if you want to get text you may use var country=$(this).text()
var maskuse;
if(country=='USA')
{
maskuse="(999) 999-9999";
}
if(country=='Canada')
{
maskuse="(999) 999-9999";
}
/// and soon changing mask for a country
$("#user_phone").inputmask("mask", { "mask": maskuse });
});
if you are looking for Selection of an input mask for a phone number, use inputmask-multi

jQuery Validation for onChange or alternative

I have an interactive/editable table that does a number of things when a cell value is changed using onChange="myfunction". The problem is that I need to have a few validations:
maxlength = 1
only letters ^[a-zA-Z]+$
cannot be blank...require = true
However I fear that due to using onChange I may not be able to achieve this.
Here is a working example of my table: http://jsfiddle.net/JEAkX/32/
Here is the jQuery validator code I am hoping to get to work:
$.validator.addMethod(
"legalValue",
function(value, element) {
return this.optional(element) || /^[a-zA-Z]+$/.test( value );
},
alert("Bad Value!")
);
$(document).ready(function() {
$("#wholeTable").validate({
rules: {
cell: {
legalValue: true,
required: true,
maxlength: 1
}
}
});
});
Is it possible to make this work given my current setup using onChange? If not what direction would you recommend taking to converting to a system that would allow for this validation.
If I stay with onChange do I need to great a global array to house the values of the table in the case that someone enters something incorrect and the value is reverted so the table doesn't change?
just had a look at your sources, I'm not sure I understand what is your problem, but your code has one mistake:
<script type="text/javascript" scr="http://view.jquery.com/trunk/plugins/validate/jquery.validate.js"></script>
should be
<script type="text/javascript" src="http://view.jquery.com/trunk/plugins/validate/jquery.validate.js"></script>
not pushing you to solve the puzzle what's the difference is, I could say that path to script file is specifying using src attribute rather than using scr. After I changed that, when I enter "4" in any field, I get warning message about mistake etc. Also I can't enter few characters... So look like it works.. Was it the problem, or I didn't get your question?

Categories

Resources