JavaScript function() is not a function - javascript

I have a strange error Or I'm being dumb and when I search for my error I don't get the answer I need.
I am trying to have some javascript run if a certain key "/" is pressed in a text box.
Here is the Code:
function ClockIn(){
var kb_press = event.keyCode;
if(kb_press == 47)
{
alert("you are clocking in");
if(document.ClockIn.status.value === "IN"){
alert("You Cant Clock in wile you are already Clocked in\n Please try again!")
document.ClockIn.tx_Barcode.value, document.ClockIn.status.value, document.ClockIn.name.value = "";
}
}
}
<form method="POST" name="ClockIn">
<lable>Type your BarCode <input type="text" name="tx_Barcode" id="tx_Barcode" class="tx_Barcode" onkeypress="ClockIn()" ></lable><br>
<lable>Is your Name? <input type="text" name="name"></lable><br>
<lable>You are currently Signed <input type="text" name="status"></lable><br>
</form>
My result is: ClockIn is not a function

The problem here is you've named your "ClockIn" form, so due to age-old quirks in how HTML interacts with JavaScript, the ClockIn form overwrites your global ClockIn function.
Maybe rename the form "ClockInForm"? Better yet, though, you might want to use document.getElementById("...") to refer to elements.

Related

How to detect if a specific string (email domain) is entered into an input to add/remove attribute/class from a button

So I know how to do the remove/add class/attribute from a submit button, but I need to be able to apply this to a button based off of entry into an input.
The scenario is this, user enters their email address, but if it's at a specific domain, ex: xxxx#troopers.gov I then want to be able to apply/remove the class, and attribute from the submit button, since this is a domain they are not supposed to enter for a registration.
I have done some similar validation in the past, and tried a few different methods in jQuery .val(), indexOf, etc. But still can't seem to get it working.
I tried something like
var badDomain = 'troopers.gov';
and then
if (!$('#input').val() === badDomain) {
doStuff();
}
but it didn't seem to get me anywhere.
I thought I may be able to do this without using a RegEx (I don't have much experience with that)
Would be nice to be able to account for case as well... and I don't mind if the solution is jQuery, or pure JS... for learning purposes, it would be great to see how I could do it both ways...
So this does what you want, by turning anything typed into the field in lower case and then comparing against a given array of bad strings. Any time the input field blurs, it checks and turns the submit on or off.
Take a look in the code to see some bad addresses for sample use.
var badDomains = [
"troppers.com",
"fooBarBaz.org",
"myReallyUselessDomainName.com",
"a.net"
]
$(function(){
$("#email").on("blur", function(){
var addressBad = false;
var thisEmail = $(this).val().toLowerCase();
for (var i=0; i<badDomains.length; i++){
if (thisEmail.includes(badDomains[i])){
addressBad = true;
}
}
if (addressBad) {
console.log("bad address!")
$(".disabledButton").attr('disabled', "disabled");
} else {
console.log("not a bad address!");
$(".disabledButton").removeAttr("disabled");
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
<input class="disabledButton" type="submit" disabled />
</form>
simple workaround :
var email = document.getElementById('email');
var checkEmail = document.getElementById('checkEmail');
checkEmail.onclick = function() {
if ((email.value).includes('#troopers.gov')) alert('This email address cannot be used!');
}
<input id="email">
<button id="checkEmail">Check Email</button>
there are multiple ways around though.
You can use a regex for this purpose.
HTML:
<input type="text" id="InputTest" />
<button id="TestBtn" type="button">
Validate
</button>
<p>
Valid
</p>
CSS:
.valid{
background-color:green;
}
.invalid{
background-color: red;
}
JS:
$("#TestBtn").on("click",function() {
var pattern = /\S+#troopers\.com/gi;
var str = $("#InputTest").val();
var arr = str.match(pattern);
alert(arr); // just to see the value
if(arr !== null){
$("p").addClass("invalid");
}
else{
$("p").addClass("valid");
}
});
Here is a JSFiddle. Basically, if what the user typed in the textbox matches the expression.. then the background color turns red, but if it doesn't match, then the background color turns green.
Let me know if this helps.
You can use the following Regex for the Email property of the related Model in order to accept mails having 'abc.com' suffix:
[RegularExpression("^[a-zA-Z0-9_#./#&+-]+(\\.[a-zA-Z0-9_#./#&+-]+)*#abc.com$",
ErrorMessage = "Please enter an email with 'abc.com' suffix")]

JQuery and HTML5 custom validation not working as intended

I just started learning JS, Jquery and HTML online. I have a question, and have tried doing things which were told in the answers of similar questions on SO, but it won't help.
I have a password form which only accepts input which have atleast 6 characters, one uppercase letter and one number. I wish to show a custom validation message which could just state these conditions again.
Here's my HTML code -
<div class="password">
<label for="password"> Password </label>
<input type="password" class="passwrdforsignup" name="password" required pattern="(?=.*\d)(?=.*[A-Z]).{6,}"> <!--pw must contain atleast 6 characters, one uppercase and one number-->
</div>
I'm using JS to set the custom validation message.
JS code
$(document).ready(function () {
$('.password').on('keyup', '.passwrdforsignup', function () {
var getPW = $(this).value();
if (getPW.checkValidity() === false) {
getPW.setCustomValidity("This password doesn't match the format specified");
}
});
});
However, the custom validation message doesn't show. Please help. Thank you so much in advance! :)
UPDATE 1
I changed the password pattern to (?=.*\d)(?=.*[A-Z])(.{6,}). Based on 4castle's advise, I realized there were a few errors in my javascript, and changed them accordingly. However, the custom validation message still doesn't show.
JavaScript:
$(document).ready(function () {
$('.password').on('keyup', '.passwrdforsignup', function () {
var getPW = $(this).find('.passwrdforsignup').get();
if (getPW.checkValidity() === false) {
getPW.setCustomValidity("This password doesn't match the format specified");
}
});
});
Again, than you all in advance!
First, update this:
var getPW = $(this).find('.passwrdforsignup').get();
to this:
var getPW = $(this).get(0);
...because $(this) is already the textbox .passwrdforsignup, you can't find it in itself!
The problem with setCustomValidity is, that it does only work once you submit the form. So there is the option to do exactly that:
$(function () {
$('.password').on('keyup', '.passwrdforsignup', function () {
var getPW = $(this).get(0);
getPW.setCustomValidity("");
if (getPW.checkValidity() === false) {
getPW.setCustomValidity("This password doesn't match the format specified");
$('#do_submit').click();
}
});
});
Please note the getPW.setCustomValidity(""); which resets the message which is important because if you do not do this, getPW.checkValidity() will always be false!
For this to work the textbox (and the submit-button) must be in a form.
Working JSFiddle
There are several issues going on here.
The pattern doesn't have a capture group, so technically nothing can ever match it. Change the pattern to (?=.*\d)(?=.*[A-Z])(.{6,})
$(this).value() doesn't refer to the value of the input tag, it's referring to the value of .password which is the container div.
getPW.checkValidity() and getPW.setCustomValidity("blah") are getting run on a string, which doesn't have definitions for those functions, only DOM objects do.
Here is what you should do instead (JS code from this SO answer)
$(document).ready(function() {
$('.passwrdforsignup').on('invalid', function(e) {
var getPW = e.target;
getPW.setCustomValidity("");
if (!getPW.checkValidity())
getPW.setCustomValidity("This password doesn't match the format specified");
}).on('input', function(e) {
$(this).get().setCustomValidity("");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="password">
<label for="password">Password</label>
<input type="password" class="passwrdforsignup" name="password"
required pattern="(?=.*\d)(?=.*[A-Z])(.{6,})" />
</div>
<input type="submit" />
</form>

Javascript run onChange not onLoad

I have a very simple piece of Javascript that works perfectly onLoad, but I need it to work onChange.
My script;
<form action="" method="post" name="product_search">
<p><strong>Existing Part Number:</strong>
<input name="v_prodref" type="text" id="v_prodref" size="25" maxlength="25" onChange="searchValue()">
<input type="text" name="prodref" id="prodref">
<input type="submit" name="search_Submit" id="search_Submit" value="Submit">
</p>
<div>
<%=(rs_ProductCheck.Fields.Item("prodref").Value)%>
// <%=(rs_ProductCheck.Fields.Item("proddesc").Value)%></div>
<script>
function searchValue() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref');
if(c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add) }
else {
n_ProdRef = c_ProdRef.replace(/GST/i,"NWGST") }
document.getElementById("prodref").value = n_ProdRef;
}
</script>
</form>
So, I enter a part number in the first text box, and I want my javascript to run and enter the new value in the second text box, but it doesn't seem to work.
What am I missing?
search does not exist on an HTMLInputElement. You need to use c_ProdRef.value.search.
(Actually, since you're using it in many places as a string, and never as an input, you probably intended to define c_ProdRef as var document.getElementById('v_prodref').value)
You would've seen this error on load as well.
you want onkeyup if it works perfectly onLoad, and you want to start typing in something in textbox 1 and the javascript to run, you dont want onchange
onchange triggers after blur of focused element
onkeyup triggers after you release a keyboard input
Thanks to everyone for their help. After a little tweaking I have managed to get my code working.
function myFunction() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref').value;
if (c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add)
} else {
n_ProdRef = c_ProdRef.replace(/GST/i, "NWGST")
}
document.getElementById("prodref").value = n_ProdRef;
}
Along with #indubitablee suggestion of onKeyup and specifying the .value of my first text field it all works.

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Validate specific input, Javascript

<form action="/cgi-bin/Lib.exe" method=POST name="checks">
<input type=checkbox name="user1" value="'$NAME'">
<input type=checkbox name="user2" value="'$NAME'">
<input type=checkbox name="user3" value="'$NAME'">
<input type="button" value="User 1" onclick="somefunction()">
For example, if I selected checkbox user2 I would want the javascript function to pop up saying "you are not user 1..." (all input check boxes are under same form name).
After validation of specific check box name I will do document.checks.submit();
Thanks.
I'd propose few improvements to sktrdie's reply.
This will avoid submitting form on errors.
<form action="".... onsubmit="return somefunction(this);">
function somefunction(f) {
var user1 = f.user1;
var user2 = f.user2;
// etc..
if(user2.checked) {
alert("you are not user1");
return false;
}
return true;
}
Note #1: this example is very simple and not-so-flexible, so additional reading on forms validation would be good idea. Say, on w3schools
Note #2: do not forget to implement server-side validation along with this. JS checks can be easily avoided.
<form onsubmit="somefunction(this);" ...
function somefunction(f) {
var user1 = f.user1;
var user2 = f.user2;
// etc..
if(user2.checked) alert("you are not user1");
}
You may want to use the checkbox's onclick event to do the validation... So when they click it to turn it on/off you can catch em immediately, before form submission.
<input type=checkbox name="user1" value="'$NAME'" onclick="javascript:validatecheckbox(document.checks.user1);">
And then whatever you want to validate against in the JS function: (sorry for some reason the encoding of this code isn't working right... but hopefully you get the idea)
<script language="javascript">
function validatecheckbox(inputbox) {
if (inputbox.checked)
alert ('Are you ' + inputbox.name + '?');
}
</script>

Categories

Resources