Can't Get If / Else Statement To Trigger - javascript

Here's my full code for what I'm working on:
https://codepen.io/sygilmore89/pen/BREvqG?editors=1010
The exact issue I'm having is that the if / else statement at the end isn't triggering like I would hope. I added the counter variable, and listed it to verify it's at the number I need, to account for an exact sequence of clicks to produce a particular outcome. If the player doesn't do that exact sequence, then the game should end in another way.
I'm puzzled as I don't see how it isn't triggering that counter is three AND the bottom left div is without text. Instead of putting the X where it should go at the point, it only continues to trigger the else statement. I probably should scrap it and try another method entirely but at this point I'm just confused as to why that exact line isn't working.
$(document).ready(function() {
var counter = 0;
$("#letterChoice").hide();
$("#button1").on("click", function() {
$("#letterChoice").show();
});
$("#buttonR").on("click", function() {
$("#letterChoice").show();
$("#topLeft").text("");
$("#topLeft").off("click");
$("#topCenter").text("");
$("#topCenter").off("click");
$("#topRight").text("");
$("#topRight").off("click");
$("#middleLeft").text("");
$("#middleLeft").off("click");
$("#middleMid").text("");
$("#middleMid").off("click");
$("#middleRight").text("");
$("#middleRight").off("click");
$("#bottomLeft").text("");
$("#bottomLeft").off("click");
$("#bottomMid").text("");
$("#bottomMid").off("click");
$("#bottomRight").text("");
$("#bottomRight").off("click");
counter = 0;
$("#test").text(counter);
});
$("#buttonX").on("click", function() {
$("#middleMid").text("O");
$("#middleMid").off("click");
if ($("#topLeft").text("")) {
$("#topLeft").on("click", function() {
$("#topLeft").text("X");
$("#topCenter").text("O");
counter++; //1
$("#test").text(counter);
});
}
if ($("#bottomMid").text("")) {
$("#bottomMid").on("click", function() {
$("#bottomMid").text("X");
$("#middleLeft").text("O");
counter++;
$("#test").text(counter);
});
}
if ($("#middleRight").text("")) {
$("#middleRight").on("click", function() {
$("#middleRight").text("X");
$("#topRight").text("O");
counter++;
$("#test").text(counter);
});
}
if ($("#bottomLeft").text("") && counter == 3) {
$("#bottomLeft").on("click", function() {
$("#bottomLeft").text("X");
$("#bottomRight").text("O");
});
} else {
$("#bottomLeft").on("click", function() {
$("#bottomLeft").text("X");
$("#bottomMid").text("O");
$("#topLeft").off("click");
$("#topCenter").off("click");
$("#topRight").off("click");
$("#middleLeft").off("click");
$("#middleMid").off("click");
$("#middleRight").off("click");
$("#bottomLeft").off("click");
$("#bottomMid").off("click");
$("#bottomRight").off("click");
});
}
});
});
body {
margin-top: 15px;
}
#board {
background-color: white;
width: 480px;
height: 480px;
}
.title {
margin-bottom: 15px;
}
#topLeft {
border: 1px solid black;
height: 160px;
width: 160px;
font-size: 92.5px;
}
#topCenter {
border: 1px solid black;
height: 160px;
width: 160px;
font-size: 92.5px;
}
#topRight {
border: 1px solid black;
height: 160px;
width: 160px;
font-size: 92.5px;
}
#middleLeft {
border: 1px solid black;
height: 160px;
width: 160px;
font-size: 92.5px;
}
#middleMid {
border: 1px solid black;
height: 160px;
width: 160px;
font-size: 92.5px;
}
#middleRight {
border: 1px solid black;
height: 160px;
width: 160px;
font-size: 92.5px;
}
#bottomLeft {
border: 1px solid black;
height: 160px;
width: 160px;
font-size: 92.5px;
}
#bottomMid {
border: 1px solid black;
height: 160px;
width: 160px;
font-size: 92.5px;
}
#bottomRight {
border: 1px solid black;
height: 160px;
width: 160px;
font-size: 92.5px;
}
#buttonX {
margin-bottom: 20px;
box-shadow: 0px 0px 1px 1px black;
border-radius: 2px;
outline: none;
background-color: #ccc;
}
#buttonR {
margin-bottom: 20px;
box-shadow: 0px 0px 1px 1px black;
border-radius: 2px;
outline: none;
background-color: #ccc;
}
#buttonO {
margin-bottom: 20px;
box-shadow: 0px 0px 1px 1px black;
border-radius: 2px;
outline: none;
background-color: #ccc;
}
#button1 {
margin-bottom: 20px;
box-shadow: 0px 0px 1px 1px black;
border-radius: 2px;
outline: none;
background-color: #ccc;
}
#letterChoice {
margin-left: 33.5px;
}
#choices {
margin-left: 175px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
<div class="container text-center" id="board">
<h1 class="title">Tic Tac Toe</h1>
<div class="row" id="choices">
<input type="button" value="New Game" id="button1" />
<div id="letterChoice"><input type="button" value="X" id="buttonX" /> or <input type="button" value="O" id="buttonO" /></div>
</div>
<div><input type="button" value="Reset" id="buttonR" /></div>
<div id="test">Test it</div>
<div class="row" id="topRow">
<div id="topLeft">
</div>
<div id="topCenter">
</div>
<div id="topRight">
</div>
</div>
<div class="row" id="middleRow">
<div id="middleLeft">
</div>
<div id="middleMid">
</div>
<div id="middleRight">
</div>
</div>
<div class="row" id="bottomRow">
<div id="bottomLeft">
</div>
<div id="bottomMid">
</div>
<div id="bottomRight">
</div>
</div>
</div>

Your condition is setting the text and evaluating the result instead of checking if it equals an empty string. You're looking for:
if($("#bottomLeft").text() == '' && counter == 3)
What's happening with your existing code is it sets the text to an empty string and then evaluates the result, which is a jQuery object that will always evaluate to true.

Related

What's the problem with this angular ts code for implementing floating label input onfocus?

I am trying to float the labels onfocusing input in angular.
I did wrote code to perform the action of a class to be applied on focusing the input, & then focus out to check empty value or values present, to remove the applied class.
forms.component.html
<div class="forms-field-box">
<div class="forms-field-inp-box">
<input id="forms_field_inp_fn" class="forms-field-inp" type="text" (focus)=inpAnim();>
<label for="forms_field_inp_fn" id="forms_input" class="forms-field-inp-lbl">
FirstName
</label>
</div>
</div>
<div class="forms-field-box">
<div class="forms-field-inp-box">
<input id="forms_field_inp_ln" class="forms-field-inp" type="text" (focus)=inpAnim();>
<label for="forms_field_inp_ln" id="forms_input" class="forms-field-inp-lbl">
LastName
</label>
</div>
</div>
<div class="forms-field-box">
<div class="forms-field-inp-box">
<input id="forms_field_inp_p" class="forms-field-inp" type="text" (focus)=inpAnim();>
<label for="forms_field_inp_p" id="forms_input" class="forms-field-inp-lbl">
Password
</label>
</div>
</div>
<div class="forms-login-btn">
Login
</div>
forms.component.scss
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
.forms-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 60%;
background-color: #ffffff;
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.5);
min-height: 120px;
padding: 20px;
border-radius: 5px;
}
.forms-field-box {
background-color: #ffffff;
margin-bottom: 15px;
}
.forms-field-inp-box {
width: 97%;
position: relative;
}
.forms-field-inp {
width: 100%;
height: 35px;
border-radius: 5px;
border: 1px solid #e4e4e4;
outline: none;
padding: 6px;
}
.forms-field-inp:hover {
border: 1px solid #cccccc;
}
.forms-field-inp:focus {
border: 1px solid #0089ff;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}
.forms-field-inp-lbl {
position: absolute;
top: 8px;
left: 10px;
font-size: 14px;
font-weight: 600;
background-color: #ffffff;
padding: 2px 6px;
user-select:none;
color: #cccccc;
}
.forms-field-inp-lbl-anim ~ .forms-field-inp-lbl {
top: -9px;
}
.forms-login-btn {
width: 20%;
height: 35px;
text-align: center;
font-size: 18px;
padding: 5px;
background-color: blue;
border: 1px solid blue;
border-radius: 5px;
margin: 10px auto;
cursor: pointer;
box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
}
forms.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.scss']
})
export class FormsComponent implements OnInit {
constructor() {
}
ngOnInit(): void {
}
inpAnim(){
let forms_input_ele:any = document.querySelector(".forms-field-inp-box input");
forms_input_ele.addEventListener("focusin", () => {
console.log("focussed in");
forms_input_ele.classList.add("forms-field-inp-lbl-anim");
} );
forms_input_ele.addEventListener("focusout", () => {
let forms_inp_val = forms_input_ele.value;
if(forms_inp_val == ""){
forms_input_ele.classList.remove("forms-field-inp-lbl-anim");
console.log("focussed out");
console.log(forms_inp_val);
}
});
}
}
Please Help me to solve this.
input focused & label floated
input has value & label stays
Problem: But, the first input only works, other inputs not working if focused & nothing happens.,
Next input is focused, but label not floating
This can be easily applied by css, but need to make this small code to work correctly

Price range slider not working in mozzila browser but working in chrome & opera browser

I've created price range slider by using html, css & javascript. It is working perfectly in google chrome and opera browser but not working in mozzila firefox browser.
See below mention screenshot what I got when I tried to run this in mozzila firefox browser. I'm unable to identify the issue.
I'm unable to add image here but here is the image link : Screenshot of the issue
Please anyone can help me to resolve this issue?
// Custom price range slider created by Pawan Mall | www.pawanmall.net
let rangeSlider = ((containerSelector, minSelector, maxSelector, selectionSelector, inputCallback, changeCallback) => {
inputCallback = inputCallback || function () { };
changeCallback = changeCallback || function () { };
let timeout;
let sliderContainer = document.querySelector(containerSelector);
let sliderMinElement = document.querySelector(minSelector);
let sliderMaxElement = document.querySelector(maxSelector);
let sliderSelectionElement = document.querySelector(selectionSelector);
let values = { min: sliderMinElement.value, max: sliderMaxElement.value };
sliderMinElement.addEventListener('input', e => {
sliderTimeout(() => { valueChanged(e); });
});
sliderMaxElement.addEventListener('input', e => {
sliderTimeout(() => { valueChanged(e); });
});
sliderMinElement.addEventListener('change', () => { changeCallback(values); });
sliderMaxElement.addEventListener('change', () => { changeCallback(values); });
return {
setHandles: data => {
data = data || {};
if (data.min) {
sliderMinElement.value = data.min;
valueChanged({ target: sliderMinElement });
}
if (data.max) {
sliderMaxElement.value = data.max;
valueChanged({ target: sliderMaxElement });
}
}
};
function valueChanged(event) {
if (event.target === sliderMinElement && +sliderMinElement.value >= +sliderMaxElement.value) {
sliderMinElement.value = +sliderMaxElement.value - 5;
return event.preventDefault();
}
if (event.target === sliderMaxElement && +sliderMinElement.value >= +sliderMaxElement.value) {
sliderMaxElement.value = +sliderMinElement.value + 5;
return event.preventDefault();
}
values.min = sliderMinElement.value;
values.max = sliderMaxElement.value;
sliderSelectionElement.style.left = +sliderMinElement.value / +sliderMaxElement.getAttribute('max') * 100 + '%';
sliderSelectionElement.style.right = +sliderMaxElement.value / +sliderMaxElement.getAttribute('max') * -100 + 100 + '%';
inputCallback(values);
}
function sliderTimeout(callback) {
clearTimeout(timeout);
timeout = setTimeout(callback, 10);
}
})('.range-slider', '.range-slider-min', '.range-slider-max', '.range-slider-selection', values => {
// console.log('values changed!', values);
// document.querySelector('.display1').innerHTML = '₹ '+ values.min + ', ₹ ' + values.max;
document.querySelector('.minmaxprice').value = values.min + ',' + values.max;
document.querySelector('.minprice').innerHTML = '₹ ' + values.min;
document.querySelector('.maxprice').innerHTML = '₹ ' + values.max;
}, values => {
// console.log('change done!', values);
});
rangeSlider.setHandles({ min: 5000, max: 250000 });
// console.log('inited!');
// https://seiyria.com/bootstrap-slider/#example-13
// $("#BudgetRange").slider({ min: 5000, max: 250000, value: [25000, 55000], focus: true });
/* Custom price range slider created by Pawan Mall | www.pawanmall.net */
.range-slider {
margin: 0 0;
position: relative;
height: 20px;
}
.range-slider::before,
.range-slider-selection {
content: "";
position: absolute;
z-index: 2;
top: 50%;
margin-top: -2px;
height: 3px;
z-index: 2;
}
.range-slider-selection {
background: orange;
left: 0px;
right: 0px;
}
.range-slider::before {
background: #ccc;
left: 0px;
right: 0px;
}
.range-slider-min,
.range-slider-max {
pointer-events: none;
position: absolute;
overflow: hidden;
left: 0;
top: 0;
width: 100%;
outline: none;
-webkit-appearance: none;
}
.range-slider-min::-webkit-slider-thumb,
.range-slider-max::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
pointer-events: all;
position: relative;
z-index: 3;
outline: 0;
width: 20px;
height: 20px;
border-radius: 50%;
border: 1px solid #ddd;
background: #fff;
}
.range-slider-min:active::-webkit-slider-thumb,
.range-slider-max:active::-webkit-slider-thumb {
background: #f3f3f3;
}
.minmaxprice {
width: 200px;
text-align: center;
margin: 0 auto;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container m-3 p-3">
<div class="row mt-2">
<div class="col-md-6 col-sm-6 col-xs-6 col-lg-6">
<b class="minprice">₹ 5,000</b>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 col-lg-6 text-right">
<b class="maxprice">₹ 2,50,000</b>
</div>
</div>
<div class="row mt-2">
<div class="col-md-12">
<div class="range-slider"><span class="range-slider-selection"></span>
<input class="range-slider-min" type="range" min="5000" max="250000"
step="1" value="5000" />
<input class="range-slider-max" type="range" min="5000" max="250000"
step="1" value="250000" />
<br />
<input type="hidden" class="minmaxprice" name="pricerange" value="" />
</div>
</div>
</div>
</div>
You've used Webkit specific prefix pseudo element styling for the range slider.
::-webkit-slider-thumb
but failed to take into account that Mozilla and Microsoft have their own prefixes:
::-moz-range-thumb
::-ms-thumb
At a minimum you must implement the Mozilla version, but should consider implementing both.
From the MDN site about this tech, follow this link for a correctly implemented cross-browser slider: https://css-tricks.com/styling-cross-browser-compatible-range-inputs-css/
input[type=range] {
-webkit-appearance: none;
margin: 18px 0;
width: 100%;
}
input[type=range]:focus {
outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 8.4px;
cursor: pointer;
animate: 0.2s;
box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
background: #3071a9;
border-radius: 1.3px;
border: 0.2px solid #010101;
}
input[type=range]::-webkit-slider-thumb {
box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
border: 1px solid #000000;
height: 36px;
width: 16px;
border-radius: 3px;
background: #ffffff;
cursor: pointer;
-webkit-appearance: none;
margin-top: -14px;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: #367ebd;
}
input[type=range]::-moz-range-track {
width: 100%;
height: 8.4px;
cursor: pointer;
animate: 0.2s;
box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
background: #3071a9;
border-radius: 1.3px;
border: 0.2px solid #010101;
}
input[type=range]::-moz-range-thumb {
box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
border: 1px solid #000000;
height: 36px;
width: 16px;
border-radius: 3px;
background: #ffffff;
cursor: pointer;
}
input[type=range]::-ms-track {
width: 100%;
height: 8.4px;
cursor: pointer;
animate: 0.2s;
background: transparent;
border-color: transparent;
border-width: 16px 0;
color: transparent;
}
input[type=range]::-ms-fill-lower {
background: #2a6495;
border: 0.2px solid #010101;
border-radius: 2.6px;
box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
}
input[type=range]::-ms-fill-upper {
background: #3071a9;
border: 0.2px solid #010101;
border-radius: 2.6px;
box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
}
input[type=range]::-ms-thumb {
box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
border: 1px solid #000000;
height: 36px;
width: 16px;
border-radius: 3px;
background: #ffffff;
cursor: pointer;
}
input[type=range]:focus::-ms-fill-lower {
background: #3071a9;
}
input[type=range]:focus::-ms-fill-upper {
background: #367ebd;
}
<input type="range" min="0" max="100" step="5" value="50"/>
Then modify the CSS to accommodate your needs.

gradient box dynamically append jquery

If click on button some boxes are append. next you will click on that boxes gradient box will append but gradient boxes are not appending.its append only first box if click on another box gradient box doesn't append
My Fiddle
<script src="https://cdn.office24by7.com/add-templates/gradX.js"></script>
<button class="clbtn" name="button" value="button">button</button>
<div class="appenddiv">
</div>
<script>
$(document).ready(function(){
var i = 0;
$(".clbtn").click(function(el){
$.fn.myFunction = function(){
gradX("#clrpik", {
targets: [".target"]
});
}
$(".appenddiv").append('<div class="target"><div class="target_text">Click Here for gradient</div></div>');
$(".target").click(function(){
$(".appenddiv").append('<div id="clrpik"></div>').myFunction();
});
});
});
</script>
Gradient box appending on other div click but it's stick to first div
use this to set:
$(this).append('<div id="clrpik"></div>').myFunction();
});
$(document).ready(function(){
var f = 0;
$(".clbtn").click(function(el){
$.fn.myFunction = function(){
gradX("#clrpik", {
targets: [".target"]
});
//f++;
}
$(".appenddiv").append('<div class="target"><div class="target_text">Click Here for gradient</div></div>');
$(".target").one('click', function(){
$(this).append('<div id="clrpik"></div>').myFunction();
});
});
});
.targets {
margin:0 auto;
text-align: center;
border: 1px solid #ccc;
background: #f8f8f8;
margin: 0 auto;
border-radius: 4px;
width:auto;
padding:10px;
}
.target_text {
margin: 0px auto;
margin-top: 40%;
background: #f8f8f8;
width: 70px;
border: 1px solid #ddd;
padding: 2px;
border-radius: 2px;
color: #111;
}
.target {
border: 1px solid;
margin: 0px 10%;
width: 150px;
height: 150px;
display:inline-block;
}
#target {
border-radius: 150px;
}
.result {
text-align: center;
text-transform: uppercase;
font-weight: bold;
padding:12px;
padding-left: 15px;
margin: 10px 0px;
border: 1px solid #ddd;
background: #f8f8f8;
}
.clrpik {
height: 200px;
margin: 100px 34%;
}
<link href="https://cdn.office24by7.com/add-templates/colorpicker.css" rel="stylesheet"/>
<link href="https://cdn.office24by7.com/add-templates/gradX.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://codologic.com/page/sites/all/files/gradx/dom-drag.js"></script>
<script src="https://codologic.com/page/sites/all/files/gradx/colorpicker/js/colorpicker.js"></script>
<script src="https://cdn.office24by7.com/add-templates/gradX.js"></script>
<button class="clbtn" name="button" value="button">button</button>
<div class="appenddiv">
</div>

JQuery Calculation Button

Currently I have this GPA Calculator that calculates the data as it is inputted. I want to add a calculation button called "Calculate" that will calculate all of the inputted data but only when pressed. So the calculation will only occur when this button is pressed, not on the fly like it is currently doing.
Here is the code:
var $oBox = $('.outer-box');
var $gpa = $('#gpa');
var $result = $('.result').hide();
$('.btn').click(function() {
$('.block').last().clone().children().val("").parent().appendTo($('.inner-box'));
});
$oBox.on('keyup', '.credits', function() {
$gpa.text(getTotal());
});
$oBox.on("change", ".grade-select", function() {
$gpa.text(getTotal());
$result.is(":hidden") && $result.show();
});
function getTotal() {
var gradeTotal = 0;
var sum = 0;
$(".credits").each(function() {
var $this = $(this);
if (!isNaN($this.val()) && !isNaN($this.parent().find('.grade-select').val())) {
sum += parseFloat($this.val() || 0) * parseFloat($this.parent().find('.grade-select').val() || 0);
gradeTotal += parseFloat($this.val() || 0)
}
});
return (sum / gradeTotal).toFixed(2);
}
$(".btn").on("click", function() {
$('html, body').animate({
scrollTop: $(document).height()
}, 'slow');
return false;
});
body {
background-color: #A00000;
background-size: cover;
margin: 0;
padding: 0;
}
.outer-box {
border: 3px solid black;
height: true;
width: 75%;
padding: 10px;
margin: 10px auto 10px auto;
border-radius: 10px;
background-color: white;
}
.block {
margin: 5px;
}
.class {
border: 1px solid gray;
border-radius: 5px;
width: 150px;
height: 35px;
margin: 10px;
padding: 5px;
}
.credits {
border: 1px solid gray;
border-radius: 5px;
width: 100px;
height: 35px;
margin: 10px;
padding: 5px;
}
.grade-select {
border: 1px solid gray;
border-radius: 5px;
width: 100px;
height: 35px;
margin: 10px;
padding: 5px;
}
.btn {
border: 2px solid black;
border-radius: 5px;
width: 150px;
height: 35px;
margin: 10px;
padding: 5px;
font-weight: bold;
text-align: center;
}
.result {
border: 2px solid black;
border-radius: 5px;
width: 200px;
height: 100px;
margin: 20px auto 20px auto;
padding: 5px;
font-weight: bold;
text-align: center;
}
#gpa {
font-size: 4rem;
color: black;
font-weight: bold;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class='outer-box'>
<div class='inner-box'>
<form class='block'>
<input type="text" class='class' placeholder="Class">
</br>
<select class='credits'>
<option value="">Credits</option>
<option value="0.5">Half Year</option>
<option value="1">Full Year</option>
</select>
</br>
<select class='grade-select'>
<option value="">Grade</option>
<option value="4.6">A+</option>
<option value="4.0">A</option>
<option value="3.6">B+</option>
<option value="3.0">B</option>
<option value="2.6">C+</option>
<option value="2.0">C</option>
<option value="1.0">D</option>
<option value="0.0">F</option>
</select>
</form>
</div>
<div class='btn btn-default'>Add Class</div>
<div class='result'>
<h3 id="gpa">GPA</h3>
</div>
</div>
change the calling of calulate funtionality from drop down change event to button on click
var $oBox = $('.outer-box');
var $gpa = $('#gpa');
var $result = $('.result').hide();
$('.btn').click(function() {
$('.block').last().clone().children().val("").parent().appendTo($('.inner-box'));
});
$oBox.on('keyup', '.credits', function() {
$gpa.text(getTotal());
});
$oBox.on("change", ".grade-select", function() {
});
function getTotal() {
var gradeTotal = 0;
var sum = 0;
$(".credits").each(function() {
var $this = $(this);
if (!isNaN($this.val()) && !isNaN($this.parent().find('.grade-select').val())) {
sum += parseFloat($this.val() || 0) * parseFloat($this.parent().find('.grade-select').val() || 0);
gradeTotal += parseFloat($this.val() || 0)
}
});
return (sum / gradeTotal).toFixed(2);
}
$("#Calculate").on("click", function() {
$gpa.text(getTotal());
$result.is(":hidden") && $result.show();
$('html, body').animate({
scrollTop: $(document).height()
}, 'slow');
return false;
});
body {
background-color: #A00000;
background-size: cover;
margin: 0;
padding: 0;
}
.outer-box {
border: 3px solid black;
height: true;
width: 75%;
padding: 10px;
margin: 10px auto 10px auto;
border-radius: 10px;
background-color: white;
}
.block {
margin: 5px;
}
.class {
border: 1px solid gray;
border-radius: 5px;
width: 150px;
height: 35px;
margin: 10px;
padding: 5px;
}
.credits {
border: 1px solid gray;
border-radius: 5px;
width: 100px;
height: 35px;
margin: 10px;
padding: 5px;
}
.grade-select {
border: 1px solid gray;
border-radius: 5px;
width: 100px;
height: 35px;
margin: 10px;
padding: 5px;
}
.btn {
border: 2px solid black;
border-radius: 5px;
width: 150px;
height: 35px;
margin: 10px;
padding: 5px;
font-weight: bold;
text-align: center;
}
.result {
border: 2px solid black;
border-radius: 5px;
width: 200px;
height: 100px;
margin: 20px auto 20px auto;
padding: 5px;
font-weight: bold;
text-align: center;
}
#gpa {
font-size: 4rem;
color: black;
font-weight: bold;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class='outer-box'>
<div class='inner-box'>
<form class='block'>
<input type="text" class='class' placeholder="Class">
</br>
<select class='credits'>
<option value="">Credits</option>
<option value="0.5">Half Year</option>
<option value="1">Full Year</option>
</select>
</br>
<select class='grade-select'>
<option value="">Grade</option>
<option value="4.6">A+</option>
<option value="4.0">A</option>
<option value="3.6">B+</option>
<option value="3.0">B</option>
<option value="2.6">C+</option>
<option value="2.0">C</option>
<option value="1.0">D</option>
<option value="0.0">F</option>
</select>
</form>
</div>
<div class='btn btn-default'>Add Class</div>
<button id=Calculate class='btn btn-default' >Calculate</button>
<div class='result'>
<h3 id="gpa">GPA</h3>
</div>
</div>
You are calling your getTotal function in listeners for keyup and change. Hence it is being calculated immediately. If you want it to happen on click of some button, assign a listener to the click of button and call getTotal there.
Something like:
$("#calculate").click(function(){
// code for getting values from input box using .val()
//then call getTotal();
});
Hope it helps, let us know if you still are unable to achieve it.

jQuery check if 4 fields are filled in

I am working on a form with 4 fields which I directly validate. So if a field is filled in correctly I give this field green borders for example. But now I want to do a check if all the fields are filled in and then I show a message.
My idea is to first make a function for each field like this below. And then check the 4 functions if they return true. But that didn't work, so I first check a single function (in this example for the field 'width') if they match, an alert returns. But this also doesn't work, so I cannot go any further now.
Can anybody help me to make this function work first?
(The #config-steps #width is an input field with the an id 'width')
My code snippet:
jQuery(document).ready(function($) {
// Validate text fields
$("#config-steps #width, #config-steps #height").on('input', function() {
var input = $(this);
var width = input.val();
if (width.match(/^\d+$/)) {
input.removeClass('invalid').addClass('valid');
input.parents('li').find('.step-number').removeClass('unvalid-step').addClass('valid-step');
} else {
input.removeClass('valid').addClass('invalid');
input.parents('li').find('.step-number').removeClass('valid-step').addClass('unvalid-step');
}
});
// Validate select box
$("#config-steps #type").change(function() {
var slct = $(this);
var type = slct.val()
if (type) {
slct.parents('li').find('.step-number').removeClass('unvalid-step').addClass('valid-step');
} else {
slct.parents('li').find('.step-number').removeClass('valid-step').addClass('unvalid-step');
}
});
// Check all fields filled in.
function check_field() {
function validate_width() {
var width = $("#config-steps #width").val();
if (width.match(/^\d+$/)) {
alert('test');
} else {
return false;
}
}
}
});
.valid {
background: #f7fff7 !important;
border: 1px solid #459b40 !important;
}
.invalid {
background: #fff7f7 !important;
border: 1px solid #ff0000 !important;
}
.clear {
clear: both;
}
#config-steps li:nth-child(odd) {
background: #f6f8f9;
}
#config-steps li {
border-bottom: 1px solid #e1e6ea;
padding: 20px;
list-style: none;
}
#config-steps li .step-number {
color: #FFF;
font-size: 16px;
display: inline-block;
background: #f08f02;
border: 1px solid #d98c1a;
padding: 8px 11px;
font-weight: bold;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
float: left;
min-width: 8px;
text-align: center;
margin: 0 15px 0 0;
-moz-box-shadow: inset 0px 0 1px #FFF;
-webkit-box-shadow: inset 0px 0 1px #FFF;
box-shadow: inset 0px 0 1px #FFF;
}
#config-steps li .valid-step {
background: #55ad50;
border: 1px solid #2b8825;
}
#config-steps li .unvalid-step {
background: #ed7171;
border: 1px solid #cf0000;
}
#config-steps li .step-description {
font-size: 14px;
float: left;
padding: 10px 0 0 0;
}
#config-steps li .step-action {
float: right;
}
#config-steps li .step-action .textfield {
background: #f1f9ff;
border: 1px solid #9eabb6;
padding: 7px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
}
#config-steps li .step-action input[type="text"] {
width: 180px;
text-align: right;
}
#config-steps li .step-action input[type="text"]:focus {
background: #fffcf6;
border: 1px solid #f6a41d;
}
#config-steps li .step-action select {
margin: 7px 3px 0 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="config">
<ul id="config-steps">
<li> <span class="step-number">1</span>
<p class="step-description">Width (mm)</p>
<div class="step-action">
<input autofocus type="text" class="textfield" id="width" />
</div>
<!--End step-action-->
<div class="clear"></div>
</li>
<li> <span class="step-number">2</span>
<p class="step-description">Height (mm)</p>
<div class="step-action">
<input type="text" class="textfield" id="height" />
</div>
<!--End step-action-->
<div class="clear"></div>
</li>
<li> <span class="step-number">3</span>
<p class="step-description">Glasstype (mm)</p>
<div class="step-action">
<select id="type">
<option value="">-- Select glasstype --</option>
<option value="1">Mat</option>
<option value="2">Glossy</option>
</select>
</div>
<!--End step-action-->
<div class="clear"></div>
</li>
</ul>
<!--End config-steps-->
</form>
<!--End config-->
Use $('#width').change for checking
$('input,select').change(function(){
var width = $("#config-steps #width").val();
var height = $("#config-steps #height").val();
var size = $("#config-steps select").val();
if (width.match(/^\d+$/)&&height.match(/^\d+$/)&&size.match(/^\d+$/)) {
alert('Well done!');
} else {
return false;
}
});
Updated here:
jQuery(document).ready(function($) {
// Validate text fields
$("#config-steps #width, #config-steps #height").on('input', function() {
var input = $(this);
var width = input.val();
if (width.match(/^\d+$/)) {
input.removeClass('invalid').addClass('valid');
input.parents('li').find('.step-number').removeClass('unvalid-step').addClass('valid-step');
} else {
input.removeClass('valid').addClass('invalid');
input.parents('li').find('.step-number').removeClass('valid-step').addClass('unvalid-step');
}
});
// Validate select box
$("#config-steps #type").change(function() {
var slct = $(this);
var type = slct.val()
if (type) {
slct.parents('li').find('.step-number').removeClass('unvalid-step').addClass('valid-step');
} else {
slct.parents('li').find('.step-number').removeClass('valid-step').addClass('unvalid-step');
}
});
// Check all fields filled in.
$('input,select').change(function() {
var width = $("#config-steps #width").val();
var height = $("#config-steps #height").val();
var size = $("#config-steps select").val();
if (width.match(/^\d+$/) && height.match(/^\d+$/) && size.match(/^\d+$/)) {
alert('Well done!');
} else {
return false;
}
});
});
.valid {
background: #f7fff7 !important;
border: 1px solid #459b40 !important;
}
.invalid {
background: #fff7f7 !important;
border: 1px solid #ff0000 !important;
}
.clear {
clear: both;
}
#config-steps li:nth-child(odd) {
background: #f6f8f9;
}
#config-steps li {
border-bottom: 1px solid #e1e6ea;
padding: 20px;
list-style: none;
}
#config-steps li .step-number {
color: #FFF;
font-size: 16px;
display: inline-block;
background: #f08f02;
border: 1px solid #d98c1a;
padding: 8px 11px;
font-weight: bold;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
float: left;
min-width: 8px;
text-align: center;
margin: 0 15px 0 0;
-moz-box-shadow: inset 0px 0 1px #FFF;
-webkit-box-shadow: inset 0px 0 1px #FFF;
box-shadow: inset 0px 0 1px #FFF;
}
#config-steps li .valid-step {
background: #55ad50;
border: 1px solid #2b8825;
}
#config-steps li .unvalid-step {
background: #ed7171;
border: 1px solid #cf0000;
}
#config-steps li .step-description {
font-size: 14px;
float: left;
padding: 10px 0 0 0;
}
#config-steps li .step-action {
float: right;
}
#config-steps li .step-action .textfield {
background: #f1f9ff;
border: 1px solid #9eabb6;
padding: 7px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
}
#config-steps li .step-action input[type="text"] {
width: 180px;
text-align: right;
}
#config-steps li .step-action input[type="text"]:focus {
background: #fffcf6;
border: 1px solid #f6a41d;
}
#config-steps li .step-action select {
margin: 7px 3px 0 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="config">
<ul id="config-steps">
<li> <span class="step-number">1</span>
<p class="step-description">Width (mm)</p>
<div class="step-action">
<input autofocus type="text" class="textfield" id="width" />
</div>
<!--End step-action-->
<div class="clear"></div>
</li>
<li> <span class="step-number">2</span>
<p class="step-description">Height (mm)</p>
<div class="step-action">
<input type="text" class="textfield" id="height" />
</div>
<!--End step-action-->
<div class="clear"></div>
</li>
<li> <span class="step-number">3</span>
<p class="step-description">Glasstype (mm)</p>
<div class="step-action">
<select id="type">
<option value="">-- Select glasstype --</option>
<option value="1">Mat</option>
<option value="2">Glossy</option>
</select>
</div>
<!--End step-action-->
<div class="clear"></div>
</li>
</ul>
<!--End config-steps-->
</form>
<!--End config-->
You will need to call the
check_field();
Function after each input has been updated. I've created an example of how you can achieve this.
http://jsfiddle.net/EsBTg/6/
You can use .each() function in jQuery to test several elements at once:
function validate_width() {
var error = 0;
$("#width, #height, #type").each(function () {
if (!$(this).val().match(/^\d+$/)) {
error++;
}
});
if (!error){
alert("Everything's fine!");
}
}
jQuery(document).ready(function($) {
// Validate text fields
$("#config-steps #width, #config-steps #height").on('input', function() {
var input = $(this);
var width = input.val();
if (width.match(/^\d+$/)) {
input.removeClass('invalid').addClass('valid');
input.parents('li').find('.step-number').removeClass('unvalid-step').addClass('valid-step');
} else {
input.removeClass('valid').addClass('invalid');
input.parents('li').find('.step-number').removeClass('valid-step').addClass('unvalid-step');
}
});
// Validate select box
$("#config-steps #type").change(function() {
var slct = $(this);
var type = slct.val()
if (type) {
slct.parents('li').find('.step-number').removeClass('unvalid-step').addClass('valid-step');
} else {
slct.parents('li').find('.step-number').removeClass('valid-step').addClass('unvalid-step');
}
});
// Check all fields filled in.
function validate_width() {
var error = 0;
$("#width, #height, #type").each(function() {
if (!$(this).val().match(/^\d+$/)) {
error++;
}
});
if (error) {
alert("There were " + error + " errors.");
} else {
alert("Everything's fine!");
}
}
$("#check").click(function() {
validate_width();
})
});
.valid {
background: #f7fff7 !important;
border: 1px solid #459b40 !important;
}
.invalid {
background: #fff7f7 !important;
border: 1px solid #ff0000 !important;
}
.clear {
clear: both;
}
#config-steps li:nth-child(odd) {
background: #f6f8f9;
}
#config-steps li {
border-bottom: 1px solid #e1e6ea;
padding: 20px;
list-style: none;
}
#config-steps li .step-number {
color: #FFF;
font-size: 16px;
display: inline-block;
background: #f08f02;
border: 1px solid #d98c1a;
padding: 8px 11px;
font-weight: bold;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
float: left;
min-width: 8px;
text-align: center;
margin: 0 15px 0 0;
-moz-box-shadow: inset 0px 0 1px #FFF;
-webkit-box-shadow: inset 0px 0 1px #FFF;
box-shadow: inset 0px 0 1px #FFF;
}
#config-steps li .valid-step {
background: #55ad50;
border: 1px solid #2b8825;
}
#config-steps li .unvalid-step {
background: #ed7171;
border: 1px solid #cf0000;
}
#config-steps li .step-description {
font-size: 14px;
float: left;
padding: 10px 0 0 0;
}
#config-steps li .step-action {
float: right;
}
#config-steps li .step-action .textfield {
background: #f1f9ff;
border: 1px solid #9eabb6;
padding: 7px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
}
#config-steps li .step-action input[type="text"] {
width: 180px;
text-align: right;
}
#config-steps li .step-action input[type="text"]:focus {
background: #fffcf6;
border: 1px solid #f6a41d;
}
#config-steps li .step-action select {
margin: 7px 3px 0 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="config">
<ul id="config-steps">
<li> <span class="step-number">1</span>
<p class="step-description">Width (mm)</p>
<div class="step-action">
<input autofocus type="text" class="textfield" id="width" />
</div>
<!--End step-action-->
<div class="clear"></div>
</li>
<li> <span class="step-number">2</span>
<p class="step-description">Height (mm)</p>
<div class="step-action">
<input type="text" class="textfield" id="height" />
</div>
<!--End step-action-->
<div class="clear"></div>
</li>
<li> <span class="step-number">3</span>
<p class="step-description">Glasstype (mm)</p>
<div class="step-action">
<select id="type">
<option value="">-- Select glasstype --</option>
<option value="1">Mat</option>
<option value="2">Glossy</option>
</select>
</div>
<!--End step-action-->
<div class="clear"></div>
</li>
</ul>
<!--End config-steps-->
</form>
<!--End config-->
<input id=check value=Check type=button>

Categories

Resources