Validation on a JS function - javascript

I have a list of people that are being added via a search. Everything works, but there's one case where if you don't select a person from this list, you get an ugly 400 page. Obviously it's because I'm not handling the validation there.
My "remove from list" button is done this way:
<input type="button" value="Remove" onclick="delTeamNominee(document.f.teamList.value)"/>
Here's my function:
function delTeamNominee(id) {
document.dl.empId.value = id;
document.dl.submit();
}
dl is a hidden form that executes a Spring MVC method:
<form name="dl" action="teamDeleteEmployee" method="post">
<input type="hidden" name="empId">
</form>
Obviously I would like to do something like this:
function delTeamNominee(id) {
if (id == null) {
alert("You must select a person");
} else {
document.dl.empId.value = id;
document.dl.submit();
}
}
Which of course, doesn't work.

Perhaps you should also check to see if id is undefined. Something like the following will catch both null and undefined:
if (!id) {
....
}

Related

onclick() and multiple depending function calls

This code is what i got so far:
<html>
<head>
<script>
function confirmer(what) {
var retVal = confirm("Do you want "+what+"?");
if( retVal == true ) {
document.write ("User wants "+what);
return true;
} else {return false;}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="confirmer('a'); confirmer('b'); confirmer('c')" value="Result">
</form>
The user should be able to choose between a, b or c. Sometimes it's only a and b (the confirmer-functions-calls are written with PHP dynamically).
The problem is: Even if the user chooses an option it calls the following function but it should break/stop/end and not asking for another confirm.
You can simplify your code a bit so that you only have to make a single function call. You can achieve this by hard-coding your options into your function, instead of hard-coding them in the inline HTML. For example:
function confirmer() {
console.clear();
var options = ['a', 'b', 'c'];
var option;
while (options.length) {
option = options.shift();
if (confirm(`Do you want ${option}?`)) {
console.log(`User wants ${option}`);
return true;
}
}
console.log('User does not want any option');
return false;
}
<input type="button" onclick="confirmer()" value="Result">
You need to check the result of each method call in order to decide if you should move on to the next one.
The following is a version of your code that will do just this.
<input type="button" onclick="if (!confirmer('a')) { if (!confirmer('b')) { confirmer('c'); } }" value="Result">
If you cannot modify the output from the PHP, then you can use a global variable to prevent the other confirmations from executing.
var confirmed = false; // global variable
function confirmer(what) {
if (!confirmed) {
var confirmed = confirm("Do you want "+what+"?");
if (confirmed) {
document.write ("User wants "+what);
}
}
}
Though this would require you to reset that global variable in order to run the code again without a page refresh. So your input might look something like this:
<input type="button" onclick="confirmer('a'); confirmer('b'); confirmer('c'); confirmed=false;" value="Result">
Notice that confirmed=false; was added at the end of the code generated by PHP.

How to correctly validate form with jQuery?

So I have this jQuery for my form:
frm.submit(function(event) {
validateForm();
if(validateForm()) {
$(this).submit();
} else {
event.preventDefault();
}
});
It does sort of work, but I get JS <error> (and it doesn't say anything else in the console about it), I think the reason is that the function has to go through the validation again? Kind of like a circular dependency.
Can you show me a better way to do the exact thing that I'm trying to achieve here please?
Validate and show errors if filled in the wrong way;
Submit the form if everything is ok
Something like this maybe?
HTML -
<input type="text" id="name" />
<input type="tel" id="phone" />
<button type="button" id="submit">Submit</button>
<div id="errors"></div>
JS -
const user = {}
$('#submit').click(function(){
// validating form
if(!$('#name').val()) {
$('#errors').text('invalid value in "name" field')
return;
}
if(!$('#phone').val()) {
$('#errors').text('invalid value in "phone" field')
return;
}
$('#errors').text('');
user.phone = $('#phone').val();
user.name = $('#name').val();
// form submission goes here
});
Logic -
Once a function returns, the execution of anything else after the return expression itself, is prevented.
If you don't return anything, the interpreter will continue to the next expression.
This gives you the option of manipulating elements and handle errors just before returning and stopping the function from continuing to run.
function validateForm(){
if (input.val().isok && select.val().ispresent){
form.submit();
}else{
show_errors();
}
}
why not that way?

passing a simple variable in javascript (form)

I am an inexperienced web developer writing a registration form using JS for client-side validation and PHP for server-side. I am stuck trying to just test a variable and make sure that it is getting passed to JS. I heard that jsfiddle doesn't like forms, so I restructured my fiddle code to not include any form tags. The code does not do anything when I run it. Can someone help please? Also, should I install Apache to test the form locally or would Chrome be able to handle it? I know that I'll have to eventually to test PHP, but I'm just trying to get JS validation to work right now.
http://jsfiddle.net/5JT94/
HTML:
<p>Zip Code: <input type="text" name="zipbox"></p>
<p><input type="submit" name="submit" onClick="formValidation()" value="Submit" /></p>
JS:
function formValidation()
{
var zip=document.getElementById("zipbox");
function allnumeric(zip)
{
var numbers = /^[0-9]+$/;
if(zip.value.match(numbers))
{
alert("Everything OK");
}
else
{
alert("Numbers only please");
}
};
};
You weren't executing the function on the zip that you found.
var zip=document.getElementById("zipbox");
allnumeric(zip);
http://jsfiddle.net/5JT94/1/
And in case you don't want to add an id (can't see why):
Demo: JSFiddle
HTML
<form name="zipform">
<p>Zip Code: <input type="text" name="zipbox" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
JS
function formValidation() {
var zip=document.forms["zipform"].elements["zipbox"];
var numbers = /^[0-9]+$/;
if(zip.value.match(numbers)) {
alert("Everything OK");
} else {
alert("Numbers only please");
return false;
}
return true;
}
document.forms["zipform"].elements["submit"].onclick=formValidation;
One of the problems may relate to how jsfiddle works. I had to add "window.formValidation = formValidation" so that the formValidation function you defined in the onClick would be found. Second, you had an allnumeric function but it wasn't being called.
function formValidation()
{
var zip=document.getElementById("zipbox");
function allnumeric(zip)
{
var numbers = /^[0-9]+$/;
if(zip.value.match(numbers))
{
alert("Everything OK");
}
else
{
alert("Numbers only please");
}
};
allnumeric(zip);
};
window.formValidation = formValidation
your element does not have an id ? change like below
<input id="zipbox" type="text" name="zipbox">
then debug from there

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 :)

Javascript form validation: how to force focus to remain on 'incorrect' field?

I can't believe that I can't find the answer to this question but I really have searched and can't find it! honest!
anyway - here is the question: I am trying to create a validation function for a form that will not permit the user to proceed to the next form field if the field doesn't validate.
I just want the 'incorrect' field to have focus until it is 'correct'.
because this is for a JS class I cannot use jQuery or any other framework.
here is one of the HTML fields:
<li>Number 1:<input class="field2" type="text" id="star1" onchange="validateAndDraw(this.value);"></li>
and here is a truncated version of the JS function:
function validateAndDraw(theValue) {
if (isNaN(theValue)) {
alert("no good");
} else {
[do stuff here]
}
}
I have tried using 'this.focus();' and 'this.parentNode.focus();' but no joy.
I am sure the answer is ridiculously simple, but I can't seem to find it.
thanks,
bennett
Try sending the object reference to the function instead of the value.
So in your input event:
validateAndDraw(this);
And change your function to:
function validateAndDraw(input) {
if (isNaN(input.value)) {
alert("no good");
input.focus();
} else {
[do stuff here]
}
}
As a side, I would suggest looking into Progressive Enhancement.
document.getElementById('star1').focus();
Using this inside your function will refer back to the function.
Alternatively, you could pass the object in the onclick event:
<input class="field2" type="text" id="star1" onchange="validateAndDraw(this);">
so the function could look like
function validateAndDraw(obj) {
alert(obj.value);
}
Try calling focus() in the blur event.
Also, this in your function refers to the global context, not the element.
(It only refers to the element inside the inline handler; you are making an ordinary function call from there)
You should change your function to accept the element as a parameter (which you can pass as this insidethe inline handler)
Why not pass in the element?
function validateAndDraw(theElement) {
var theValue = theElement.value;
if (isNaN(theValue)) {
alert("no good");
theElement.focus()
} else {
[do stuff here]
}
}
Send as trigger
There are for each loop function for check input in form.
If there are input[x].value = "", so alert and focus in it, next input and next alert
<html>
<body>
<form onsubmit="return validateForm(this)">
Name: <input type="text" name="name"><br />
E-mail: <input type="text" name="email"><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Send">
</form>
<script >
function validateForm(input) {
for (x in input) {
if (input[x].value == "") {
alert(input[x].name + " must be filled out");
input[x].focus();
return false;
}
}
}
</script>
</body>
</html>

Categories

Resources