How to change the value of an active text input using Javascript? - javascript

I am trying to make a form with a date input.
However, this input is in date format, and I would like to change the value while the control is still active.
Here is the full code :
// Javascript code
function add_value()
{
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length = 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length = 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onchange="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
But this is only updating the text when you exit of the control, and I would like to know how to run this javascript function while the control is still active.
Thanks.

You need to use onkeyup.
<input id="fin_mater" type="text" onkeyup="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
From the docs
Execute a JavaScript when a user releases a key
Also in your if your are using =, you should be using ==
...
if(document.getElementById("fin_mater").value.length == 2)//==
...
else if(document.getElementById("fin_mater").value.length == 5)
...

First let's make the code smell more like the "javascript" :)
// Javascript code
function $(id) {
return document.getElementById(id);
}
function add_value(event) {
var dataOriginale = $("fin_mater").value,
len = dataOriginale.length,
key = event.keyCode || event.charCode;
// Allow BACKSPACE and DEL
if (key === 8 || key === 46) {
return true;
}
if(len === 2 || len === 5) {
$("fin_mater").value = dataOriginale + '-';
}
return false;
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onKeyUp="add_value(event);" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
If you want to append the "-" automatically when you input numbers, you can listen on the "onKeyUp" event of the text box rather than the "onchange".
PS: You can use the key code to limit only numbers input and also do some validations.

You can use keypress():
$(document).ready(function()
{
$( "#fin_mater" ).keypress(function() {
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
});
});
Fiddle

With some of your help and some documentation, I finally went to this, that works perfectly on every browser that supports javascript.
$(document).ready(function(event)
{
$( "#fin_mater" ).keypress(function(event) {
var dataoriginale = document.getElementById("fin_mater").value;
if(event.keyCode != 8)
{
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
});
});
Thanks everyone !

Related

Stop form whitespace when user pressing submit

Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

Javascript show validation message right after the text box

I am trying to validate a form using javascript. On button click function I have called a javascript function where I have displayed the message after the text box. The number of times I click the button same number of times message gets displayed just below the existing validation message. Please help me
Here goes my code:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstname').after('Validation message');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastname').after('Some validation text');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}
Assuming I understand what v is for. Which i probably don't because v (I hate one letter variable names...).
Try this:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
if ($('#firstnameMessage').length <= 0)
{
$('#firstname').after('<p id="firstnameMessage">Validation message</p>');
document.getElementById('firstname').style.borderColor='#DA394B';
}
v = false;
}
if ((document.getElementById('lastname').value == "")) {
if ($('#lastnameMessage').length <= 0)
{
$('#lastname').after('<p id="lastnameMessage">Some validation text</p>');
document.getElementById('lastname').style.borderColor = '#DA394B';
}
v = false;
}
return v;
}
Simple fiddle to show this working: https://jsfiddle.net/srLt7wo0/
Using .after will insert another element per http://api.jquery.com/after/
The below solution uses a separate element already in the HTML to display the error message. If you use .after you have to check that you have not already added an element to your HTML
HTML
<input id="firstname" type="text"/><div id="firstnameMessage"></div>
<input id="lastname" type="text"/><div id="lastnameMessage"></div>
JS
function check() {
$("#firstnameMessage,#lastnameMessage").text(''); // clear message, reset border color
document.getElementById('firstname').style.borderColor='';
document.getElementById('lastname').style.borderColor='';
var isValid = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstnameMessage').text('First name is required');
document.getElementById('firstname').style.borderColor='#DA394B';
isValid = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastnameMessage').text('Last name is required');
document.getElementById('lastname').style.borderColor='#DA394B';
isValid = false;
}
return isValid;
}
I'm not sure to have understood you issue but maybe this could help you :)
window.firstname = document.getElementById('firstname')
window.lastname = document.getElementById('lastname')
window.issue = document.getElementById('issue')
function check() {
if(firstname.value == '' || lastname.value == '') {
issue.innerHTML = 'Please, use correct credentials.'
} else {
issue.innerHTML = ''
}
}
<input id="firstname" />
<input id="lastname" />
<button onclick="check()">
Check
</button>
<div id="issue" style="color:red;"></div>
This should work if i understand you.
It will add only one message no matter how many times you click
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#message').remove()
$('#firstname').after('<span id='message'>Validation message</span>');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#message').remove()
$('#lastname').after('<span id='message'>Some validation text</span>');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}

Try to validate IP Address with javascript

I'm a beginner to javascript. Now, I'm trying to make a form to post back to server. There are some "input" that contains ip address which should be validate before submitting. Now I have done a javascript function which work well. But now I'm trying to add this function into jquery selection. Just confuse how to do it.
This is my validate javascript code.
function ValidateIPaddress(Ipfield)
{
IpAddr=Ipfield.value;
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(!IpAddr.match(ipformat))
return true;
else
return false;
}
and this is now how I implement for this validation.
<input type= "text" name= "LocalIP" style= "margin-right:10px " value="192.168.1.193" class="ip" onfocusout="ValidateIPaddress(document.getElementById('LocalIp'))" id="LocalIp" > Remote VIP Address :
<input type= "text" name= "RemoteVIPAddr" style= "margin-right:10px" value="234.5.6.7" class="ip" onfocusout="ValidateIPaddress(document.getElementById('RemoteIp'))" id="RemoteIp" >
Remote VIP Port :
<input type= "text" name= "RemoteVIPPort" style= "margin-right:10px" value="5004" class="ip" onfocusout="ValidatePort(document.getElementById('RemoteVIPPort'))" id="RemoteVIPPort">
Now I want to use jquery selection to always check if there are some invalid input. Which is something like this but with my own design function.
$("input.ip:visible").filter(function() { return this.ValidateIPaddress === true }).addClass("invalid");
Anyone has idea bout it?
You're not calling ValidateIPAddress in your filter function, you're just testing whether the DOM element has a non-empty property named ValidateIPAddress. It should be:
$("input.ip:visible").filter(function() {
return ValidateIPAddress(this);
}).addClass("invalid");
Try this:
isIP(ip) {
if (typeof(ip) !== 'string')
return false;
if (!ip.match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)) {
return false;
}
return ip.split('.').filter(octect => octect >= 0 && octect <= 255).length === 4;
}
Original: https://stackoverflow.com/a/50612630/3261332
And if one needs to accept also CIDR format IP/{0-32} please update the 2 lines as below:
if (!ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/([0-9]|[12][0-9]|3[0-2]))?$/)) {
return ip.split('/')[0].split('.').filter(octet => octet >= 0 && octet <= 255).length === 4;
See if this help. This is valid fo IP4 only.
0.0.0.0 - Invalid
Any ip with CIDR is invalid
function validateIP(ip) {
is_valid = false;
ip = ip.replace(/\s+/, "");
if(ip.indexOf('/')!=-1){
alert("IP not valid");
return false
}
try {
var ipb = ip.split('.');
if (ipb.length == 4) {
for (i = 0; i < ipb.length; i++) {
b = parseInt(ipb[i]);
if (b >= 0 && b <= 255) {
is_valid = true;
} else {
is_valid = false;
break;
}
}
}
} catch (exception) {
alert("IP is not valid")
return false;
}
if (!is_valid) {
alert("IP is not valid")
return false;
}
return true;
}

How to write simplified and generic validation logics and rules in JQuery

I know there are tons of information out there over internet to validate form in JavaScript and JQuery. But I’m interested to write my own. Basically I want to learn this thing.
So here is my validation script I have written and its working fine.
function validate() {
var firstName = jQuery("#firstName").val();
var lastName = jQuery("#lastName").val();
var dateOfBirthy = jQuery().val("dateOfBirth");
if (firstName.length == 0) {
addRemoveValidationCSSclass("#firstName", false);
} else {
addRemoveValidationCSSclass("#firstName", true);
}
if (lastName.length == 0) {
addRemoveValidationCSSclass("#lastName", false);
} else {
addRemoveValidationCSSclass("#lastName", true);
}
}
function addRemoveValidationCSSclass(inputField, isValid) {
var div = jQuery(inputField).parents("div.control-group");
if (isValid == false) {
div.removeClass("success");
div.addClass("error");
} else if (isValid == true) {
div.removeClass("error");
div.addClass("success");
} else {
}
}
I want to achieve few things--
add validation message
More generic way to handle for every form.
And I want to add validation rule, like length, email validation,
date validation etc.
Now how can I achieve these?
Use jQuery validate. It does everything you want straight out of the box.
I did something similar to this, except that I wrote my rules in PHP since you need a server-side backup. When the PHP generates the form, it also generates some simple client-side validation that looks like this:
<!-- html field -->
<label for="first">
First Name: <input type="text" name="first" id="first">
<span id="first_message"></span>
</label>
Then the script is like this:
<script>
var formValid = true;
var fieldValid = true;
// Check first name
fieldValid = doRequiredCheck("first");
if (!fieldValid) {formValid = false};
fieldValid = doCheckLength("first", 25);
if (!fieldValid) {formValid = false};
function doRequiredCheck(id) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value === "") {
box.innerHTML = "**REQUIRED**";
}
}
function doCheckLength(id,len) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value.length > len) {
box.innerHTML = "Too long";
}
}
</script>
Create a simple function:
function validations(day, hour, tap1, tap2, employed){
if( day== "" | hour== "" | tap1== "" | tap2== "" | employed== "" ){
return false;
} else {
return true;
}

More efficient way of writing this javascript

I am creating a contact form for my website and and using javascript to the first layer of validation before submitting it which is then checked again via php but i am relatively new to javascript, here is my script...
$("#send").click(function() {
var fullname = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
if (fullname == ""){
$("input#fullname").css("background","#d02624");
$("input#fullname").css("color","#121212");
}else{
$("input#fullname").css("background","#121212");
$("input#fullname").css("color","#5c5c5c");
}
if (email == ""){
$("input#email").css("background","#d02624");
$("input#email").css("color","#121212");
}else{
$("input#email").css("background","#121212");
$("input#email").css("color","#5c5c5c");
}
if (subject == ""){
$("input#subject").css("background","#d02624");
$("input#subject").css("color","#121212");
}else{
$("input#subject").css("background","#121212");
$("input#subject").css("color","#5c5c5c");
}
if (message == ""){
$("textarea#message").css("background","#d02624");
$("textarea#message").css("color","#121212");
}else{
$("textarea#message").css("background","#121212");
$("textarea#message").css("color","#5c5c5c");
}
if (name && email && subject && message != ""){
alert("YAY");
}
});
How can i write this more efficiently and make the alert show if all the fields are filled out, thanks.
$("#send").click(function() {
var failed = false;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
var item = $(this);
if (item.val()) {
item.css("background","#121212").css("color","#5c5c5c");
} else {
item.css("background","#d02624").css("color","#121212");
failed = true;
}
});
if (failed){
alert("YAY");
}
});
glavic and matt's answers were exactly what I was going to suggest, except I would take it a step further by separating the logic from the presentation.
Have classes defined in your css for when a field contains an invalid entry, and add or remove that class using $.addClass() or $.removeClass()
Since you're using jQuery, I would recommend setting a class on each field that requires a non-blank value (class="required").
Then you do something like this:
var foundEmpty = false;
$(".required").each(function()
{
if($(this).val())
{
foundEmpty=true;
$(this).style("background-color", "red");
}
});
if(foundEmpty)
{
alert("One or more fields require a value.");
}
Giving them a common class, define classes to apply the styles, and do this:
JS
$("#send").click(function() {
$('.validate').attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( $('.invalid').length === 0 ) {
alert('YAY');
}
});
CSS
.valid {
background:#121212;
color:#5c5c5c
}
.invalid {
background:#d02624;
color:#121212;
}
HTML
<button id="send">SEND</button><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate">
JSFIDDLE DEMO
A little bit more efficient approach:
var validate = $('.validate');
$("#send").click(function() {
validate.attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( validate.filter('.invalid').length === 0 ) {
alert('YAY');
}
});
You can use jQuery to iterate over each object and get their values. Depending on your form, this code will change, but it's to give you an example. I'm probably missing a couple of brackets here and there but the concept is there.
var objectName=$(this).attr('id');
$('#formId').children().each(
function(){
if ($(this).value == ""){
$(this).css("background","#d02624");
$(this).css("color","#121212");
$error[objectName]='true';
}else{
$(this).css("background","#121212");
$(this).css("color","#5c5c5c");
$error[objectName]='false';
}
}
);
$.each(error, function(key, value){
if (value=='false'){
alert (key + 'is empty');
}
});
I would probably divide part of this up into my css file. If any of the fields are empty add a class like "empty" to the object, if not, remove it. Then in your css file you can add some descriptors like:
input#fullname,
input#email {
...
}
input#fullname.empty,
input#email.empty {
...
}
You can use jQuery addClass() and removeClass().
You can then add a loop as follows:
var inputs = new Array();
inputs[0] = "input#fullname";
inputs[1] = "input#email";
inputs[2] = "input#subject";
inputs[3] = "textarea#message";
var complete = true;
for (var i = 0; i < 4; i++) {
var value = $(inputs[0]).val();
if (value.length > 0) {
$(inputs[i]).removeClass("empty");
} else {
complete = false;
$(inputs[i]).addClass("empty");
}
}
if (complete) {
}
EDIT:
There you go, fixed it for you.

Categories

Resources