Explanation: At the beginning the value of the field is YYYY-MM-DD. if the user delete the value and doesn't type anything, the button "ok" should be disabled. if the user delete the value and type new value, the button "ok" should be enable. The code is working only for the second case.
function ChangeOkButton()
{
if(document.getElementById('fromDate').value == null)
{ document.getElementById('save').disabled = true; }
else {document.getElementById('save').disabled = false; }
}
<input type="text" name="fromDate" id="fromDate" value="YYYY-MM-DD" onkeypress="ChangeOkButton();"/>
Is this possible?
Thank you!
That function is not very useful for that kind of control, since you could overwrite the value with '12345', 'foobar' or something else different than a realistic value. I suppose you want date starting from 2000-01-01
function ChangeOkButton(field) {
var okbtt = document.getElementById('save');
if ((/^(YYYY\-MM\-DD|2\d{3}\-(0[1-9]|1[0-2])\-(0[1-9]|[12]\{d}|3[01]))$/).test(field.value)) {
okbtt.removeAttribute('disabled');
}
else {
okbtt.disabled = 'disabled';
}
}
and your input is
<input type="text" name="fromDate" id="fromDate" value="YYYY-MM-DD" onkeyup="ChangeOkButton(this);"/>
Please note I've not considered leap years or days per month, this is only a more reliable control on data type entered by the user. Change the regexp as you like
Note: consider to put the 'okbtt' variable outside to the function for a matter of performance, otherwise you need to obtain a reference each time you call this function. awful.
Related
I do have a input with the pattern and the title to show the error in case of wrong data, I do need to not use the post method, so I just make some Jquery code to use the input validation, but I can't find how to show the default message of the input
This is the HTML5 input:
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
And this is the jquery code:
$("#inputEnviar").click(
function(){
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if ( userValidation ){
//code to do whatever I have to do if the data is valid
} else {
//if the data is invalid
//the input already has a default message to show
//then, how do I force to show
$("#user")-> FORCE TO SHOW TO THE DEFAULT ERROR MESSAGE OF THE INPUT
}
});
If the validation fails, in your else code block, set the custom message that you want to notify to the user:
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
Then, you can use reportValidity() to show that message. From MDN:
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
$("#inputEnviar").click(
function() {
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if (userValidation) {
//code to do whatever I have to do if the data is valid
} else {
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
var isValid = $('#user')[0].reportValidity();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
<input id="inputEnviar" type="button" value="Send">
For old browsers (i.e. IE) you would need to use a polyfill.
There are several implementations around (like this git). This article goes deeper on the topic.
This should work. The reportValidity() function will show the default message after you have set it with setCustomValidity.
function send() {
var input = $("#user")[0];
input.setCustomValidity("");
if(!input.checkValidity()) {
input.setCustomValidity("watch me break");
input.reportValidity();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="user" pattern="[^,]*" title="Message">
<button onclick="send()">Click</button>
I wrote the code for a form validation.
Should work like this:
It checks (allLetter (uName)) and if it's true, then validate the next input.
If any validation is false then it should return false.
My problem is that if both validations are true, then everything is exactly false and the form is not sent.
If I set true in formValidation (), if at least one check false, the form should not be sent.
<form name='registration' method="POST" onSubmit="return formValidation();">
<label for="userName">Name:</label>
<input type="text" name="userName" size="20" />
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" size="20" />
<input type="submit" name="submit" value="Submit" />
</form>
function formValidation() {
var uName = document.registration.userName;
var uPhone = document.registration.userPhone;
if(allLetter(uName)) {
if(phone(uPhone)) {}
}
return false;
}
function phone(uPhone){
var digts = /^[0-9]+$/;
if(uPhone.value.match(digts)){
return true;
} else {
alert('Phone must have only digits');
uPhone.focus();
return false;
}
}
function allLetter(uName) {
var letters = /^[A-Za-z]+$/;
if(uName.value.match(letters)) {
return true;
}else{
alert('Username must have alphabet characters only');
uName.focus();
return false;
}
}
First, you are using a 20+ year old way to gain references to your elements (document.form.formElementNameAttributeValue) and, while this still works for legacy reasons, it doesn't follow the standard Document Object Model (DOM) API.
Next, you've broken up your validation tests into different methods (and that's certainly not a bad idea for reusability), but in this case is is adding a ton of code that you just don't need. I've always found it's best to start simple and get the code working, then refactor it.
You're also not using the <label> elements correctly.
One other point, your form is set to send its data via a POST request. POST should only be used when you are changing the state of the server (i.e. you are adding, editing or deleting some data on the server). If that's what your form does, you'r fine. But, if not, you should be using a GET request.
Lastly, you are also using a 20+ year old technique for setting up event handlers using inline HTML event attributes (onsubmit), which should no longer be used for many reasons. Additionally, when using this technique, you have to use return false from your validation function and then return in front of the validation function name in the attribute to cancel the event instead of just using event.preventDefault().
So, here is a modern, standards-based approach to your validation:
// Get references to the elements you'll be working with using the DOM API
var frm = document.querySelector("form[name='registration']");
var user = document.getElementById("userName");
var phone = document.getElementById("userPhone");
// Set up event handlers in JavaScript, not with HTML attributes
frm.addEventListener("submit", formValidation);
// Validation function will automatically be passed a reference
// the to event it's associated with (the submit event in this case).
// As you can see, the function is prepared to recieve that argument
// with the "event" parameter.
function formValidation(event) {
var letters = /^[A-Za-z]+$/;
var digts = /^[0-9]+$/;
// This will not only be used to show any errors, but we'll also use
// it to know if there were any errors.
var errorMessage = "";
// Validate the user name
if(user.value.match(letters)) {
// We've already validated the user name, so all we need to
// know now is if the phone is NOT valid. By prepending a !
// to the test, we reverse the logic and are now testing to
// see if the phone does NOT match the regular expression
if(!phone.value.match(digts)) {
// Invalid phone number
errorMessage = "Phone must have only digits";
phone.focus();
}
} else {
// Invalid user name
errorMessage = "Username must have alphabet characters only";
user.focus();
}
// If there is an error message, we've got a validation issue
if(errorMessage !== ""){
alert(errorMessage);
event.preventDefault(); // Stop the form submission
}
}
<!-- 20 is the default size for input elements, but if you do
want to change it do it via CSS, not HTML attributes -->
<form name='registration' method="POST">
<!-- The for attribute of a label must be equal to the id
attribute of some other element, not the name attribute -->
<label for="userName">Name:</label>
<input type="text" name="userName" id="userName">
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" id="userPhone">
<input type="submit" name="submit" value="Submit">
</form>
I am trying to build a form using only JavaScript and jQuery. For one of the textboxes, I need to make it display as a date. And another as American Currency.
I have seen a few really cool forms before where it already has the " / /" symbols in there, and as you type the date, it falls perfectly into the symbols so you don't have to type them. Also, I need it to display as a date in the same format (mm/dd/yyyy) when a button is clicked. In addition, somehow, I need it where if no dates were entered, it displays nothing when the button is pushed.
EDIT:
Okay, so, after looking around online, I found a better way to describe what I am looking for for the date. It is exactly the same as the HTML5
<input type="date">
However, after clicking the button, I need it to display as MM/DD/YYYY and the HTML5 only allows YYYY-MM-DD which is NOT what I want.
So, how do I build a single textbox that has the same functions (I don't need the date picker) as the HTML5 "date", but with the display formate as MM/DD/YYYY after a button is clicked?
This sort of input is not trivial. There's some finesse that you'll need to do. First the HTML:
<div id="dateInput">
<input type="number" placeholder="MM" maxlength="2"/>/<input type="number" placeholder="DD" maxlength="2"/>/<input type="number" placeholder="YYYY" maxlength="4"/>
</div>
<div id="moneyInput">
$<input type="number"/>
</div>
Now basic CSS, we'll remove the borders from the inputs and instead add them to the containers:
input{
border:none;
background:transparent;
}
div{
border:1px solid #e0e0e0;
}
Here's the hardest part, the Javascript/jQuery. The money one should work natively but the date one will take some work.
$('#dateInput').on('input', function(){
//get max length of the input
var maxLength = parseInt($(this).attr('maxlength'));
//get the current value of the input
var currentValue = $(this).val();
//if the current value is equal to the maxlength
if(maxLength == currentValue.length){
//move to next field
$(this).next().focus();
};
});
On button press gather all the values from the inputs and display
$('button').on('click', function(e){
e.preventDefault();
//set the variable to append ti
var dateDisplay = '';
//iterate over the inputs
$('#dateInput input').each(function(){
//if dateDisplay exists (will explain soon)
if(dateDisplay && $(this).val() != ''){
//append the value
dateDisplay += $(this).val() + '/';
} else {
//if the value is blank, make the variable false.
dateDisplay = false;
};
});
//now check the variable
if(dateDisplay){
//if it's all good, remove the last character (/) and display
alert(dateDisplay.slice(0,-1));
}
return false;
});
This doesn't check for validity, just handles the general UX.
I was browsing online and in other forums, and found this answer:
$('#date').keyup(function(){
if ($(this).val().length == 2){
$(this).val($(this).val() + "/");
}
else if ($(this).val().length == 5){
$(this).val($(this).val() + "/");
}
});
I have a function that currently works with an input to prevent customers from inputting a P.O. Box into an address field. The input that works has an inline onKeyPress event, however the input I need to run the function on doesn't (and I can't access it).
My question is how to incorporate the correct event listener so that my function runs on this inaccessible input?
My JS Fiddle is here: http://jsfiddle.net/ZQQS9/4/
function killPObox(id) {
var idValue = document.getElementById('v65-onepage-shipaddr1').value;
if (id == 'v65-onepage-shipaddr1') {
function runVal() {
if (idValue.substr(0,4).toUpperCase() === "PO B" || idValue.substr(0,5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
setInterval(runVal(),1);
}
}
<!-- Practice input that works -->
1. <input type="text" class="quantity" name="v65-onepage-shipaddr1" id="v65-onepage-shipaddr1" onKeyPress="killPObox(this.name)">
<br>
<br>
<!-- Actual input that I need to hook into, cannot edit -->
2. <input type="text" size="25" maxlength="75" name="ShipAddress1" id="v65-onepage-shipaddr1" value="" style="" onkeydown="">
You can use the addEventListener() method like this:
document.getElementById('v65-onepage-shipaddr2').addEventListener('keypress', killPObox('v65-onepage-shipaddr2'));
I think your first input is incorrectly passing this.name as the argument to the killPObox() function. Should you be passing this.id instead? Also you may want to replace 'v65-onepage-shipaddr1' in your killPObox() function to just id to use the argument passed into the function.
I'm sure you have solved this already, but since this is still unanswered (and I stumbled on it) I'll add the solution for future visitors.
Use the correct event
First off, the onKeyPress will actually fire before the typed character has been registered in the input element. So if a user types abc and you do onKeyPress="alert(this.value)" it would alert ab. A better alternative would be onKeyUp, since this would get the last typed character too.
Use the event correctly
Next, the events - your options are:
//inline, not considered "best practice"
<input type="text" name="myinput" id="myinput" onKeyUp="killPObox(this)"/>
//same event as above, but in pure js
document.getElementById('myinput').onkeyup = function (e) {
killPObox(e.target);
};
//or attach an eventListener
document.getElementById('myinput').addEventListener('keyup', function (e) {
killPObox(e.target)
});
All of these should work for the majority of browsers. I would suggest alternative 3, or if you need IE8 support, alternative 2.
The JavaScript, simplified
Your function, killPObox(), should look something like this (using one of the above events):
function killPObox(el) {
if (el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') {
if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
}
Last but not least..
Finally, a very important part when using event binding, you need to use window.onload(). This is to make sure that both the script and elements that are to be bound are loaded before any code is run.
window.onload = function () {
// my binds, events and calls here
};
An actual working example of all three events:
function killPObox(el) {
if (el.id == 'v65-onepage-shipaddr0' || el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') {
if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
}
window.onload = function () {
document.getElementById('v65-onepage-shipaddr1').onkeyup = function (e) {
killPObox(e.target);
};
document.getElementById('v65-onepage-shipaddr2').addEventListener('keyup', function (e) {
killPObox(e.target)
});
};
"PO B" or "P.O. " will trigger the alert in all boxes:<br><br>
0. <input type="text" class="quantity" name="v65-onepage-shipaddr0" id="v65-onepage-shipaddr0" onKeyUp="killPObox(this)" />
<br/><br/>
1. <input type="text" class="quantity" name="v65-onepage-shipaddr1" id="v65-onepage-shipaddr1" />
<br/><br/>
2. <input type="text" class="quantity" name="v65-onepage-shipaddr2" id="v65-onepage-shipaddr2" />
I am looking for some date.parse() help for JavaScript. I have been searching different forums and sites and still have not been able to find a decent example of how to implement this. I am taking a beginning web design class and my instructor has asked for me to do this : "Set the placeholder text for the text box to “Enter a date.” Add an empty paragraph tag set to the document. In a separate JavaScript file code the event handler for the button to set the paragraph text to state whether or not the entered value is a recognizable date format. The Date.parse() method will return a number if passed a valid date string and the special value NaN (not a number) otherwise. NaN can be check for using the built-in function isNaN(). (You may want to refer to your online resources for more information on the Date object, NaN , and isNaN().)" I have been to a ton of websites that show the string but I need a dumbed down example of how to actually use it. here is my html code for the button:
<body>
<form>
<input type="text" id="dateTextInput" size="40" placeholder="Please Enter A Date">
<input type="button" id="addButton" value="Enter a Date">
</form>
<p></p>
</body>
and here is what I have for my .js file:
window.onload = init;
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
function handleButtonClick() {
var textInput = document.getElementById("addDateButton");
var dateString = textInput.value;
if (dateString == "") {
alert("Please enter a date");
}
else {
my issue is after my else, if that is even appropriate. I am lost as how to implement the date.parse function. I know it's date.parse(variable) but not sure how to make sure it can be a valid format. Dates can be entered in numerous ways. Should I make an array of possible dates and validate it that way? Or is there a simpler option? A link to a great guide would also be helpful, if an answer cannot be provided here. Thank you for your time.
Update; here is what I am using now. It halfway works. It alerts for an empty set. I just can't get the parse to alert:
function handleButtonClick() {
var textInput = document.getElementById("dateTextInput");
var dateString = textInput.value;
var dateValue = Date.parse(dateString);
var valid = !isNaN(dateValue);
if (dateString == "") {
alert("Please enter a date");
} else {
return(valid);
}
}
I hope everthing is understandable.
<form id="dateForm">
<!-- pattern just allow such format X.X.XXXX Or XX.XX.XXXX Or X.XX.XXXX Or XX.X.XXXX -->
<input type="text" id="dateTextInput" size="40" pattern="^\d{1,2}.\d{1,2}.\d{4,4}$" placeholder="Please Enter A Date">
<input type="submit" id="addButton" value="Enter a Date">
</form>
<script>
// onsubmit ist just called when dateTextInput is empty or has got valid date
document.getElementById('dateForm').onsubmit = function(e){
e.preventDefault(); // avoid to reload page
var date = document.getElementById('dateTextInput').value;
if(date === ''){ // always use === because == is sometimes buggy
alert('Please enter a date');
}
else{
var convertedDate = date.split('.'); // -> ['03','06','1985']
convertedDate = new Date(convertedDate[2],convertedDate[1],convertedDate[0]);
console.log(convertedDate.getTime()); // I think you wanted to get Milliseconds, but this works just as well
}
return false;
};
</script>
When the order of the day, month and year is not right, then just edit the pattern of the input-field and this codeline:
convertedDate = new Date(convertedDate[2],convertedDate[1],convertedDate[0]);
Dates can be entered in numerous ways. Should I make an array of possible dates and validate it that way?
No array. You should just accept what Date.parse does accept:
whether the entered value is a recognizable date format. The Date.parse() method will return a number if passed a valid date string and NaN otherwise.
"recognizable" does refer to Date.parse capatibilites I'd say. It's trivial to implement then:
var dateValue = Date.parse(dateString);
var valid = !isNaN(dateValue);
// grab the paragraph
if (valid)
// set the paragraph text accordingly
else
// output something different