I'm working on a form using Parsley form validation and am running into one last issue before it's all good to go. This is my first time using Parsley too.
I have this bit of custom script to autofill hyphens and parentheses:
<script type="text/javascript">
$("#inf_field_Phone1").on("change keyup paste", function () {
var output;
var input = $("#inf_field_Phone1").val();
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$("#inf_field_Phone1").val(output);
});
</script>
When tabbing through the form fields though to double check that all works well and I get to the phone number field, the first parenthesis autofills, and then when I submit the form, Parsley accepts that as a valid phone number. Here is the HTML:
<form accept-charset="UTF-8" id='become-partner-form' method="POST" name='Form'>
<div class="col-md-6">
<input type="tel" class="form-control tc-custom-focus" id="inf_field_Phone1" name="inf_field_Phone1" placeholder="Phone*" data-parsley-trigger='change' data-parsley-required>
</div>
And this may be unrelated but just in case, here is the js that is binding Parsley to the form:
<script type="text/javascript">
$(function () {
$('#become-partner-form').parsley().on('field:validated', function() {
var ok = $('.parsley-error').length === 0;
$('.bs-callout-warning').toggleClass('invisible', ok);
})
});
</script>
Please let me know if you need a jsfiddle or anything to help out (I don't post here much!)
Any ideas on how to prevent the form submit without a full valid phone number?
First, you probably want to use the input event instead of change (useless in your case btw), keyup and paste.
Parsley uses the inputevent, so as long as your code runs before parsley's (i.e. if you bind your autofill code before Parsley), you should be ok.
Related
I have written a JavaScript code. In this the alert is displaying more than one time.
<input type="text" name="grouptype" id="grouptype">
<input type="hidden" id="type_id" name="type_id">
<input type="text" id="type_bal" name="type_bal" onfocus="place1(form.grouptype.id,form.type_id.id)">
function place1(x,y)
{
var place=document.getElementById(x).value;// it hold the value of grouptype
var place_id=document.getElementById(y).value;//it hold the value of type_id
if(place!="" && place_id=="") {
document.getElementById(x).focus();
alert("pl. select the livesearch data");
}
}
not only that I used a jQuery code also. The following is the code
//<!-- the following commented code is used to move tab index when we press enter-->
$("input[tabindex],select[tabindex], textarea[tabindex]").each(function () {
$(this).on("keypress", function (e) {
if (e.keyCode === 13)
{
var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
if (nextElement.length) {
$('[tabindex="' + (this.tabIndex + 1) + '"]').focus();
$('[tabindex="' + (this.tabIndex + 1) + '"]').select();
e.preventDefault();
} else
$('[tabindex="1"]').focus();
}
});
});
The above code is used to move focus from one text field to another text field it is working properly when in another text field I kept a focus function named as place1 which I given in the above code is not invoking that place1 function without alert. Then i kept alert. By that the alert message it will was invoking by 3 times. why?
I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle
I'm trying to make a sub-total calculation tool, but I can't continue because I don't know what the problem is. When the form is submitted, or the button is clicked, everything quickly disappears.
Here's the fiddle :: http://jsfiddle.net/xFmBK/
I'm clueless...
function calcSub(){
var input = document.getElementById('fld'),
subTotal = document.getElementById('sub-total'),
tax = document.getElementById('tax'),
total = document.getElementById('total');
var subTotalCalc = input.value / 1.06;
var flag = true;
if(input.value == "" || input.value == null){
alert("Please enter in a total!");
return false;
} else {
subTotal.innerHTML = "Subtotal:" + " " + "$" + subTotalCalc;
tax.innerHTML = "Tax:" + " " + "$" + input.value - subTotalCalc;
total.innerHTML = input.value;
return flag;
}
}
That happens because your submit button actually does a form submit on some action and page is being refreshed. There are some ways to fix behavior, such as:
make your submit button just a button: <input type="button">
actually doesn't seem you need a form there
or add return false to onClick handler:
<button type="submit" onclick="calcSub(); return false;">Calculate</button><br>
Be aware of another issue: You have to use parentheses around (input.value - subTotalCalc). Without parentheses, you're trying to add and subtract strings, which results in NaN.
tax.innerHTML = "Tax:" + " " + "$" + (input.value - subTotalCalc);`
Your form is getting submitted when you click on the button, so the values are getting calculated but are disappearing immediately as the page is re-loaded.
Try adding onsubmit='return false;' to your form tag and the page re-load will be prevented.
Alternately you can change the button type to button.
Check this fiddle.
Just remove all the return from your code and add return false at the end
You need to prevent the form from being submitted. The form might be submitted by the user pressing enter when the form element is in focus, or by clicking the submit button. Even if the onclick event returns false, the submit event isn't altered.
I've taken the liberty of forking your fiddle:
Check the demo
window.addEventListener('load',function()
{
var input = document.getElementById('fld'),
subTotal = document.getElementById('sub-total'),
tax = document.getElementById('tax'),
total = document.getElementById('total'),
subTotalCalc;
document.getElementById('calcForm').addEventListener('submit',function(e)
{
e = e || window.event;
e.preventDefault();//prevent form's default behaviour
e.stopPropagation();//if submit was sent by clicking submit button, stop the event here
if (input.value === '' || input.value != +(input.value))
{
alert('Please enter valid subtotal (numeric)');
return;
}
subTotalCalc = input.value / 1.06;
subTotal.innerHTML = "Subtotal:" + " " + "$" + subTotalCalc;
tax.innerHTML = "Tax:" + " " + "$" + (input.value - subTotalCalc);
total.innerHTML = input.value;
},false)
},false);
I'd be happy to explain the code further if needs be...
Note that this doesn't fix the issue JS has with floating-point precision, if you're thinking about asking a follow-up question on that matter, check this fiddle first! I've added a simple toDecimal function here:
var toDecimal = function(num, precision)
{
precision = precision || 2;
num = +(num || 0);
return ( Math.round(num*Math.pow(10, precision))
/ Math.pow(10,precision)
).toFixed(precision);
};
So first multiply by 10^n, round and divide to 10^n again to get the desired float. To avoid any issues that might occur still (though there shouldn't be any AFAIKT, I've added a toFixed(n) call, too. This might be useful in case the rounded number is 213.00
I have a link which calls some javascript. The javascript populates a form value and submits it. Works fine in all browsers except internet explorer.
All other options on the page are links, thats why I also would like this option to be a link
thanks
<script type="text/javascript">
function timeZone(){
today = new Date()
difference = today.getTimezoneOffset()
var field = document.getElementById("form").timezone
alert("test")
if(difference < 0){
difference = difference * -1
field.value = "GMT+" + pad(Math.floor(difference/60), 2) + ":" + pad(difference%60, 2);
}
else{
field.value = "GMT-" + pad(Math.floor(difference/60), 2) + ":" + pad(difference%60, 2);
}
form = document.getElementById('form');
form.submit();
}
function pad(num, digits) {
num = String(num); while (num.length < digits) { num="0"+num; }; return num;
}
</script>
<form method="get" action="ViewLog.do?page=1" id="form">
<input id="timezone" name="timezone" type="hidden" value=""></input>
<img id="activityHistoryImage" Class = "navImage" src="imgs/history.png" alt="Activity history"/>
Activity history<br/>
<small class="navSubText">See your most recent activities </small>
</form>
Internet Explorer may or may not have issues with the fact that you've given an id of 'form' to your form element; I imagine it probably does. In general, it's best to avoid using tag names as the value on id or name attributes.
Also, your hidden input element has an id, yet you're not using it to reference it. Change:
var field = document.getElementById("form").timezone
to
var field = document.getElementById("timezone");
Declare variables with var.
Place ; where they should be.
I have seen in a few "username" fields where you type in a username, and below it, in something like a span, it will append it to a url. A lot like what is happening as I type this in StackOverflow at the bottom.
I would like to show only allowed characters from a list, ignore any input of characters not in that list.
I am really new to JS. In this case, I am using Jquery, and have a sort of works with some parts, and other parts I do not, or I have not gotten there yet.
Desire:
Input form field accepts only characters from a list, others are ignored.
Get the new key as entered, and append it to an element.
Here is the mess I have so far:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keyup(function(e) {
var entered = $('#cart-name').val();
entered = entered.toUpperCase();
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
// fromCharCode always returns uppercase?
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
var pos = allowed.indexOf(entered_char);
console.log('position is: ' + pos);
if (pos <= 0) {
console.log('does not contain');
} else {
console.log('contains');
}
$('#live').text(entered);
console.log(entered);
});
});
</script>
In the html I have:
<input type="text" name="cart_name" value="" id="cart-name" autocomplete="off" />
<br />
http://example.com/
<span id="live"></span>
<br />
Why not use a regular exprsession to replace non alphanumeric characters?
entered = entered.replace(/[^a-zA-Z 0-9]+/g,'');
Looking at your comments, you have some confusion over the different Key events:
keyup (and keydown) tell you which physical key has been pressed, while keypress will tell you which character has been typed - which is why you're always getting uppercase letters from fromCharCode.
I'm using something like this to sort out urls:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keypress(function(e) {
var entered = $('#cart-name').val();
// Regular Express to perform match on all alphanumeric characters,
// and - and _
var matchPattern = /[\w/_/-]/g;
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
if (entered_char.match(matchPattern)) {
$('#live').text(entered + entered_char);
}
else if (enteredKey == " ") {
// Replace spaces with hyphens for SEO
$('#live').text(entered + "-");
}
});
});
</script>
Should see you right.