changing class with onkeypress - javascript

I'm learning javascript and i'm using bootstrap so i don't really have to worry about css.
I have a form group and i want to add class as the user inputs something. Here's my code:
<div class="form-group" id="loginForm">
<label for="inputLogin" class="pull-left">Login</label>
<input type="text" class="form-control" id="inputLogin" placeholder="Enter login" onkeypress="changeToGreenBorder('loginForm','inputLogin')">
</div>
and it's calling those functions:
function changeToGreenBorder(string,string2){
var tag = getElement(string);
var tag2 = getElement(string2);
if (tag2.innerHTML.length > 6) {
tag.setAttribute('class','form-group has-success');
} else if({
tag.setAttribute('class','form-group has-error');
}
}
function getElement(string){
var doc = document;
return doc.getElementById(string);
}
It's working with the error class, but when it has more then 6 letters, it doesn't switch to success class. How can i solve this?

You had a lingering ( and a Else If without a condition so I'm thinking you don't need a Else If
You were also trying to get the lenght of the innerHTML when what you really wanted was the lengthof the elements' value;
Working JSFiddle

Related

Make sure I'm selecting and running through all elements for an "each" statment

I'm trying to create a script that keeps our main button disabled until specific field requriments are met.
jQuery(document).ready(function() {//check if all are filled else disable submit
var inputFields = jQuery('#list-item-cc input, #field_28_50 input,#field_28_18 input');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if (jQuery(this).val().length == 0) {
empty = true;
}
});
if (empty) {
jQuery('#gform_submit_button_28').attr('disabled', 'disabled');
} else {
jQuery('#gform_submit_button_28').removeAttr('disabled');
}
I'm having trouble thinking of a way to ensure my inputFields variable can be passed to my inputFields.each(function() in a way that would allow the loop.
We're not worried about all input fields. Just the specific inputs in our inputFields variable.
Is this an effective way to ensure a button is disabled if certain fields are not filled out and can I create the selector in the way that i did and use that in an each statement?
Looks like you are using gravity forms? In that case I would add a css class to each field that you want to validate. That way you don't have to go searching for ID's and change the code for multiple forms.
https://docs.gravityforms.com/css-ready-classes/
Here is a fiddle in which I pretend that I added "ensure-filled" to each item in the gravity forms builder
https://jsfiddle.net/dokLz4hm/3/
Also note that I added a .trim() to the value so that blank spaces aren't counted as input and made the submit button generic so it would work with any field in a form that contains the ensure-filled class
Html
<div>
<div id="arbitraty_id_1">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_2">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_3">
<input type="text" class="ensure-filled" />
</div>
<input type="submit" value="submit" disabled>
</div>
JS
$(document).ready(function() {
var inputFields = $('.ensure-filled');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if ($(this).val().trim().length == 0) {
empty = true;
}
});
$('input[type="submit"]').attr('disabled', empty);
})
})

How to call multiple functions with DOM and Javascript

I'm working on an assignment and need to validate multiple inputs. I have created multiple functions and am having trouble calling each one. The first one is the only one that will call. The other two will just hang and do nothing.
If I do a single function call for oninput at the form tag it works. Just that it automatically calls the function and all validations. This causes all the prompts to come out at the same time which I don't want. This is why the oninput call is being done at the input tag.
HTML:
<div id="nameValidate"></div>
<label for="name">Name:</label>
<input type="text" id="nameID"
oninput="nameValidation()"/> <br />
<div id="emailValidate"></div>
<label for="email">Email:</label>
<input type="text" id="emailID"
oninput="emailValidation()"/> <br />
<div id="phoneValidate"></div>
<label for="phone">Phone Number:</label>
<input type="number" id="phoneID"
oninput="phoneValidation()"/>
Javascript
function nameValidation() {
var name = document.getElementById("nameID").value;
if (name.length < 3) {
document.getElementById("nameValidate").innerText = "Please
enter your full name.";
}
else if (name.length > 3) {
document.getElementById("nameValidate").innerText = "";
}
}
function emailValidation() {
var email = document.getElementById("emailID").value;
if (!email.match(".com") && email < 5) {
document.getElementById("emailValidate").innerText = "Please
enter your full email address.";
}
else {
document.getElementById("emailValidate").innerText = "";
}
}
function phoneValidation() {
var phone = document.getelementbyid("phoneID").value;
if (phone == "" || phone.length < 10) {
document.getelementbyid("phoneValidate").innertext = "please
enter your full phone number.";
}
else if () {
document.getelementbyid("phoneValidate").innertext = "";
}
}
Let's back up a minute and break some very bad habits that someone who doesn't know any better is teaching you.
Do not set up events using inline HTML event attributes (ie. onclick). This is a 25+ year old technique that persists today because people just copy/paste it and it seems to work in many cases. However, there are a number of very good reasons not to use this ancient technique that just will not die. Separate your JavaScript from your HTML and use modern, standards-based approaches to event handling with .addEventListener().
You've also mis-capitalized .getElementById() when you were getting the phone data and this would cause an error in your code that would prevent it from continuing. Always work with your developer tools (F12) open and the Console tab showing as this is where error messages will appear.
Next, only query the DOM once for elements that you'll need over and over. This means remove all the document.getElementById() lines from inside the functions and move them so they just get executed only once.
And, don't make references to properties of DOM elements, make the references to the element itself. This way, you scan the document just once to get the element reference, but then you can get any property you like when you need it without having to scan the document for the same element again.
Next, don't use .innerText as it is non-standard. Use .textContent instead.
And, don't use self-terminating tag syntax (ie.<br />, <input />). Here's why.
So, here's what your code should look like:
// Get references to the elements you'll be working with just once
var userName = document.getElementById("nameID");
var nameValidate = document.getElementById("nameValidate");
var email = document.getElementById("emailID");
var emailValidate = document.getElementById("emailValidate");
var phone = document.getElementById("phoneID");
var phoneValidate = document.getElementById("phoneValidate");
// Set up your event handlers in JavaScript, not HTML
userName.addEventListener("input", nameValidation);
email.addEventListener("input", emailValidation);
phone.addEventListener("input", phoneValidation);
function nameValidation() {
if (this.value.length < 3) {
nameValidate.textContent = "Please enter your full name.";
} else {
nameValidate.textContent = "";
}
}
function emailValidation() {
// Check the last 4 characters of the input
if ((this.value.substr(this.value.length - 4) !== ".com") && email.value.length < 5) {
emailValidate.textContent = "Please enter your full email address.";
} else {
emailValidate.textContent = "";
}
}
function phoneValidation() {
if (phone.value == "" || phone.value.length < 10) {
phoneValidate.textContent = "please enter your full phone number.";
} else {
phoneValidate.textContent = "";
}
}
<div id="nameValidate"></div>
<label for="name">Name:</label>
<input type="text" id="nameID"> <br>
<div id="emailValidate"></div>
<label for="email">Email:</label>
<input type="text" id="emailID"> <br>
<div id="phoneValidate"></div>
<label for="phone">Phone Number:</label>
<input type="number" id="phoneID">
Finally, as a professional technology trainer for over 25+ years, I would strongly advise you to inform whoever is teaching you these outdated techniques that they are doing you and anyone else they are teaching a disservice. Modern web development is hard-enough without having to unlearn bad habits brought on by those who don't know any better.
Firstly, your elseif has brackets but the condition is empty. Check your console, it should be showing a syntax error because:
} else if () {
document.getelementbyid("phoneValidate").innertext = "";
}
is not valid syntax. Turn it into an else.
Secondly, the function:
document.getelementbyid("phoneValidate").innertext = "";
does not exist on document, however, getElementById does.
Finally, ensure that you use the console to help you debug your code.

JQuery Not Triggering On Button.click

I've written some code that should check a textbox (ID tfa_1) to see if its empty or contains text, this should trigger on a next page button (wfpagenextID6) being clicked.
I've tried replacing my script with an alert("test.") and it dosent appear, so im assuming I have my trigger wrong but I cannot work out what I have done wrong!
My HTML that defines the textbox is below:
<input type="text" id="tfa_2685" name="tfa_2685" value="" placeholder="" title="Previous Surname (if applicable) " class="">
and the button is
<input value="Next Page" type="button" class="wfPageNextButton" wfpageindex_activate="7" id="wfPageNextId6" style="visibility: visible;">
Both of these are generated and I cannot change them!
My Script is:
<script>
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inp.Val= $("#tfa_2685").val();
if (inp.val().length > 0) {
alert("Test.");
}
});
})
</script>
An identifier ( variable ) must not contains dots. ( see more details ECMAScript specification in section 7.6 Identifier Names and Identifiers)
the next variable declaration is wrong
var inp.Val= $("#tfa_2685").val();
to fix this
var inp = $("#tfa_2685");
if you want to assign value to inp variable, you should just do: var inp = $("#tfa_2685").val();
And then call to inp.val() just replace with inp, for inp is not jQuery object so it doesn't have val() method
You have syntax, try this:
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inpVal= $("#tfa_2685").val();
if (inpVal.length > 0) {
alert("Test.");
}
});
});
https://jsfiddle.net/cua40s80/

Calling jQuery functions on inputs in Bootstrap Modal

I have a couple of jQuery functions that validate an input field according to a regex. When I have a form embedded on a page, they work fine. However, when I try to use them inside of a Bootstrap Modal they do not work.
Any ideas?
<input class="form-control input-lg validate-email" id="email" name="email" minlength="2" type="text" placeholder="Email">
$('.validate-email').on('input', function() {
var input = $(this).val();
var regex = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
var is_email = regex.test(input);
if(is_email){
$(this).removeClass("invalid").addClass("valid");
} else{
$(this).removeClass("valid").addClass("invalid");
}
});
Once again, this code works when the form is on a page, but not when the form is in a Bootstrap Modal.
One more detail, the valid and invalid are CSS classes that change the background-color of the field to change. If I skip the jQuery and just hardcode an invalid class in the <input> it shows the invalid class. So I know it is the jQuery.
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}

jscript 'type' attribute

Im trying to implement the following logic on javascript.
If type is 'bankAccountTypeId' get all fields with the same className as field using $(field.className) then use .each to loop through each result compare field.value with $(this).val() and use alert to show an error message if they are different (break if fail).
function onChange_productListField(field, type) {
if (HimmsJSUtil.elementHasClass(field, 'DC')) {
var allProductGroupFields = $(".DC."+type);
var value = field.value;
if (field.options) {
value = HimmsJSUtil.getSelectedDropDownOption(field);
}
allProductGroupFields.each(function(index) {
if ($(this).attr("id") != field.id
&& !$(this).val()) {
$(this).val(value);
}
});
} else {
/* implement the logic here */
}
}
My question is , how would the type attribute work, within this logic?
Firsly let's make clear that jscript is not javascript and "type" in your code is not attribute but just a parameter of the function.
var allProductGroupFields = $(".DC."+type);
The above line uses jQuery to select a group of elements having classes "DC" and "bankAccountTypeId" at the same time where type is "bankAccountTypeId". Such a code can be used in a structure like this:
<div class="whatever">
<input type="text" class="DC bankAccountTypeId" />
<input type="text" class="DC userId" />
<a href="http://stackoverflow.com/questions/1041344">
jQuery multiple class selector
<a>
</div>
Extra:
For a structure like this
<div class="DC">
<input type="text" class="bankAccountTypeId" />
<input type="text" class="userId" />
<a href="http://stackoverflow.com/questions/3767512">
jQuery class within class selector
<a>
</div>
the selector line must be changed to
var allProductGroupFields = $(".DC ."+type);

Categories