My goal is user require to choose at least one option from 2 check boxes and 2 text boxes. If user do not select anything, the system will prompt the user to select at least one.
However, right now, the user need to select everything which is not what I want.
Below are my codes..
Help will be appreciate..Thanks! :)
At index.jsp
<form method="post" name="searchform" onsubmit="return validateForm();">
Date: <input name="date" readonly="readonly" />
Number: <input type="text" name="on">
<input type="checkbox" id="completed"> Option A
<input type="checkbox" id="pending"> Option B
<input type="submit" value="Submit">
</form>
At javascript
function validateForm() {
var radio1 = document.getElementById('pending').checked;
var radio2 = document.getElementById('completed').checked;
var on = document.forms["searchform"]["on"].value;
var date = document.forms["searchform"]["date"].value;
if ((radio1 == "") || (radio2 == "") || (on == null || on="") || (date == null || date =="")){
alert('Please Choose at least 1 Option');
return false;
}
}
simply change your outer || to &&
if ((radio1 == "") && (radio2 == "") && (on == null || on="") && (date == null || date =="")){
alert('Please Choose at least 1 Option');
return false;
}
Try this one
if (((radio1 == "") && (radio2 == "")) &&(on == null || on="") && (date == null || date =="")){
alert('Please Choose at least 1 Option');
return false;
}
Related
I have three selectors and currently if anyone of them is not selected, the alert message is "Please fill in the fields".
However, I want to customize the alert.
Suppose out of 3 only 1 selector is not selected - say "dimension" than how can I amend the alert to " Please fill in the field - Two".
My current code is:
if (
checkforNullEmptySelect("group")
&& checkforNullEmptySelect("one")
&& checkforNullEmptySelect("two")
&& checkforNullEmptySelect("three")
) {
// alert("Values filled in correctly");
formValid = true
getData();
return true;
} else {
alert(alertMessageArr.correctFields);
return false;
}
I am assuming your HTML structure to be as given below:
<input id="one" type="text"/>
<input id="two" type="text"/>
<input id="three" type="text"/>
Snippet to check fields are empty or not:
if(inputOne === 0 && inputTwo === 0 && inputThree === 0){
alert("Please fill all fields");
}else{
$('input').each(function() {
if ($(this).val() != '') { //Or $(this).length > 0
alert('all inputs filled');
}
else{
alert('theres an empty input'); //alert selectors if needed
return false
}
});
}
You can concatenate the selector by using "+" operator or `` if you are using es6.
// ES5 ->
alert('Please fill out the fields - ' + selector);
//ES6 -> alert(`Please fill out the fields - ${selector}`);
I've been trying to use the following javascript code to validate several fields on a contact form. The validation works for the first item being validated, the name field, but not the second, the email field. If the name field is filled in, the validation seems to skip over the email field check when it's blank and the form submits.
function validateForm()
{
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
else if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
else
{
return( true );
}
}
Here is the HTML on the contact form:
<FORM name="contact" METHOD="POST" ACTION="thankyou.php" onsubmit="return validateForm()">
<input type="checkbox" name="newsletter" value="YES" width="30" height="30"> Check the box to subscribe to Herb's Newsletter
<input type="text" class="form-control" size=20 name="name" placeholder="Your name" />
<input type="email" class="form-control" name="email" placeholder="Email Address" />
<input class="btn btn-theme btn-subscribe" type="submit" value="Send" />
</form>
Thank you
You seem to be using empty function in your if clauses which doesn't seem to be defined nor it is part of the standard javascript functions. Try getting rid of it:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "") {
alert("Please enter your name.");
document.contact.name.focus();
return false;
} else if (ema == null || ema == "") {
//Check if the email is missing
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
} else {
return true;
}
}
And here's a live demo.
In your code you use else if statement.
Basically what you code does is:
check name -> if that is falsy check email -> if that is falsy move into else condition.
But when the name is true, the if statement will not move to else conditions because it it already satisfied. So if you want to check both, you either separate the statements and make a 5 separate ifs, make it a switch statement or you create one long check. For example:
if ((n == null || n == "" || empty(n)) || ( ema == null || ema == "" || empty(ema) ))
{
alert("Something is missing");
return false;
}
else
{
return( true );
}
or you use multiple ifs:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
return( true );
}
The latter will always return true unless one of the if statements is triggered.
And see answer below about the empty() thing. I don't know what that is and if it messes anything up.
I have 4 radio button in my form, once i submit the form any of the radio button should checked, if not a alert message will be displayed. its working properly in chrome, firefox, but in ie one i checked the radion it always showing the alert so i cant submit the form, i have given my code below please help me
PHP:
<form action="user_register.php" method="POST" name="myForm" onsubmit="return validateForm()" enctype="multipart/form-data">
<label>USERNAME:</label></td>
<input type="text" name="username" class="regtext" required/>
<label>RESIDING CITY:</label></td>
<input type="text" name="city" class="regtext" required/>
<label>I'M A</label>
<label>ARTIST   <input type="radio" value="1" name="user_type" > </label> 
<label>MODEL   <input type="radio" value="2" name="user_type"></label> 
<label>COMPOSER   <input type="radio" value="3" name="user_type" ></label> <br>
<label>BEAT MAKER   <input type="radio" value="4" name="user_type" ></label> 
<label>NONE   <input type="radio" value="0" name="user_type" ></label>
<label> <input type="checkbox" value="1" name="letter" >   I WOULD LIKE TO RECEIVE YOUR NEWSLETTER</label>
</div>
<div class="mainhead">
<input type="submit" name="register" class="submit" value="SEND AND REGISTER NOW">
</div>
</form>
JS:
<script type="text/javascript">
function validateForm() {
var province = document.forms["myForm"]["province"].value;
if (province == 0 ) {
alert("Select Province");
document.myForm.province.focus()
return false;
}
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
Problem is that for IE, document.forms["myForm"]["user_type"] is an HTMLCollection and has no value
Solution is to change
var user_type = document.forms["myForm"]["user_type"].value;
to
var user_type = document.querySelector('form[name="myForm"] input[name="user_type"]:checked').value;
What i observed is :
No name province present in code (what you gave). If you include it here, it will not work.
<script type="text/javascript">
function validateForm() {
var province = document.forms["myForm"]["province"].value;
if (province == 0 ) {
alert("Select Province");
document.myForm.province.focus()
return false;
}
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
After removing province validation. It started working.
<script type="text/javascript">
function validateForm() {
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
So, as Mr Rayon Dabre said "There is no element having name as province". So, i also agree with him. Remove province validation from validateForm() function (as it is not used in <from></form>)
This code should do the trick:
function validateForm() {
var user_type = document.getElementsByName('user_type');
var u_type = '';
for (var i = 0, length = user_type.length; i < length; i++) {
if (user_type[i].checked) {
// do whatever you want with the checked radio
u_type = user_type[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
if (u_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.getElementsByName('letter')[0].checked;
if (letter == "" || letter == undefined) {
alert("Select that you want to receive news letter");
return false;
}
}
The below is a snippet
<tr>
<td>7</td>
<td>Tick the Teaching Methods Used </td>
<td>
<input type="checkbox" id="lectures" name="lectures" value="lectures">Lectures
<input type="checkbox" id="study" name="study" value="study">Case Study
<input type="checkbox" id="audvid" name="audvid" value="audvid">Audio|Video
<input type="checkbox" id="interactive" name="interactive" value="interactive">Interactive Methods
<input type="checkbox" id="discussion" name="discussion" value="discussion">Discussion
<input type="checkbox" id="role" name="role" value="role">Role Play
<input type="checkbox" id="quiz" name="quiz" value="quiz">Quiz
</td>
</tr>
and the validation code is
if ((document.form1.lectures.checked == false)
&& (document.form1.study.checked == false)
&& (document.form1.audvid.checked == false)
&& (document.form1.interactive.checked == false)
&& (document.form1.discussion.checked == false)
&& (document.form1.role.checked == false)
&& (document.form1.quiz.checked == false)) {
alert("Please check any one method");
isValid = false;
}
return isValid;
How do i insert only the checked values into mysql database, implode doesn't seem to help
Edit : If i use the same "name" for all checkbox implode works but in that case I'm not able to validate
Use the same name for all your checkboxes. You said implode, so that's good. As for the validation, change it to use the IDs:
else if ((document.getElementById("lectures").checked == false)
&& (document.getElementById("study").checked == false)
&& (document.getElementById("audvid").checked == false)
&& (document.getElementById("interactive").checked == false)
&& (document.getElementById("discussion").checked == false)
&& (document.getElementById("role").checked == false)
&& (document.getElementById("quiz").checked == false)) {
alert("Please check any one method");
isValid = false;
}
return isValid;
Checkboxes are only put in POST, if selected (checked).
PHP:
$keys = explode(',','lectures,study,audvid'); //get all keys
$result = array();
foreach ($keys as $key) {
if (isset($_POST[$key]) && $_POST[$key]) { //selected!
$result[] = $key;
}
}
print_r($result); //only selected checkeboxes are in result.
I have this form
<form class="form" method="post">
<input type="text" id="input_what" holder="what" />
<input type="text" id="input_where" holder="where" />
<input type="submit" value="submit" />
</form>
and this script to prevent submitting the form
$('.form').submit(function(e) {
var what = $('#input_what').val();
var where = $('#input_where').val()
if ( what == "what" || what =="" && where == "where" || where == "") {
e.preventDefault();
console.log('prevented empty search');
return false;
}
});
I know that my condition doesn't work, but i need it to work like this
IF (what == "what" OR what == "") AND (where == "where" OR where == "")
have a look at this fiddle to understand why http://jsfiddle.net/pK35e/
the placeholder-script i´m using, needs me to not submit the form for the cases above
using placeholder="attribute" is no solution for me, so can anyone give me a hint how to set this if-condition ?
Uses parenthesis just like in the textual description you made :
if (( what == "what" || what =="") && (where == "where" || where == "")) {
Side remark : You might be interested, for future versions as it's not supported by IE9-, by the placeholder attribute which will make this simpler.
Try this
if ( (what == "what" || what =="") && (where == "where" || where == ""))
IF ((what == "what" ||what == "") &&(where == "where" ||where == ""))
Use parens. The && operator has a higher precedence than the || operator.
if ((what == "what" || what =="") && (where == "where" || where == ""))
http://en.m.wikipedia.org/wiki/Order_of_operations
I believe you need some parenthesis in order to get what you want:
if ( (what == "what" || what =="") && (where == "where" || where == ""))
This means that both
(what == "what" || what =="")
and
(where == "where" || where == "")
has to return true in order for the code within your if statement to be executed. This is actually quite close to your textual example.
--
Just for the understanding of all of this. Your old code would look like this with parenthesis:
if ( (what == "what") || (what =="" && where == "where") || (where == "")) {
Where again, just one of these would have to return true.