How to add auto calculation for two inputs - javascript

I have this calculator that I'd like for the results to auto update after the the user adds input.
I've tried the .keyup thing, but I don't understand it.
I'm kinda new to javascript.
Here's my codepen for the project.
http://codepen.io/Tristangre97/pen/zNvQON?editors=0010
HTML
<div class="card">
<div class="title">Input</div>
<br>
<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">
<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div>
<br>
<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>
JS
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("#submit").click(function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == '') {
$("#metalAlert").html("Please enter a value");
}
else if (forges == 0 || forges == '') {
$("#metalAlert").html('');
$("#forgeAlert").html("Please enter a value");
}
else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
}
else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
}
else {
$(".plural").html("in the");
}
$("#forgeAlert").html('');
if (metals % 2 == 0) {}
else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(((spread / 2) * 20) / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
}
else {
$("#allSpark").html(String(''));
}
$("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html((isWood) ? "wood" : "sparkpowder");
$("#result").show();
}
});
});

To run the function whenever something is inputted in the field, try the
$("input").on('input', function() { .. });
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("input").on('input', function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == "") {
$("#metalAlert").html("Please enter a value");
} else if (forges == 0 || forges == "") {
$("#metalAlert").html("");
$("#forgeAlert").html("Please enter a value");
} else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
} else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
} else {
$(".plural").html("in the");
}
$("#forgeAlert").html("");
if (metals % 2 == 0) {
} else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(spread / 2 * 20 / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
} else {
$("#allSpark").html(String(""));
}
$("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html(isWood ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
body {
background-color:#316b6f;
font-family:Helvetica,sans-serif;
font-size:16px;
}
.whiteinput {
outline: none;
border-width: 0px;
margin: 0;
padding: .5em .6em;
border-radius: 2px;
font-size: 1em;
color: #316b6f;
}
.actionButton {
background-color: #316B6F;
color: #fff;
padding: .5em .6em;
border-radius: 3px;
border-width: 0px;
font-size: 1em;
cursor: pointer;
text-decoration: none;
-webkit-transition: all 250ms;
transition: all 250ms;
}
.actionButton:hover {
color: #fff;
}
.actionButton:active {
background: #BBFF77;
color: #316B6F;
-webkit-transition: all 550ms;
transition: all 550ms;
}
.card {
position: relative;
background: #4E8083;
color:#FFFFFF;
border-radius:3px;
padding:1.5em;
margin-bottom: 3px;
}
.title {
background: #76B167;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.title2 {
background: #2F3A54;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.floater {
padding: 3px;
}
.radiobtn {
background: red;
border-radius: 2px;
}
input[type=radio] + label:before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
vertical-align:middle;
margin-right: 8px;
background-color: #aaa;
margin-bottom: 6px;
border-radius: 2px;
-webkit-transition: all 450ms;
transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
display:none;
}
input[type=radio]:checked + label:before {
content: "\2022"; /* Bullet */
color:white;
background-color: #fff;
font-size:1.8em;
text-align:center;
line-height:14px;
margin-right: 8px;
}
input[type=checkbox]:checked + label:before {
content:"\2714";
color:white;
background-color: #fff;
text-align:center;
line-height:15px;
}
*:focus {
outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="card">
<div class="title">Input</div><br>
<div id="metalSpan">
<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
Metal Quantity
</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan">
<input class="whiteinput" id="numForge" type="number">
<div class="floater">
Forge Quantity
</div>
</div>
<br>
<input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
<button class="actionButton" id="submit"
type="button">Calculate</button>
</div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div><br>
<div id="result">
<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
"allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br>
</div>
</div>
</div>
Codepen
It is triggering your errors because that is part of your function.
More info regarding the input method.

Look, you have two options:
Put all your algorithm of submit click into a function and call him into two binds: the submit click and input change (on('change')) or just remove your calculate button and rely the calculation into onchange of the inputs: each change of checks or inputs will trigger the calculation of metals. The second approach it's more interesting for me and removes the necessity to the user clicks to calculate (he already clicked into inputs and checks). Obviously you can add a filter to only allow to calculation function run after a certain minimum number of data filled, it's a good idea to avoid poor results resulted by lack of data.

In order to auto update calculation, we have to listen to users input on input elements. The easiest approach with minimum changes to existing code is to add input events and emit click on the button:
$("#numMetal, #numForge").on('input', function(){
$("#submit").click()
})
Better approach is to move calculation logic to separate function and call it on desirable events:
$("#numMetal, #numForge").on('input', function(){
calculate()
})
$("#submit").click(function(){
calculate()
})
This will keep the code structured and easier to follow.

Try this:
$( "#numMetal, #numForge" ).keyup(function(event) {
console.log('a key has been pressed');
// add code to handle inputs here
});
What happens here is that an event listener - the key up event - is bound to the two inputs you have on your page. When that happens the code inside will be run.
As suggested in other comments it would be a good idea to call a separate method with all the input processing code you have in the submit call, this way you will avoid code duplication.
You will also want to bind events to the checkboxs. This can be achieved with this:
$( "input[name=fuel]" ).on('change',function() {
console.log('checkbox change');
// call processing method here
});

Related

When div is visible on screen add .active class to li

I am trying to build a page:
Like This
When a div gets into the view on the screen, then a class gets added to the right side of the "table of contents", then when it's scrolled off the screen and another div shows up the class gets moved to the next "title" of the content.
So far I have a list of divs stacked on the top of each other and some basic JS but it does not work. I am not even sure if this is a good approach to get this done?
$(window).scroll(function(){
if ( $('#field-wrap1').offset().top <= 100 ) {
$('#slide-li1').addClass("active");
}else{
$('#slide-li1').removeClass("active");
}
});
JSFiddle
<!---
With this code it doesn't require editing the JavaScript
at all, only the HTML/CSS, it will apply the class .qqq_menu_active
to the active menu item and .qqq_section_active to the active section.
--->
<style>
* {
font-family: Arial;
margin: 0;
padding: 0;
}
body {
font-size: 10pt;
}
.qqq_container {
padding: 50px;
}
.qqq_menu {
position: fixed;
width: 200px;
left: 750px;
top: 50px;
}
.qqq_menu_item {
color: #333;
}
.qqq_menu_active {
font-size: 14pt;
font-weight: bold;
color: #000;
}
.qqq_section {
width: 600px;
padding: 25px;
color: #676767;
background-color: #fff;
}
.qqq_section_active {
color: #281c96;
background-color: #bdb6ff;
}
h1 {
padding-bottom: 20px;
}
</style>
<div class="qqq_menu">
<div class='qqq_menu_item'>section_1</div>
<div class='qqq_menu_item'>section_2</div>
<div class='qqq_menu_item'>section_3</div>
<div class='qqq_menu_item'>section_4</div>
<div class='qqq_menu_item'>section_5</div>
</div>
<div class='qqq_container'>
<div class='qqq_section'>
<h1>section_1</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_2</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_3</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_4</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_5</h1>
<p class='text_fill'></p>
</div>
</div>
<script>
// note: have tried editing .repeat to 3000 to make it a lot of text and 150 to make it a little text and still works right. also added a bunch of space with <br /> above and below the .qqq_container element and still works right.
asdf_text = "asdf ".repeat(750);
document.querySelectorAll(".text_fill").forEach(function (element) {
element.innerHTML = asdf_text;
});
container = document.querySelectorAll(".qqq_container")[0];
sections = document.querySelectorAll(".qqq_section");
menu = document.querySelectorAll(".qqq_menu_item");
percentage = 0;
function qqq_menu_highlight() {
active = 0;
ttt = window.innerHeight / 100;
lll = ttt * percentage;
zzz = window.scrollY + lll;
sections.forEach(function (v, k, l) {
if (zzz > v.offsetTop) {
active = k;
}
});
menu.forEach(function (v, k, l) {
if (active === k) {
v.classList.add('qqq_menu_active');
} else {
v.classList.remove('qqq_menu_active');
}
});
sections.forEach(function (v, k, l) {
if (active === k) {
v.classList.add('qqq_section_active');
} else {
v.classList.remove('qqq_section_active');
}
});
}
function element_scroll_percentage(element) {
//inc = (document.body.scrollHeight - window.innerHeight) / 100;
//console.log(active);
rect = element.getBoundingClientRect();
if (Math.sign(rect.top) == -1) {
value = Math.abs(rect.top);
inc = (rect.height - window.innerHeight) / 100;
percentage = value / inc;
if (percentage > 100) {
percentage = 100;
}
} else {
percentage = 0;
}
return percentage;
}
document.onscroll = function() {
percentage = element_scroll_percentage(container);
qqq_menu_highlight();
//console.log(percentage);
}
document.onscroll();
</script>
In the solution below, I divided the value of this.scrollY by 200, since the height of the containers is 200px. I added the result of this action to the end of the slide-li statement to use as the id of the targeted item.
function removeClass() {
for(let i = 0 ; i < 6 ; i++)
$(`#slide-li${i + 1}`).removeClass("active");
}
$(window).scroll(function(){
console.clear();
console.log(`Scroll: ${this.scrollY}`);
removeClass();
let visibleElement = Math.floor(this.scrollY / 200);
$(`#slide-li${visibleElement + 1}`).addClass("active");
});
#container {
width: 800px;
margin: auto;
text-align: left;
display: inline-flex;
margin: 0;
margin: 100px 0;
}
#field {
width: 500px;
float: left;
font-weight: 500;
color: #001737;
}
.field-wrap {
padding: 0;
border-bottom: 1px solid #8392A5;
height: 200px;
background-color: #FF000030;
}
#slidecart {
position: fixed;
top: 10px;
right: 0px;
width: 300px;
display: inline-block;
padding: 20px;
border-left: 1px solid #8392A5;
}
#slide-ul {
list-style-type: none;
margin: 0;
padding: 5px 0 0 5px;
}
.slide-li {
margin: 0;
padding: 0 0 0 10px;
cursor: pointer;
}
.active {
padding: 0 0 0 5px;
border-left: 5px solid #0168FA;
color: #0168FA;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="field">
<div id="field-wrap1" class="field-wrap">
1.) - Hello World!
</div>
<div id="field-wrap2" class="field-wrap">
2.) - Hello World!
</div>
<div id="field-wrap3" class="field-wrap">
3.) - Hello World!
</div>
<div id="field-wrap4" class="field-wrap">
4.) - Hello World!
</div>
<div id="field-wrap5" class="field-wrap">
5.) - Hello World!
</div>
<div id="field-wrap6" class="field-wrap">
6.) - Hello World!
</div>
</div>
<div id="slidecart">
TABLE OF CONTENTS
<ul id="slide-ul">LIST
<li id="slide-li1" class="slide-li">1.) - Hello World!</li>
<li id="slide-li2" class="slide-li">2.) - Hello World!</li>
<li id="slide-li3" class="slide-li">3.) - Hello World!</li>
<li id="slide-li4" class="slide-li">4.) - Hello World!</li>
<li id="slide-li5" class="slide-li">5.) - Hello World!</li>
<li id="slide-li6" class="slide-li">6.) - Hello World!</li>
</ul>
</div>
</div>

How to get the quantity of the product chosen by the user?

I am working on an e-commerce website. Now I am on single product description page and I have quantity and add to cart button. Initial quantity I set one.
I am able to increase and decreased the quantity on click on plus and minus button.
Now the issue is, I choose quantity four and I clicked on add to cart button and it redirects to checkout page where I am checking the output
checkout.php
Just for testing
if (isset($_POST['submit'])) {
echo $action=$conn->real_escape_string($_POST['action']);
echo $decrypted_p_id=$conn->real_escape_string($_POST['p_id']);
}
I got an output
addcart
1 //instated of one It should display four. right?
I know I will get one because I set the value="1" but is there any other option
to get the quantity whatever user choose?
Or do you have any other code to do this?
Thanks you!
/*increase the product qty*/
/*increase the product qty*/
$(".ddd").on("click", function () {
var $button = $(this),
$input = $button.closest('.sp-quantity').find("input.quntity-input");
var oldValue = $input.val(),
newVal;
if ($.trim($button.text()) == "+") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$input.val(newVal);
var price = $('.total_amount').data('price');
$('.total_amount').html(price * newVal);
});
.sp-quantity {
width:150px;
float: left;
height:42px;
margin-right: 10px;
}
.sp-minus {
width:40px;
height:40px;
float:left;
text-align:center;
}
.sp-input {
border:1px solid #e1e1e1;
border-left:0px solid black;
float:left;
}
.sp-plus {
width: 41px;
height: 40px;
border: 1px solid #f44336;
float: left;
margin-left: -1px;
text-align: center;
}
.sp-input input {
width:40px;
height:39px;
text-align:center;
border: none;
}
.sp-input input:focus {
border:1px solid #f44336;
border: none;
}
.sp-minus a, .sp-plus a {
display: block;
width: 100%;
height: 100%;
padding: 2px;
font-size: 22px;
color: #fff;
background: #f44336;
}
.product-details .cart button {
width: 100%;
background-color: #f44336;
border: 0;
padding: 10px 0;
vertical-align: bottom;
color: #fff;
max-width: 150px;
}
<main class="product-details">
<section class="pro-detail-sec">
<!-- counter and cart div -->
<div class="counter-cart clearfix">
<div class="sp-quantity">
<div class="sp-minus fff"><a class="ddd" href="javascript:void(0)" data-multi="-1">-</a></div>
<div class="sp-input">
<input type="text" class="quntity-input" value="1" />
</div>
<div class="sp-plus fff"><a class="ddd" href="javascript:void(0)" data-multi="1">+</a></div>
</div>
<!-- add to car -->
<div class="cart">
<form action="test15.php" method="POST">
<button type="submit" name="submit">Add to cart</button>
<input type="hidden" name="action" value="addcart"/>
<input type="hidden" name="p_id" value="1"/>
</form>
</div>
</div>
</section>
</main>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
You should place the
<input type="text" class="quntity-input" value="1" />
element inside your form in order to submit the selected quantity when clicking the "Add to cart" button. An alternative would be setting the value of the "p_id" input element to the desired quantity in your javscript code when incrementing or decrementing the value.
Seems like you're not updating p_id value when increasing/decreasing it.
var qty = $("#p_id");
$(".ddd").on("click", function() {
var $button = $(this),
$input = $button.closest('.sp-quantity').find("input.quntity-input");
var oldValue = $input.val(),
newVal;
if ($.trim($button.text()) == "+") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$input.val(newVal);
var price = $('.total_amount').data('price');
$('.total_amount').html(price * newVal);
qty.val(newVal);
});
Now, when you'll increase or decrease user quantity, it will update p_id input value, which is the one you are retrieving from PHP
Your JS is updating the value of the input with class .quntity-input, but you are looking at your hidden field with the name p_id.
You can't submit input that are not inside the form tag which is why .quntity-input is not being submitted. You need to also update the value of the input with name p_id if you want that to reflect the new value.

Textarea which counting entered symbolys

function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
// var last2 = 100 - integer2;
if (symbolCount >= 100) {
document.querySelector('.hidden_block').style.color = 'green';
}
else if (symbolCount <= 100) {
document.querySelector('.hidden_block').style.color = 'black';
document.querySelector('.error').style.display = "block";
}
else {
document.getElementById('max').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
email.addEventListener("click", function(){
document.querySelector('.hidden_block').style.display = 'block';
document.getElementById('max').style.display = 'none';
});
#max, #max2 {
text-align: right;
margin-right: 55px;
}
.hidden_block {
display: none;
text-align: right;
margin-right: 55px;
}
.error {
display: none;
color: red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<label for="email">Positive</label>
<textarea type="email" class="form-control" id="email" oninput="someFunc()" placeholder="Tell people about your experience: describe the place or activity, recommendations for travelers?"></textarea>
<p id="max">Minimal length - symbols</p>
<div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (minimum:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long. Adding details really helps travelers.</span>
Hi everyone.I have a that simple textarea field.I need to realize something like that.When u write less than 100 words and click the outside of the email id the border color must be red.And error class must displayed.And i need to if the textarea field is empty the tag p with id max must be display block if the user will write any symbol the id max must bu display none.Thanks for help
function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
var integerValue = document.getElementById('email');
var hidden_block = document.querySelector('.hidden_block');
var max = document.getElementById('max');
var error = document.querySelector('.error');
var positive = document.getElementById("positive");
// var last2 = 100 - integer2;
if (integer >= 1) {
hidden_block.style.display = 'inline-block';
max.style.display = 'none';
integerValue.classList.add("form-control");
} else {
hidden_block.style.display = 'none';
max.style.display = 'block';
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
}
integerValue.addEventListener("click", function(){
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
});
//Red error and border
document.body.addEventListener("click", function(e) {
var target = e.target || e.srcElement;
if (target !== integerValue && !isChildOf(target, integerValue)) {
error.style.display = "inline-block";
integerValue.classList.add("form-redBorder");
positive.style.color = "red";
} if (integer >= 100) {
error.style.display = "none";
integerValue.classList.remove("form-redBorder");
positive.style.color = "#002C38";
}
}, false);
function isChildOf(child, parent) {
if (child.parentNode === parent) {
return true;
} else if (child.parentNode === null) {
return false;
} else {
return isChildOf(child.parentNode, parent);
}
}
//Finished Red error and border
//Start to count symbols
if (symbolCount >= 100) {
hidden_block.style.color = 'green';
}
else if (symbolCount <= 100) {
hidden_block.style.color = 'black';
}
else {
max.style.color = 'black';
// document.getElementById('max2').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
#email {
display: block;
padding: 6px 12px;
margin: 0 auto;
width: 90% !important;
height: 120px !important;
/*border:1px solid #44A1B7 !important;*/
}
.form-control {
margin: 0 auto;
width: 90% !important;
height: 120px !important;
border:1px solid #44A1B7;
}
#positive, #negative {
padding: 14px 15px 1px 55px;
color: #002C38;
font-size: 18px;
}
.form-redBorder {
margin: 0 auto;
border:1px solid #FF0000 !important;
}
#max, #max2 {
position: absolute;
right: 1%;
margin-right: 55px;
}
.hidden_block {
position: absolute;
right: 1%;
display: none;
text-align: right;
margin-right: 55px;
}
.error {
margin-left: 55px;
display: none;
color: #FF0000;
}
<form role="form">
<div class="form-group">
<p class="help-block">About youre site.</p>
<label for="email" id="positive">Positive</label>
<textarea type="email" id="email" oninput="someFunc()" placeholder="Your review must be at least 100 characters long<br> Adding details really helps travelers"></textarea>
<p id="max">(100 character minimum)</p><div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (min:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long.<br> Adding details really helps travelers..</span>
</div>
</form>

checkbox works only after second click after search

I'm trying to create list of suppliers (checkboxes + labels) and search field to filter suppliers. I managed to get list renderered and after first load it works fine, but after I search through supplier list first click on checkbox doesn't work. I need to click twice for checkbox to become checked.
screenshot
I need checkbox to become checked after first click when searching through supplier list. Please help.
I created this fiddle here
HTML:
<div class="col-sm-12">
<div class="infoBlock suppliersWrapper">
<div class="blockTitle">Supplier:</div>
<div class="blockContent">
<p class="checkedSupliersTitile">Supplier list:</p>
<div class="row">
<div class="col-sm-12 col-lg-8">
<input type="text" class="form-control stickTop" placeholder="Search..." id="SearchSupplierInput">
<ul class="supplierList scrollable" id="suppliers"></ul>
</div>
<div class="col-sm-12 col-lg-4">
<p class="checkedSupliersTitile">Checked suppliers:</p>
<p class="checkedSupliersText" id="checkedSuppliers">no suppliers selected</p>
</div>
</div>
</div>
</div>
</div>
CSS:
.supplierList label {
color: #575757;
display: block;
font-size: 15px;
font-weight: 400;
cursor:pointer;
font-family: 'Ubuntu', sans-serif;
}
.supplierList input[type="checkbox" ]{
width : 2em;
margin : 0;
padding : 0;
font-size : 1em;
opacity : 0;
}
.supplierList input[type="checkbox" ] + label{
display : inline-block;
margin-left : -1em;
line-height : 1.5em;
position:relative;
z-index: 33;
}
.supplierList input[type="checkbox"] + label::before {
border: 1px solid #d6d6d6;
border-radius: 1px;
content: "";
height: 20px;
left: -1.8em;
position: absolute;
top: 0.06em;
width: 20px;
-webkit-box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
-moz-box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
background: #ffffff;
}
.supplierList input[type="checkbox" ]:checked + label:before{
background:#46c87c;
}
.supplierList input[type="checkbox"]:checked + label::after {
color: #fff;
content: "";
font-family: "fontawesome";
left: -1.6em;
position: absolute;
top: 0;
}
JavaScript:
$(document).ready(function() {
var SupplierList = [{"name":"125","id":"1"},
{"name":"2Bit Telecom Corporation","id":"2"},
{"name":"Alleven Telecom Corp Standart","id":"3"}];
var selectedSuppliers = [];
// Собираем и фильтруем активных поставшиков
renderSupplierList(SupplierList);
$("#SearchSupplierInput").on("change paste keyup", function() {
var userInput = $(this).val();
var my_json = JSON.stringify(SupplierList);
var filtered_supplierList = find_in_object(JSON.parse(my_json), {name:userInput});
if (userInput.length >= 3) {
$("#suppliers").html("");
renderSupplierList(filtered_supplierList);
} else if(!userInput) {
$("#suppliers").html("");
renderSupplierList(SupplierList);
}
});
function renderSupplierList(array) {
array.forEach(function(item, i) {
if(typeof selectedSuppliers["id"+item.id] === 'undefined') {
var ifCheckd = "";
}
else {
var ifCheckd = "checked";
}
$("#suppliers").append('\
<li><span>\n\
<input class="supplierSelect" type="checkbox" id="supplier'+i+'" ' + ifCheckd + ' name="supplier" value="'+ item.id +'"> \n\
<label for="supplier'+i+'">'+ item.name +'</label>\n\
</span></li>');
});
}
function find_in_object(my_object, my_criteria) {
return my_object.filter(function(obj) {
//console.log(obj);
return Object.keys(my_criteria).every(function(c) {
//if (obj[c].search(/my_criteria[c]/i) == -1) {
if (obj[c].search(new RegExp(my_criteria[c], "i")) == -1) {
return false;
} else {
return true;
}
});
});
}
$('.supplierList').on('change', 'input[type=checkbox]', function() {
supplierCheckboxChange(this);
});
function sortSingle(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
function supplierCheckboxChange(currEl) {
var cText = $( currEl ).siblings("label").text();
var cID = "id" + currEl.value;
if(currEl.checked) {
selectedSuppliers[cID] = cText;
}
else {
delete selectedSuppliers[cID];
}
var tmpSuppl = [];
for (var key in selectedSuppliers) {
tmpSuppl.push(selectedSuppliers[key]);
}
tmpSuppl.sort(function(a, b) {
var x = a.toLowerCase(); var y = b.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
var suppliers = tmpSuppl.join(', ');
if (!suppliers) {
suppliers = "no suppliers selected";
}
$('#checkedSuppliers').text(suppliers);
}
});
This happens because your renderList function is being called more than once. First keyup is triggered when you press a key and then when text box looses focus(when you click on checkbox) change is triggered.
This causes your renderList method to get executed twice and the checked checkbox gets replace by a new checkbox.
To fix this, just change
$("#SearchSupplierInput").on("change paste keyup", function() { ... }
To
$("#SearchSupplierInput").on("paste keyup", function() { ... }
Have a look at this fiddle and check the console. https://jsfiddle.net/nh7u4Lck/2/

Missing word game (gap filler)

i am making a little word game where theres a missing word and if you fill in the input field with the correct answer it turns green
I would like to add a functionality to this code but I am not sure how
I want to edit it so if you put a wrong answer in it turns red
at the minute it just adds up your score and turns green if you put in the right answer
i know the answer is to do with the end of the js file where it turns it green if correct
this is the html
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'> </script>
<script type="text/javascript">
$(document).ready(function(){
$("input").not( $(":button") ).keypress(function (evt) {
if (evt.keyCode == 13) {
iname = $(this).val();
if (iname !== 'Submit'){
var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
var index = fields.index( this );
if ( index > -1 && ( index + 1 ) < fields.length ) {
fields.eq( index + 1 ).focus();
}
return false
}
}
});
});</script>
<script type="text/javascript" src="prolinguis-gap-filler.js"></script>
<div style="font-family:Helvetica; font-size: 18px; vertical-align:bottom; color:#3e2e41; margin:16px 0;"> Score: <label id="label_score">0%</label></div>
<form class="game-form" style="padding: 0px; width: 100%; margin: 10px auto;" >
<!-- //////////////////////////////////////////////////////////////////////////////////////// -->
<div class="game-hold" style=" width: 100%; text-align: left; display: inline-block;">
<p style="font-size: 14px; font-weight: bold; margin: 5px 0; color: #333333;">Question 1</p>
<p>Where is Stephen from? <input TYPE="text" id="ctr1" onBlur="validate(this.value, this.id)" style="text-transform: uppercase; font-family:Helvetica; font-size: 10px; width:150px; height:18px; text-align: left; color:#000000;"></input></p>
</div>
<!-- //////////////////////////////////////////////////////////////////////////////////////// -->
<div class="game-hold" style=" width: 100%; text-align: left; display: inline-block;">
<p style="font-size: 14px; font-weight: bold; margin: 5px 0; color: #333333;">Question 2</p>
<p>If someone asks you, what’s cooking? You shouldn’t answer with: <input TYPE="text" id="ctr2" onBlur="validate(this.value, this.id)" style="text-transform: uppercase; font-family:Helvetica; font-size: 10px; width:150px; height:18px; text-align: left; color:#000000;"></input></p>
</div>
<!-- //////////////////////////////////////////////////////////////////////////////////////// -->
<div class="game-hold" style=" width: 100%; text-align: left; display: inline-block;">
<p style="font-size: 14px; font-weight: bold; margin: 5px 0; color: #333333;">Question 3</p>
<p>Instead, just say <input TYPE="text" id="ctr3" onBlur="validate(this.value, this.id)" style="text-transform: uppercase; font-family:Helvetica; font-size: 10px; width:150px; height:18px; text-align: left; color:#000000;"></input></p>
</div>
</form>
and in a js file i have this
<script>
var ctr = 0
var score_ctr = 0
function validate(value, id) {
if (id =='ctr1' && (value.toUpperCase()=="UNITED STATES" || value.toUpperCase()=="USA" || value.toUpperCase()=="AMERICA")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value="UNITED STATES";
}
if (id =='ctr2' && (value.toUpperCase()=="GOOD")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value="GOOD";
}
if (id =='ctr3' && (value.toUpperCase()=="NOTHING MUCH" || value.toUpperCase()=="NOT MUCH")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value="NOTHING MUCH";
}
}
function correct_answer (id) {
score_ctr = (ctr * 100) / 3
document.getElementById('label_score').innerHTML = score_ctr.toFixed(0) + '%'
document.getElementById(id).disabled=true;
document.getElementById(id).style.backgroundColor = '#c1d82f'
document.getElementById(id).style.cursor="default"
}
</script>
Change validate(value, id) to the following:
function validate(value, id) {
if (id == 'ctr1' && (value.toUpperCase() == "UNITED STATES" || value.toUpperCase() == "USA" || value.toUpperCase() == "AMERICA")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value = "UNITED STATES";
}
else if (id == 'ctr2' && (value.toUpperCase() == "GOOD")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value = "GOOD";
}
else if (id == 'ctr3' && (value.toUpperCase() == "NOTHING MUCH" || value.toUpperCase() == "NOT MUCH")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value = "NOTHING MUCH";
}
else
{
document.getElementById(id).style.backgroundColor = '#ff0000';
document.getElementById(id).style.cursor = "default";
}
This will go through and check all the different input fields, and if no correct answer is found, will set the background of the last blurred field to red.
Just a hint, if you want to clean up your code a bit, consider using a switch statement to determine which id you're checking.

Categories

Resources