Need to append a script to a text field in an 'enter postcode' field, which will actively check the content and pop up an alert. Blacklisting postcodes, basically.
Here is what I have:
HTML:
<input type="text" maxlength="20" size="25" value="" name="zipc" id="zipc">
JS:
jQuery("#zipc").ready(function () {
function BFPO(t) {
if (t.value.match(/\"BF1 3AA"/g)) {
alert('We cannot send parcels to BFPO addresses. Ever.');
t.value = t.value.replace(/\s/g,'');
}
}
});
Now, I'm aware that is doesn't work but how do I fully 'ready' an alert like this when you then select the next field to type in? Perhaps the use of indexOf()?
Any help would be great and thanks in advance.
I think you can use focusout function. check this out
Focusout jquery
and also you can use
blur() function as well
$('#textfieldid').blur(function() {
//logic
});
So here's the solution, if anyone was wondering:
jQuery('#zipc').focusout(function () {
var _val = jQuery(this).val();
var _array = ["BF1 3AA", "Some_postcode"];
for (var i = 0; i < _array.length; i++) {
if (_val.indexOf(_array[i]) != -1) {
alert('OH, snap! That\'s a BFPO postcode... We don\'t send stuff there. Bummer.');
jQuery('#zipc').val("");
}
}});
Fiddle:
http://jsfiddle.net/hslincoln/WbDpG/1/
Related
I have a Textbox which will only allow user to input date in mm-dd-yyyy format. If the date is valid, the user will be able to move focus out of the textbox but if it's invalid, the focus should remain inside the textbox until the user corrects it. Currently I am using regex to validate the textbox input and I am able to successfully keep focus inside the textbox in case of invalid date. The issue I am facing is, even when I am correcting the invalid date, the focus does not move out of the textbox.
var dateCheck = function() {
var value = $("#txtbox1").val()
if (/^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/.test(value)) {
$("#txtbox1").blur();
return true;
}
else {
$("#txtbox1").focus().on('blur', function () {
$(this).focus();
return false;
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" size="12" class="form-control" onfocusout="dateCheck()" id="txtbox1"/>
P.S : Using Datepicker is not part of the requirement, would have been much easier I know. Any leads regarding this would be appreciated.
Edit: I have found a working solution and have updated the code above, but this code works only in Chrome and not in IE11
This snipped checks if the date is valid and if it is correctly formatted.
var dateMMDDYYYRegex = "^[0-9]{2}/[0-9]{2}/[0-9]{4}$";
/* isValidData source: http://stackoverflow.com/questions/5812220/how-to-validate-a-date */
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[0] - 1, bits[1]);
return d && (d.getMonth() + 1) == bits[0] && d.getDate() == Number(bits[1]);
}
var dateCheck = function() {
var value = $("#txtbox1").val();
if(value.match(dateMMDDYYYRegex) && isValidDate(value)){
$("#txtbox1").blur();
return true;
} else {
$("#txtbox1").focus().on('blur', function () {
$(this).focus();
return false;
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" size="12" class="form-control" onfocusout="dateCheck()" id="txtbox1"/>
Personally I would consider using an input mask like this one to make it easier for the user to use your code. Also don't forget to validate the date serverside. I would use a libary called Carbon to phrase the date.
Reference to the code: Stackoverflow
You do not need the else part. You can use HTMLElement.blur()
to remove the focus from the element. You can easily pass this element to the function so that you can refer the current element inside the function. I will also suggest you to use oninput event instead of onfocusout.
Try the following way:
var dateCheck = function(el) {
var value = $(el).val();
if (/^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/.test(value)) {
el.blur();
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" size="12" class="form-control" oninput="dateCheck(this)" id="txtbox1"/>
You could use onblur event, instead of using onfocusout event. Please refer to the following code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var dateCheck = function () {
var value = $("#txtbox1").val()
if (/^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/.test(value)) {
$("#txtbox1").blur();
}
else {
$("#txtbox1").focus();
}
};
</script>
<input type="text" size="12" class="form-control" onblur="dateCheck()" id="txtbox1" />
the output as below:
I would like to change this code to work also when Enter is pressed to be more clear i got an submit form and an text field following with the submit button that has to be clicked to submit but that doesn't help me out as i need the form to recognize when enter is pressed, what would be the change to sort it out?
submitButton.onclick = function() {
index = 0;
results = [];
username = usernameInput.value;
if ( username.length > 0 ) {
window.location.href = '//' + window.location.host + window.location.pathname + '#' + username;
usernameInput.disabled = true;
submitButton.disabled = true;
getExistence();
}
Also i got an issue with input validation, what change should i made to allow the form recognize and accept special characters?
usernameInput.onchange = function() {
this.value = this.value.replace(/[^a-z0-9]+/ig, '').slice(0, 40);
var urlUsername = window.location.href.match(/\#([0-9a-z]{1,40})$/i)
I would ask from you to be more specific as i am new to javascript coding, and my knowledge it's not enough to sort it easily.
First solution is to read this.
https://www.tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
You get info why "button type="submit" is better way than adding that into JS.
I think, solution for your problem can be something like that:
<form>
<label for="age">Age:</label>
<input type="number" min="0" max="120" name="age" id="age">
<button id="child">Child</button>
<button id="adult">Adult</button>
</form>
<script>
(function() {
var age = document.getElementById('age');
age.addEventListener('keypress', function(event) {
if (event.keyCode == 13) {
event.preventDefault();
if (age.value > 20) {
document.getElementById('adult').click();
} else {
document.getElementById('child').click();
}
}
});
}());
</script>
In short, commenting your code:
submitButton.onclick = function() { ... your code
This work as you describe, onclick. You can have similar function with :
submitButton.onkeypress = function() { ... same code with checking keyCode as example above
Validation: the simplest way to create any Regex is by doing some real test. I'am personally prefer this site: https://regex101.com/
What "special" character you mean? Because nobody can help right now. More info in this particular example. You just don't need any RegEx for JS. Accept any char and do everything on backend.
I'm trying to compare two form inputs "password" and re-enter-password" to make sure there the same. I validate the password by sending it to a separate PHP that echoes back the results(which works fine)
<script type="text/javascript">
$(document).ready(function() {
$('#password_feedback').load('password-check.php').show();
$('#password_input').keyup(function() {
$.post('password-check.php', {
password: form.password.value
},
function(result) {
$('#password_feedback').html(result).show();
});
});
});
</script>
I tried sending password and re-enter=password to a PHP to compare with no luck. Can I compare the two with every keyup.
What are you checking for in your PHP script? Anything in particular that justifies the use of PHP?
You could do that only with JS, you don't need the AJAX part.
HTML :
<input type="password" id="password">
<input type="password" id="password_cf">
<div class="result"></div>
JS (jQuery) :
$('#password_cf').on('keyup', function(){
if($('#password_cf').val()== $('#password').val())
$('.result').html('They match');
else
$('.result').html('They do not match');
});
Fiddle : http://jsfiddle.net/2sapjxnu/
You can use the blur event if you want to only check once the focus is lost on that field. It's a bit less "responsive" than verifying on every key, but more performant I guess.
Not necessary jQuery, add the function:
function checkPass(input) {
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
Add this to your re-enter-password: oninput="checkPass(this)"
OR
just call this function in the part where you want to make the comparison:
function checkPass() {
var input = document.getElementById('password');
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
How about adding a class to each input and then:
if($(".password").val() == $(".re-enter-password").val()){
alert("it matches")
} else {
alert("no match yet");
}
Quick and dirty -
Given this markup -
<input type="password" name="pw1" />
<input type="password" name="pw2" />
You could check it client side without muliple round trips to the server using code like this -
$('[name="pw2"]').blur(function() {
var pw1 = $('[name="pw1"]').val();
var pw2 = $('[name="pw2"]').val();
if(pw2 != pw1) {
alert('passwords do not match');
}
});
Matching 2 form input fields with JavaScript by sending it off to the server to get an assertion response could render a bad user experience, because if you're doing this on each keyPress, then it generates unnecessary internet traffic - while the user is waiting.
So, instead, why not match these 2 fields directly with JavaScript?
If you are using a specific regular expression on the server for validation check as well, you can have the server put that regex "pattern" in the HTML fields - (no JavaScrpt needed for that). Then, onkeyup event you can simply do something like:
form.field2.onkeyup = function()
{
if (form.field1.value !== form.field2.value)
{
/* some code to highlight the 2 fields,
or show some message, or speech bubble */
return;
}
}
form.field1.onkeyup = form.field2.onkeyup;
I have just started with JavaScript and want to validate a form. All the tutorials I've found create an alert for feedback, but I'd like to use onblur and give an error message next to the field. I managed to do the two functions separately but can't merge them. I'd really appreciate your help!
This is what I came up with, but it doesn't do what I need:
function validateFirstName()
{
var x=document.forms["demo"]["firstname"].value;
if (x==null || x=="" || x==)
{
function addMessage(id, text)
{
var textNode = document.createTextNode(text);
var element = document.getElementById(id);
element.appendChild(textNode);
document.getElementById('firstname').value= ('Firstname must be filled out')
}
return false;
}
}
So the following is a simple way to validate a form field by checking the value of an input when the form is submitted. In this example the error messages are just sent to the div element about the form but this should still help you out.
The HTML code looks something like this:
<div id="errors"></div>
<form onSubmit="return validate(this);">
<input type="text" name="firstName" placeholder="What's your first name?">
<button type="submit" value="submit">Submit</button>
</form>
The Javascript code looks something like this:
function validate(form) {
var errors ='';
if(form.firstName.value =="") {
errors += '<li>Please enter your first name</li>';
}
if(errors !='') { //Check if there are any errors, if there are, then continue
var message = document.getElementById("errors"); //assigns the element with the id of "errors" to the variable "message"
message.innerHTML = "<ul>" + errors + "</ul>"; //adds the error message into a list with the error message into the HTML
return false;
} else {
return true;
}
}
Once you understand this you should be able to figure the rest out on your own or go to http://www.w3schools.com/ and check out the javascript section to help you out.
I'm not sure what you really looking for. If I understood right (and I can be very wrong) you are looking for something like:
var x = undefined; // Can be undefined, null, or empty string
if (x==null || x=="" || x==undefined) { // do no forget to check for undefined
function addMessage(id, text) {
// Your validation code goes here
alert(id + text);
};
addMessage(1234, "Mandatory field!");
}
Note, there are several ways to do it. I just showing the simplest way I can think of...
I want to know if its possible to change the name of the input tag with javascript or jquery, for example in this code :
<input type="radio" name="some_name" value="">
I want to change the some_name value when user select this radio button.
the reason what i want to do this is described here : How might I calculate the sum of radio button values using jQuery?
Simply elem.name = "some other name" or elem.setAttribute("name", "some other name") where elem is the element you want to alter.
And to do that on selection, use the onchange event:
<input type="radio" name="some_name" value="" onchange="if(this.selected) this.name='some other name'">
And to apply that behavior to every radio button with that name:
var inputElems = document.getElementsByTagName("input");
for (var i=inputElems.length-1; i>=0; --i) {
var elem = inputElems[i];
if ((elem.type || "").toLowerCase() == "radio" && elem.name == "some_name") {
elem.onchange = function() {
if (this.selected) {
this.name = "some other name";
}
};
}
}
But using jQuery for that is quite easier.
The jQuery way
$('input:radio[name="some_name"]').attr('name', 'new name');
Gumbo has the vanilla JavaScript way covered
Yes, you can change the name of any element with javascript. Keep in mind though that IE 6 and 7 have trouble with submitted forms where the input elements have been tinkered with in javascript (not sure if this exact case would be affected).
$('input:radio[name="some_name"]').attr('name', 'new_name');
Edit: To change it only when it is selected, here is the code for that:
$("input:radio[name='some_name']").click(function() {
if ($(this).attr('checked')) $("input:radio[name='some_name']").attr('name', 'new_name');
else $("input:radio[name='some_name']").attr('name', 'some_name');
});
Sure. If jQuery is your poison, this should do the trick:
$("input[name=some_name]").attr("name", "other_name");
I came up with this:
<input type="radio" name="some_name" value="" id="radios">
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#radios").click(function()
{
$(this).attr("name", "other_name");
});
});
</script>
Trying to change the name attribute of a radio button will cause strange, undesirable behavior in IE.
The best way to handle this is to replace the old radio button with a new one. This post may help you. If you are using jQuery, you can do it with the replaceWith function.
More information about changing name attributes in IE.