So I learning jQuery atm, and have to make a Loan calculator based on choices, as well as validate enteries, then output a result.
l wanted to make sure you guys knew what i was trying to do, so i have here a flow chart of what is supposed to happen:
http://i59.tinypic.com/8z02sh.jpg
that shows what is supposed to be happening. Problem is i dont know how to do this is Jquery. The radio button selector i found online (through another question on here) seems weird and i dont know how to use it. I could do this using javascript, but then i wouldn't be learning anything. So here's my code so far.
Also, im getting an error on line 14 of my JS (line 14 in JSfiddle), and i cant figure out what it is.
JSfiddle: http://jsfiddle.net/keup5vaw/1/
HTML:
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">
</form>
<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="0">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="0">
<label for="under1">Under 600</label></p>
</form>
<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="0">
<label for="job2">I have worked at my current job less than 1 year.</label><br>
</form>
<input type="button" id="check" name="check" value="Check">
<div id="message"></div>
and JS -
$('#check').click(function () {
var salary;
var isValid = $('#salaryForm').validate().form();
// if validation passes, display a message
if (isValid) {
var salary = Number($('#salary').val());
if (salary < 40000) {
if ($('input[name=radio]:checked').length > 0) {
if ($('input[name=job1]:checked').length > 0) {
$('#message').html("Loan Approved.")
} else if {
$('#message').html("Loan Denied.")
} else if {
$('#message').html("Loan Denied.")
}
}
} else(salary >= 40000) {
if ($('input[name=radio]:checked').length > 0) {
if ($('input[name=job1]:checked').length > 0) {
$('#message').html("Loan Approved.")
} else if {
if ($('input[name=job1]:checked').length > 0) $('#message').html("Loan Approved.")
} else if {
$('#message').html("Loan Denied.")
}
}
}
});
// form validation
$('#salaryForm').validate({
rules: {
salary: {
required: true,
digits: true,
range: [1, 1000000]
}
}
});
As per usual, thank you ahead of time, you guys are awesome.
Edit: Updated after Mottie helped out (thank you!), Still not seeing what line 14 is doing wrong, but changed the else to else if, and used the tidy up.
If your having problems with the checking if a radio is checked you can use this its a lot cleaner than what you are currently using and is more intuitive.
if($("#id1").is(":checked")){
// do something
}else if($("#id2").is(":checked")){
// do something else
}
Hope this helps.
Formatting your javascript is really important to catch those type of syntax error for your self. As #Mottie said use some kind of javascript formatter to fix those issues.Tidy Up,
http://jsbeautifier.org/ are better place to start up with. Here is the correct code
$('#check').click(function()
{
var salary;
var isValid = $('#salaryForm').validate().form();
// if validation passes, display a message
if (isValid)
{
var salary = Number($('#salary').val());
if (salary < 40000)
{
if ($('input[name=radio]:checked').length > 0)
{
if ($('input[name=job1]:checked').length > 0)
{
$('#message').html("Loan Approved.")
}
else
{
$('#message').html("Loan Denied.")
}
}
else
{
$('#message').html("Loan Denied.")
}
}
else if (salary >= 40000)
{
if ($('input[name=radio]:checked').length > 0)
{
if ($('input[name=job1]:checked').length > 0)
{
$('#message').html("Loan Approved.")
}
else
{
if ($('input[name=job1]:checked').length > 0)
$('#message').html("Loan Approved.")
}
}else
{
$('#message').html("Loan Denied.")
}
}
}
});
// form validation
$('#salaryForm').validate(
{
rules:
{
salary:
{
required: true,
digits: true,
range: [1, 1000000]
}
}
});
modified your jquery
http://jsfiddle.net/cvynLaqf/
$('#check').click(function(){
var salary;
//var isValid = $('#salaryForm').validate().form();
var isValid = true;
// if validation passes, display a message
if (isValid){
var salary = Number($('#salary').val());
if (salary < 40000){
if ($('input[type=radio]:checked').length > 0){
if ($('input[value=over1]:checked').length > 0) {
//if over 600 do this
if ($('input[id=job1]:checked').length > 0)
$('#message').html("Loan Approved.");
else
$('#message').html("Loan Denied.");
}
else {
$('#message').html("Loan Denied.");}
}
else {
$('#message').html("Loan Denied.");
}
} else if( salary >= 40000){
if ($('input[type=radio]:checked').length > 0){
if ($('input[value=over1]:checked').length > 0) {
//over 600 do this
$('#message').html("Loan Approved.");}
else {
//under 600 do this
if ($('input[id=job1]:checked').length > 0)
$('#message').html("Loan Approved.");
else
$('#message').html("Loan Denied.");
}
}
else {
$('#message').html("Loan Denied.");}
}
}
});
// form validation
//$('#salaryForm').validate({
// rules: {
// salary: {
// required: true,
// digits: true,
// range: [1, 1000000]
// }
// }
//});
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">
</form>
<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="over1">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="under1">
<label for="under1">Under 600</label></p>
</form>
<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="1">
<label for="job2">I have worked at my current job less than 1 year.</label><br>
</form>
<input type="button" id="check" name="check" value="Check">
<div id="message"></div>
i commented out your validation because im getting an error on my part
Despite an answer already being accepted, I figured I'd post an updated script since you're just beginning to learn jQuery to maybe help you improve further.
You're way over complicating the conditionals (if/else statements) for starters.
Break it down based on the behavior you would like to accomplish and word out the functionality the same way too.
Makes it a lot easier to read if you (or someone else) needs to look at it again in 6 months.
Has Good Credit?
Has Standing Job?
Is Loan Approved?
Has Good Salary?
Here's the rewritten functional fiddle.
http://jsfiddle.net/q3xpsLmL/
I also merged the individual forms to clean up a little. I changed the validation to HTML 5's required, type=number, min and max since the .validate() plugin was not in the fiddle.
Relying on HTML 5 and jQuery submit() event to validate the form.
Some more info on HTML 5 validation and pattern if you're interested:
http://www.w3.org/html/wg/drafts/html/master/forms.html#the-pattern-attribute
You can even style it using css :valid and :invalid pseudo-classes
I had trouble interpreting your logic for a applicant with a good salary. So I set it to approve if the person has a good salary and either good credit or a standing job.
If you have questions on it just add a comment.
HTML
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0);">
<label for="salary">Enter your annual salary</label>
<input id="salary" type="number" name="salary" min="0" max="1000000000" required>
<p>Please select your Credit Score</p>
<p>
<input type="radio" name="radio" id="over1" value="over1">
<label for="over1">Over 600</label>
</p>
<p>
<input checked type="radio" name="radio" id="under1" value="under1">
<label for="under1">Under 600</label>
</p>
<p>How long have you worked at your current job?</p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label>
<br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="1">
<label for="job2">I have worked at my current job less than 1 year.</label>
<br>
<button type="submit" id="check" name="check">Check</button>
</form>
<div id="message"></div>
JavaScript
//use strict to ensure variables are defined and to prevent collisions
"use strict";
//define DOM elements so events do not need refind the element.
var salryForm = $('#salaryForm');
var salaryElement = $('#salary');
var messageElement = $('#message');
var radioButtons = $('input[type=radio]');
var goodCredit = radioButtons.filter('[name=radio][value=over1]');
var standingJob = radioButtons.filter('[name=job][value=0]');
var isLoanApproved = function(salary){
//always be pecimistic and decline unless all conditions are met
var result = false;
var hasGoodCredit = goodCredit.is(':checked');
var hasStandingJob = standingJob.is(':checked');
var hasGoodSalary = (salary >= 40000);
/*
* if applicant doesn't have a good salary
* they have to have good credit and standing job to be approved
*/
if (!hasGoodSalary && hasGoodCredit && hasStandingJob) {
result = true;
/**
* otherwise if applicant does have a good salary
* they only need to have either good credit or standing job to be approved
*/
} else if(hasGoodSalary && (hasGoodCredit || hasStandingJob)) {
result = true;
}
return result;
};
/**
* track on submit rather than click so you can catch "<enter>" key presses as well
*/
salryForm.submit(function(e) {
var salary = salaryElement.val();
messageElement.html('Loan ' + (isLoanApproved(salary) ? 'Approved' : 'Denied'));
return false;
});
Related
I'm creating a quiz that contains 10 questions: 5 multiple choice through radio input and 5 written answers through text input. See code for both inputs below. But I would also like to add a score system to these questions. I found a nice script here on stack overflow that can keep the score while user enters form input. I will add it below.
The script I use to check answers from radio input:
$(document).ready(function(){
$('input[name=radio1]').change(function(){
$('.alert').remove();
if($('input[name=radio1]:checked').val() === "1") {
$(this).parent().append('<span class="correct">✓ Correct!</span>');
} else {
$(this).parent().append('<span class="incorrect">✗ Correct answer = B</span>');
}
});
});
The correct anser given is based on value="1". The other answers have value="0".
The script I use to check answers from text input:
$('submit').on('click', function() {
markAnswers(1)
});
var answers = {
q1: ["Auto's"]
};
function markAnswers(id) {
$(`#q${id}`).each(function () {
let userAnswer = this.value.replace(/[^\w\'\,\-\?\!\"\:\—\;]/g,'');
if ($.inArray(userAnswer, answers[this.id]) === -1) {
$(this).parent().append(`<br><span class='incorrect'>✗ Correct answer = ${answers[this.id]}</span>`);
} else {
$(this).parent().append("<br><span class='correct'>✓ Correct!</span>");
}
});
}
The correct value from text input is determined by this script above.
Now, the script I found that keeps the score, collects score through data-score=. But I was thinking to just use value instead. See original script below:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
The script can be found here: https://stackoverflow.com/a/58297288/4546157
It is really nice. It keeps the score but it also shows you if you have completed the form or not.
I would like each correct answer to have a value of 1 so at the end of the quiz the user can have a maximum score of 10/10. But, a big but, I don't know how to implement it. Hoping to see suggestions or solutions from you guys. Thank you!
You would do it something like this. Though it's bad practice to use globally available variables, but for the sake of simplicity i put them there. Better to wrap everything in a div and store score/progress as data attributes.
Pen: https://codepen.io/lenadax/pen/QWQqMxP?editors=1111
// global vars, put them somewhere else
var progress = 0;
var score = 0;
$('form.question').each(function(i, el) {
// I'm lazy so form id is the same as input name for each question
let inputs = $(`input[name=${$(this).attr('id')}]`);
inputs.on('change', function() {
// increase progress by 1 if button has been selected.
progress++;
if ($(this).val() === "1") {
// increase score if correct choice selected
score++;
$('<span class="result correct">').text('✓ Correct!').appendTo(el);
} else {
$('<span class="result incorrect">').text('X Incorrect!').appendTo(el);
}
// get number of questions
let question_count = $('form.question').length;
// disable after choosing for less hassle
inputs.prop('disabled', true);
// calculate the progress in percent
let progress_num = progress / question_count * 100;
$('.perc').text(progress_num);
$('#score').text(`${score} / ${question_count}`);
});
})
input {
display: inline-block;
}
label {
display: inline-block;
}
button {
display: block;
}
form {
width: 200px;
border: 1px solid gray;
margin: 10px;
padding:10px 5px;
}
.result {
display: block;
}
.result.incorrect {
color: red;
}
.result.correct {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form class="question" id="question1">
<span>Question 1</span>
</p>
<input name="question1" id="answer1" type="radio" value="0"/>
<label for="answer1">Wrong answer</label>
</p>
<input name="question1" id="answer2" type="radio" value="1"/>
<label for="answer2">Right answer</label>
</form>
<form class="question" id="question2">
<span>Question 2</span>
</p>
<input name="question2" id="answer1" type="radio" value="0"/>
<label for="answer1">Wrong answer</label>
</p>
<input name="question2" id="answer2" type="radio" value="0"/>
<label for="answer2">Wrong answer</label>
</p>
<input name="question2" id="answer3" type="radio" value="1"/>
<label for="answer3">Right answer</label>
</form>
<h5>Done <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>
I have been through a series of revisions on this website I'm working on, basically, I need to add validation to email input field that only allows .edu extension for an only student type registrations.
Currently, there is a dropdown by which someone can select either student or a business. So when someone selects a student I want that validation rule to apply that only .edu can only register.
After struggling through google and StackOverflow I coded two scripts in jQuery which does not seem to be working well.
A user fills all the form fields and when at the select student the email input field should be checked and should stop the user to create an account if it does have .edu extension.
Code 1:
jQuery( document ).ready(function(){
jQuery('#reg_email').on('input',function(e){
var email = document.getElementById("reg_email");
var counter = 0;
if(jQuery(".chosen-single span").text().search("Student") == 0){
if (email.value.indexOf("#") != -1) {
if (!(/(.+)#(.+)\.(edu)$/.test(email.value))) {
if(counter<=0){
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
counter++;
}
}else{
jQuery(#alert).remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
}
}
});
});
This Code above repeatedly adds the p tag but i tried to bound it to only once.
Code 2:
jQuery( document ).ready(function(){
var email = document.getElementById("reg_email");
if(jQuery(".chosen-single span").text().search("Student") == 0){
jQuery("#reg_email").validate({
rules: {
email: {
required: true,
email: true,
pattern: /(\.edu\.\w\w\w?)$/
}
}
});
}
});
This does not even work I have even included two scripts the validate.min.js and the additional-methods.min.js but still does not work.
It's like I'm starting to have a feeling that this is not even possible.
Please if someone can help it will be appreciated.
The website is website When you click signup you will see the sign-up modal box.
For now, I have removed all custom JS code. So you guys can check in the console.
P.S EDIT
Code 3: I tried even this
jQuery( document ).ready(function(){
var email = document.getElementById("reg_email");
var done = false;
jQuery(".chosen-single span").on('DOMSubtreeModified', function () {
if(jQuery(".chosen-single span").html() == 'Student') {
if (email.value.indexOf("#") != -1) {
if (!(/(.+)#(.+)\.(edu)$/.test(email.value))) {
if(!done) {
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
done = true;
}
else{
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
}
}
});
});
But in this code, I only check domsubtreemodified and generate an alert box if the span value is 'Student' but the rest of the below code is not working.
This is the HTML FORM
<form method="post" class="register workscout_form">
<p class="form-row form-row-wide">
<label for="reg_username">Username <span class="required">*</span>
<i class="ln ln-icon-Male"></i>
<input type="text" class="input-text" name="username" id="reg_username" value="">
</label>
</p>
<p class="form-row form-row-wide">
<label for="reg_email">Email address <span class="required">*</span>
<i class="ln ln-icon-Mail"></i><input type="email" class="input-text" name="email" id="reg_email" value="">
</label>
</p>
<p class="form-row form-row-wide">
<label for="reg_password">Password <span class="required">*</span>
<i class="ln ln-icon-Lock-2"></i><input type="password" class="input-text" name="password" id="reg_password">
</label>
</p>
<p class="form-row terms wc-terms-and-conditions">
<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">
<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="terms" id="terms" autocomplete="off"> <span>I’ve read and accept the terms & conditions</span> <span class="required">*</span>
</label>
<input type="hidden" name="terms-field" value="1">
</p>
<label for="user_email">I want to register as</label><select name="role" class="input chosen-select" style="display: none;"><option value="employer">Business</option><option value="candidate">Student</option></select><div class="chosen-container chosen-container-single chosen-container-single-nosearch" style="width: 100%;" title=""><a class="chosen-single" tabindex="-1"><span>Business</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" readonly=""></div><ul class="chosen-results"></ul></div></div>
<p class="form-row">
<input type="hidden" id="_wpnonce" name="_wpnonce" value="cc26c06e5b"><input type="hidden" name="_wp_http_referer" value="/"> <input type="submit" class="button" name="register" value="Register">
</p>
</form>
This is the last code 4 I'm using It kinda work nicely but just one thing is left is that when let suppose user corrects the email with a proper speciifed edu email the warning should go and the button should be enabled i can't get this to work in this way.
jQuery( document ).ready(function(){
var email = document.getElementById("reg_email");
var done = false;
jQuery("select[name='role']").change(function() {
if(jQuery("select[name='role']").children(':selected').html() == 'Student') {
if (email.value.indexOf("#") != -1) {
if (!(/(.+)#(.+)\.(edu)$/.test(email.value))) {
if(!done) {
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
done = true;
}
else{
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
}
}
}
});
});
This should work, note that this will update on change, not after submitting the form.
function emailValid(email) {
var re = /(\.edu\.\w\w\w?)$/;
return re.test(email);
}
$(document).ready(function() {
$(document).on('change', '#reg_email', function() {
if ($(".chosen-single span").html() == 'Student') {
if (!emailValid($('#reg_email').val())) {
// Alert user that the email is not valid
}
else {
// Remove the alert
}
}
});
});
Okay so here is the complete code which helped me accomplish this task.
jQuery( document ).ready(function(){
var email = document.getElementById("reg_email");
var done = false;
jQuery("select[name='role']").change(function() {
if(jQuery("select[name='role']").children(':selected').html() == 'Student') {
if (email.value.indexOf("#") != -1) {
if (!(/(\.edu\.\w\w\w?)$/.test(email.value))) {
if(!done) {
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
done = true;
}
else{
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
}
}
}if(jQuery("select[name='role']").children(':selected').html() == 'Business') {
done = false;
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}
});
jQuery("#reg_email").on("change keyup paste", function(){
if(jQuery("select[name='role']").children(':selected').html() == 'Student') {
if (email.value.indexOf("#") != -1) {
if (/(\.edu\.\w\w\w?)$/.test(email.value)) {
jQuery("#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', false);
}else{
if(jQuery("p#alert").length <= 1){
jQuery("p#alert").remove();
jQuery('#signup-dialog input[type="submit"]').prop('disabled', true);
jQuery(".form-row.form-row-wide:eq(1)").append('<p id="alert" style="padding-top:5px;color:red;">You are not eligible for an account. Please enter a valid .edu email.</p>');
done = true;
}
}
}
}
});
});
Everything is now working and it's awesome! It might help someone so though post this.
The validation of the checkbox doesn't work. It doesn't give any error. Could you please help me to fix it? And how can I combine errors in one alert instead of one by one?
Thanks for any help.
Html code:
<form class="contact_form" action="" method="post" name="contact_form" onsubmit="returnonFormSubmit(this)">
<li>
<label for="First Name">First Name:</label>
<input type="text" name="visitor_name" /><br />
</li>
<li>
<label for="condition">I agree with the terms and conditions.</label>
<input type="checkbox" name="lan" /><br />
</li>
<li>
<label for="Male">Male:</label>
<input type="radio" name="gender" value="m" /> Female:<input type="radio" name="gender" value="f" /><br />
</li>
<li>
<label for="National Rating">National Rating:</label>
<select name="make">
<option selected>-- SELECT --</option>
<option> Below 1200 </option>
<option> 1200 - 1500 </option>
<option> 1500 - 1800 </option>
<option> 1800 - 2100 </option>
<option> Above 2100 </option>
</select><br />
</li>
<li>
<button class="submit" type="submit">Submit</button>
</li>
<div id="error_message" style="color:#ff0000;"></div>
javascript code:
function onFormSubmit(form_element)
{
var checked = 0;
var letters = /^[a-zA-Z]+$/;
if (form_element.visitor_name.value.match(letters))
{
true;
}
else
{
alert("Please enter a valid first name. For example; John.");
false;
}
if (form_element.lan.checked == false)
{
alert("Please accept the terms and conditions");
false;
}
if (form_element.gender[0].checked == false && form_element.gender[1].checked == false)
{
alert("Please select a gender.");
false;
}
if (form_element.make.selectedIndex == 0)
{
alert("Please select your rating interval.");
form_element.make.focus();
false;
}
return true;
}
You should concatenate the error messages in a variable.
function onFormSubmit(form_element)
{
var checked = 0;
var letters = /^[a-zA-Z]+$/;
var errorMessage = "";
if (!form_element.visitor_name.value.match(letters))
{
errorMessage += "Please enter a valid first name. For example; John.\n";
}
if (form_element.lan.checked == false)
{
errorMessage += "Please accept the terms and conditions\n";
}
if (errorMessage != "")
{
alert(errorMessage);
return false;
}
return true;
}
You have a typo in onsubmit="returnonFormSubmit(this)". It should be
onsubmit="return onFormSubmit(this)"
Running this with a console open would give you a valuable error/warning. Try Chrome's Developer Tools, Firefox' Firebug or similar.
To combine the errors into one, you could start out with an empty string msg = '' and append to it if there is an error. Then at the bottom of your function, alert(msg) and return false if it is non-empty, otherwise return true.
After fixing typo in returnonFormSubmit(this) it works in Chrome and Firefox.
(BTW: you forget returns)
To combine alerts I would use an array.
Example:
function onFormSubmit(form_element)
{
var checked = 0;
var letters = /^[a-zA-Z]+$/;
var alerts = new Array();
if (!form_element.visitor_name.value.match(letters))
alerts.push("Please enter a valid first name. For example; John.");
if (!form_element.lan.checked)
alerts.push("Please accept the terms and conditions");
if (alerts.length == 0) {
return true;
}
alert(alerts.join("\n"));
return false;
}
I have two checkboxes in a group and one text input. If one (or both) of the checkboxes are selected I need to have the text input be required, as well as if the text input has text I need at least one of the checkboxes to be required. Another problem I'm having it that it's using a custom templating engine (PHP backend) and is a pain to configure and get the attributes correct, another issue is it's all referenced by the name attribute and this is why I'm using a HTML5 data-group for the checkbox options which I think it working.
Any help in getting this to work, combining functions (if this makes it easier/simpler).
BTW it's running 1.3.2 jQuery
Example: (not working)
http://jsfiddle.net/NYn8e/1/
Any suggestions?
JS:
function checkboxSelectedRequiredAdditionalFields(elem) {
var passedElement = $('input:checkbox[name=' + elem + ']');
passedElement.click(function() {
$('input[name=number]').attr('required', true).append('<span class="required">*</span>');
alert('text is required now?');
});
}
function numberEnteredRequiredAdditionalFields(elem) {
var passedElement = $('input[name=' + elem + ']');
if (passedElement.val().length > 0) {
var boxes = $('input[data-group=cbOptions]').click(function() {
boxes.not(this).attr('required', false);
alert('checkbox is selected so other checkbox is not required');
});
$('input[data-group=cbOptions]').each(function() {
$(this).attr('required', true).next().append('<span class="required">*</span>');
alert('checkbox is required now?');
});
}
}
HTML
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox1');" data-group="cbOptions">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox2');" data-group="cbOptions">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" onclick="numberEnteredRequiredAdditionalFields('number');">
</b>
</form>
You should separate the JavaScript from the HTML. Fiddle: http://jsfiddle.net/NYn8e/6/. If possible, remove <b> from the HTML source, and extend the style sheet with the right CSS property: font-weight: bold;.
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" data-required="checkbox">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" data-required="checkbox">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" data-required="number">
</b>
</form>
JavaScript:
function required(){
//Any checked checkbox? checked == 0 = no, otherwise: yes
var checked = $('input[data-required=checkbox]:checked').length;
var $checkboxes = $('input[data-required=checkbox]');
var $num = $('input[name=number]');
var length = $num.val().length;
//Remove previously added span, if existent.
$num.next('span.required').remove();
$checkboxes.next('span.required').remove();
if(!length && checked){
$num.after('<span class="required">*</span>');
alert("Number required!");
} else if(length && !checked){
$checkboxes.after('<span class="required">*</span>');
alert("Check at least one checkbox.");
}
}
$(document).ready(function(){
$("[data-required]").change(required);
});
=) Would this one help you?
<form id='myForm'>
<input type='checkbox' name='checkbox1' value='t' id='checkbox1' onchange='alertUser()' />
<input type='checkbox' name='checkbox2' value='t' id='checkbox2' onchange='alertUser()' />
<input type='text' name='number' id='number' onchange='alertUser()'/>
</form>
<script type='text/javascrip>
function alertUser() {
var checked1 = $('#checkbox1').attr('checked');
var checked2 = $('#checkbox2').attr('checked');
var number = $('#number').val();
if ((checked1 == true || checked2 == true) && number == '') {
alert('Number is required!');
} else if (number != '' && (checked1 != true && checked2 != true)) {
alert('One of the checkbox need to be checked!');
}
});
</script>
This should hopefully give you an idea on how to accomplish the task. http://jsfiddle.net/NYn8e/8/
var $textbox = $('input[name=number]').hide();
$('input[type=checkbox]').change(function() {
var $this = $(this); //store jquery object
//get the other checkbox
var $other= ($this.attr('name') === 'checkbox1') ? $('input[name=checkbox2]') : $('input[name=checkbox1]');
if (!$other.is(':checked') && !$this.is(':checked')) {
$textbox.val('').hide();
} else{
$textbox.show();
}
});
I'm making a simple client-side, self-grading quiz.
I ask 6 questions and I want to alert the user with their score (keeping things simple). If they leave an answer blank, an alert will appear.
I'm new to javascript and don't really know how to check individual form elements to see if they're empty. I'm also having problems with getting my code to run.
JS
EDIT
function grade() {
var score = 0;
var elt = document.quiz;
// Check to see if no questions were left unanswered.
if elt.question1.value.length == 0 || elt.question2.value.length == 0 ||
elt.question3.value.length == 0 || elt.question4.value.length == 0 ||
elt.question5.value.length == 0 || elt.question6.value.length == 0
{
alert ("Whoops, you're missing an answer!")
}
if (elt.question1[1].checked) {
score += 1;
}
if (elt.question2[0].checked) {
score += 1;
}
if (elt.question3[0].checked == false && elt.question3[1].checked &&
elt.question3[2].checked == false && elt.question3[3].checked == false) {
score += 1;
}
if (elt.question4[0].checked == false && elt.question4[1].checked == false &&
elt.question4[2].checked == false && elt.question4[3].checked) {
score += 1;
}
elt.question5 = elt.question5.toLowerCase()
if (elt.question5.value != '' && elt.question5.value.indexOf('galaxy') != -1) {
score += 1;
}
elt.question6 = elt.question6.toLowerCase()
if (elt.question5.value != '' && elt.question6.value.indexOf('age') != -1) {
score += 1;
}
score = score / 6 * 100;
score = score.toFixed(2);
alert("You scored " + score + "%");
return false; // Return true if you want the form to submit on validation/grade
}
You have a some significant errors in your markup:
Do not wrap a form element around each question. These should all be in one form element. (Also, each question be in a OL to number the question in series.)
You're not properly closing all of your label's, so they're selecting other elements when you click them (try question 3, first checkbox).
You need the grade() function on the form's submit handler, and it needs to be onsubmit="return grade()", with grade() returning false when it doesn't "pass" to prevent form submission*.
* Note, I set the grade() function to always return false in the example. You would need to add the logic for when it would allow the form to submit.
As far as the Javascript...
You need the elt variable to be equal to your document.quiz (note, I changed the main form to have a name="quiz" in your markup). You can use indexOf() instead of a regex if you just want to have a simple check (regex could check for age as a word, though).
If you just want to make sure a text input is not empty, you can use el.value.length != 0 or el.value != ''.
Also, looking at your grading code, if you want only one to be selected, you could use a radio, unless you want the person taking the quiz to not know if one or more were valid answers. But radio's only allow you to select a single value.
HTML
<h3> Self-Grading Astronomy Quiz </h3>
<form action="" name="quiz" onsubmit="return grade();">
<p>1. According to Kepler the orbit of the earth is a circle with the sun at the center.</p>
<p>
<label><input type="radio" name="question1" value="true" /> True </label>
<label><input type="radio" name="question1" value="false" /> False </label>
</p>
<p>2. Ancient astronomers did consider the heliocentric model of the solar system but rejected it because they could not detect parallax.</p>
<p>
<label><input type="radio" name="question2" value="true" /> True </label>
<label><input type="radio" name="question2" value="false" /> False </label>
</p>
<p>3. The total amount of energy that a star emits is directly related to its:</p>
<p>
<label><input type="checkbox" name="question3" value="1" /> a) surface gravity and magnetic field </label><br/>
<label><input type="checkbox" name="question3" value="2" /> b) radius and temperature </label><br/>
<label><input type="checkbox" name="question3" value="3" /> c) pressure and volume </label><br/>
<label><input type="checkbox" name="question3" value="4" /> d) location and velocity </label>
</p>
<p>4. Stars that live the longest have:</p>
<p>
<label><input type="checkbox" name="question4" value="1" /> a) high mass </label><br/>
<label><input type="checkbox" name="question4" value="2" /> b) high temperature </label><br/>
<label><input type="checkbox" name="question4" value="3" /> c) lots of hydrogen </label><br/>
<label><input type="checkbox" name="question4" value="4" /> d) small mass </label>
</p>
<p>5. A collection of a hundred billion stars, gas, and dust is called a __________.</p>
<p>
<input type='text' id='question5' />
</p>
<p>6. The inverse of the Hubble's constant is a measure of the __________ of the universe.</p>
<p>
<input type='text' id='question6' />
</p>
<p>
<input type='button' onclick='grade()' value='Grade' />
</p>
</form>
Javascript
function grade() {
//**Would I do something like this?
//if(elem.value.length == 0){
// alert("Whoops, looks like you didn't answer a question.")}
var score = 0;
var elt = document.quiz;
if (elt.question1[1].checked) {
score += 1;
}
if (elt.question2[0].checked) {
score += 1;
}
if (elt.question3[0].checked == false && elt.question3[1].checked && elt.question3[2].checked == false && elt.question3[3].checked == false) {
score += 1;
}
if (elt.question4[0].checked == false && elt.question4[1].checked == false && elt.question4[2].checked == false && elt.question4[3].checked) {
score += 1;
}
if (elt.question5.value != '' && elt.question5.value.indexOf('galaxy') != -1) {
score += 1;
}
if (elt.question5.value != '' && elt.question6.value.indexOf('age') != -1) {
score += 1;
}
score = score / 6 * 100;
score = score.toFixed(2);
alert("You scored " + score + "%");
return false; // Return true if you want the form to submit on validation/grade
}
http://jsfiddle.net/BeD3Z/10/
check individual form elements to see if they're empty
You just compare the value to an empty string:
if(elt.question6.value == '') {
alert('Unanswered');
}
You can use jquerys built in validation http://docs.jquery.com/Plugins/validation. It has built in functionality to check for required and to display an error message below the field which is blank.