JS validation, why this code won´t work? - javascript

I can´t get the validation in JS, and don´t understand why it doesn´t work.
The user should get an alert if at least one of the checkboxes isn´t checked.
It doesn´t work, because the form gets submitted ok even if if none checkboxes are checked.
<body>
<script>
function validar()
{
var s1=document.getElementById('s1');
var s2=document.getElementById('s2');
if (s1.value==''||s2.value=='')
{
alert("You must check at least one!");
return false;
}
}
</script>
<form name="calcular" onsubmit="return validar()" method="post">
<input type ="checkbox" name="servicios[]" id="s1" value="sinservicios">Sin servicios<br>
<input type ="checkbox" name="servicios[]" id="s2" value="dosservicios">Dos servicios<br>
...

You may try using the checked property to ensure that at least one of the 2 checkboxes is checked:
<script>
function validar() {
var s1 = document.getElementById('s1');
var s2 = document.getElementById('s2');
if (!s1.checked && !s2.checked) {
alert('You must check at least one!');
return false;
}
return true;
}
</script>
Also notice we should return true in case the validation succeeds.
The reason why your code doesn't work is because you have used the value property. That's always gonna return the value attribute of your checkbox (sinservicios or dosservicios) no matter if the user checked or not this checkbox. It will never return an empty string which is what you seem to be testing for in your if condition.

Related

I have two checkboxes that need to be checked before the form may be submitted

<input type="checkbox" value="On" name="policy" id="policy"></font>
<b><font face="Verdana" color="#ff0000" size="1">*</font></b>By checking the box, you are verifying with your digital signature that you have read and agree to all terms and conditions of the FEG agent agreement.
</td>
</tr>
<tr class="gr">
<td class="rowdot_lno">Do you agree?:</td>
<td class="rowdot_lno">
<input type="checkbox" value="On" name="iagree" id="iagree">
<b><font face="Verdana" color="#ff0000" size="1">*</font></b>I understand that I will be charged $24.95.
</td>
</tr>
I have a <form method="post" action="enroller.dhtml" name="mainform" onSubmit="update_prices()"> and a button <input type="submit" value="Continue">
I've tried a few things but to no avail. The form can be submitted without the checkboxes being checked. Here's the latest bit of jQuery I've tried.
$('input[type=checkbox]').each(function () {
if($(this).is(':checked')) {
return true;
}
});
alert("Please select at least one to upgrade.");
return false;
});
Also I found this on fiddle but it's not really working.. I tried to customize it to my needs.
http://jsfiddle.net/shryme/D3Ldj/
If you have an onSubmit on your submit button or add it though jquery, call a function which would :
if ($('input[type=checkbox] :checked').length == 0) {
alert("Please select at least one to upgrade.");
return false;
} else { return true; }
I hope this is what you are looking for.
From this line:
Please select at least one to upgrade
It seems that you need at least one checkbox checked. If that is the case, you could do something like this:
$("form").submit(function(){
var length = $("input[type=checkbox]").not(":checked").length;
if (length > 1) {
alert("Please select at least one to upgrade.");
return false;
}
});
Which checks to see how many checkboxes are not checked, determines if that number is less than the required number, and if it is, triggers the error message.
You can also further simplify the length variable if you are comfortable with CSS selectors:
var length = $("input[type=checkbox]:not(:checked)").length;
Here's an example.
I would suggest to do it with some MVVM framework but here's some code to do it with jQuery. I made it so that the submit button is disabled unless both boxes are checked.
Fiddle with 2 checkboxes and a submit button
function areChecked(){
var is_1_checked = $('#check_1').is(':checked');
var is_2_checked = $('#check_2').is(':checked');
return is_1_checked == is_2_checked == true;
}
function enableButton(val){
$('#submit').attr('disabled', false);
}
$('#check_1').on('click', function(){
if (areChecked())
enableButton(false);
});
$('#check_2').on('click', function(){
if (areChecked())
enableButton(false);
});

make a field mandatory using javascript

I am trying to make a select field mandatory on a web page. I know how to do it with help of JS and form attribute 'onsubmit' and returning the function. But the problem is that form code is already written and I dont know how to add attribute now. Let me know if I can append attribute dynamically from JS.
The other way I tried is to call the JS after page loaded. But this isnt making the field mandatory and form can be submitted.
Following is my code..
<!DOCTYPE html>
<html>
<head>
<script>
function f1()
{
var countryValue = document.getElementById('count ID').value;
if (countryValue == "")
{
alert("field value missing");
return false;
}
var stateValue = document.getElementById('state ID').value;
if (stateValue == "")
{
alert("state field value missing");
return false;
}
}
</script>
</head>
<body>
<form method = "post" action = "33.html">
Country: <input type="text" id="count ID">
state: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
<br>
<input type = "submit">
</form>
<script>window.onload=f1</script>
</body>
</html>
Please help.
Have a look at this since you have messed up the IDs
Live Demo
window.onload=function() {
document.forms[0].onsubmit=function() { // first form on page
var countryValue = this.elements[0].value; // first field in form
if (countryValue == "") {
alert("Please enter a country");
return false;
}
var stateIdx = this.elements[1].selectedIndex; // second field
if (stateIdx < 1) { // your first option does not have a value
alert("Please select a state");
return false;
}
return true; // allow submission
}
}
PS: It is likely that POSTing to an html page will give you an error
To get the last button to do the submission
window.onload=function() {
var form = document.forms[0]; // first form
// last element in form:
form.elements[form.elements.length-1].onclick=function() {
...
...
...
this.form.submit(); // instead of return true
}
}
Once you've got a function to detect improper values (empty mandatory field or anything else, like a bad e-mail address for instance) you have a few different options :
disable the submit button
cancel the onclick event on the button
cancel the submit event on the form
disabling the submit button can be annoying for the user (it might flash on and off while the values are entered).
I had the same issue, but i made a extension. Using hook system to translate fields with "*", in the names, to validate like required field. This is a simple solution not intrusive where is not required addition of fields in the database, only by the use of sufix "*" in configuration of custom fields.
There is the code: https://github.com/voiski/bugzilla-required-field

How to ensure my confirm checkbox is ticked before allowing submission of my form

Once again the novice JS is back again with a question. I want a confirmation tickbox at the end of my form before allowing the user to send me their details and if it's not ticked then they can't submit the form. I've had a look on here and tried using different examples of coding but I just find it all very confusing after looking at 10 or 20 pages of different code. Here is what I've written so far, from what I can make out my form just skips over my checkbox validation code which is obviously what I don't want to happen:
<head>
<script>
function validate (){
send = document.getElementById("confirm").value;
errors = "";
if (send.checked == false){
errors += "Please tick the checkbox as confirmation your details are correct \n";
} else if (errors == ""){
alert ("Your details are being sent)
} else {
alert(errors);
}
}
</script>
</head>
<body>
<div>
<label for="confirm" class="fixedwidth">Yes I confirm all my details are correct</label>
<input type="checkbox" name="confirm" id="confirm"/>
</div>
<div class="button">
<input type="submit" value="SUBMIT" onclick="validate()"/>
</div>
I would just enable/disable your button based on the checkbox state. Add an ID to your button, (i'll pretend the submit button has an id of btnSubmit)
document.getElementById("confirm").onchange = function() {
document.getElementById("btnSubmit").disabled = !this.checked;
}
Demo: http://jsfiddle.net/tymeJV/hQ8hF/1
you are making send be confirm's value.
send = document.getElementById("confirm").value;
This way send.checked will not work. Because you are trying to get the attribute checked from a value (probably, string).
For the correct use, try this:
send = document.getElementById("confirm");
sendValue = send.value;
sendCheck = send.checked;
Then you can test with
if (sendCheck == false){ //sendCheck evaluate true if checkbox is checked, false if not.
To stop form from submitting, return false; after the error alerts.
Here the complete code - updated to work correctly (considering the <form> tag has id tesForm):
document.getElementById("testForm").onsubmit = function () {
var send = document.getElementById("confirm"),
sendValue = send.value,
sendCheck = send.checked,
errors = "";
//validate checkbox
if (!sendCheck) {
errors += "Please tick the checkbox as confirmation your details are correct \n";
}
//validate other stuff here
//in case you added more error types above
//stacked all errors and in the end, show them
if (errors != "") {
alert(errors);
return false; //if return, below code will not run
}
//passed all validations, then it's ok
alert("Your details are being sent"); // <- had a missing " after sent.
return true; //will submit
}
Fiddle: http://jsfiddle.net/RaphaelDDL/gHNAf/
You don't need javascript to do this. All modern browsers have native form validation built in. If you mark the checkbox as required, the form will not submit unless it is checked.
<form>
<input type="checkbox" required=""/>
<button type="submit">Done</button>
</form>

Strange behavior of javascript &&

I am using below method for validating that one of radio button must be selected.
function validateForm(){
var searchType = document.getElementsByName("form1:searchType");
var a = !(searchType[0].checked);
var b = !(searchType[1].checked);
if(a&&b){
alert('Please select search type');
return false;
}
return true;
}
In above method searchType is radio button which is creating two buttons. It works fine that is shows alert message if none of the two radio buttons are selected but it show alert message even when second of the radio button is selected. Any idea please?
<html>
<head>
<script language="javascript">
function validateForm(){
var searchType = document.getElementsByName("form1:searchType");
var a = !(searchType[0].checked);
var b = !(searchType[1].checked);
if(a&&b){
alert('Please select search type');
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form1">
<input type="radio" name="form1:searchType" /> male
<input type="radio" name="form1:searchType" /> female
<input type="submit" name="submit" value="submit" onclick="validateForm()" >
</form>
</body>
</html>
i am using your function in this code and its working fine, it may help you
You need to use the or operator, not and - when using && it will be true only when both conditions are true - when one of them is false the whole statement is false as well.
So, just change to:
if(a || b){
alert('Please select search type');
return false;
}
And it should do what you want.
Edit: sorry, got confused myself with the boolean logic.
From quick test your code does work exactly as-is: only when no checkbox is ticked the alert shows up.
Please explain what is the problem and steps to reproduce in the jsFiddle if possible and we'll see.

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

Categories

Resources