UPDATE WITH SOLUTION:
I moved the unordered list to go after the go button,
<div class="row">
<form class="navbar-form suggest-holder">
<input class="form-control input-lg suggest-prompt" type="text" placeholder="Search...">
<select class="form-control input-lg">
<option>All</option>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
<button type="submit" class="btn btn-primary btn-lg">Go</button>
<ul></ul>
</form>
</div>
and added the following to my CSS:
.form-control {
float: left;
}
I have a search bar in my header that is using a JS function for autocomplete based on a small list of sample products.
My site has several categories that can be searched, similar to Amazon, so to the right of the search input box, there is a drop-down menu and a "go" button.
Before I added the autocomplete JS, these were horizontally aligned. Now, the category drop-down and the go button are being pushed below the search input box.
How can I get them horizontally aligned again? I have included a fiddle with the HTML/CSS
HTML
<div class="col-xs-12 col-sm-9 col-md-9 col-lg-9 search-block">
<div class="row">
<form class="navbar-form suggest-holder">
<input class="form-control input-lg suggest-prompt" type="text" placeholder="Search...">
<ul></ul>
<select class="form-control input-lg">
<option>All</option>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
</select>
<button type="submit" class="btn btn-primary btn-lg">Go</button>
</form>
</div>
</div>
CSS:
.suggest-holder {
input {
border: 1px solid $gray-lighter;
}
ul {
list-style: none;
border: 1px solid $gray-lighter;
background-color: white;
width:65%;
}
li {
padding: 5px;
position: inherit;
}
li:hover {
cursor: pointer;
}
li:hover, li.active {
background: rgba(100,100,100,.2);
}
}
.suggest-name {
font-weight: bold;
display: block;
margin-left: 40px;
}
.suggest-sku {
font-style: italic;
font-size:$font-size-small;
color: $gray-light;
}
.suggest-image {
height: 35px;
float: left;
padding-right: 5px;
margin-top: -20px;
}
header .search-block {
input {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
width: 65% !important;
#media (max-width:$screen-xs) {
width: 47% !important;
}
}
select {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
padding-top: 5px;
padding-left: 5px;
padding-bottom: 5px;
padding-right: 5px;
margin-left: -5px;
width: 20% !important;
#media (max-width:$screen-xs) {
width: 30% !important;
}
}
button {
vertical-align: top;
width: 14% !important;
#media (min-width:$screen-lg) {
width: 8% !important;
}
#media (max-width:$screen-xs) {
width: 21% !important;
}
}
.form-group {
> form {
> * {
display: inline-block;
}
#media (max-width:$screen-xs) {
text-align: center;
margin-left: 0;
margin-right: 0;
#include pad-sides(0);
}
}
}
}
input:focus::-webkit-input-placeholder { color:transparent; }
input:focus:-moz-placeholder { color:transparent; } /* FF 4-18 */
input:focus::-moz-placeholder { color:transparent; } /* FF 19+ */
input:focus:-ms-input-placeholder { color:transparent; } /* IE 10+ */
JS
var data = [
{
image: src = "http://placehold.it/35x35",
name: 'apples',
sku: '61583318'
},
{
image: src = "http://placehold.it/35x35",
name: 'oranges',
sku: '924335'
},
{
image: src = "http://placehold.it/35x35",
name: 'grapes',
sku: '73940'
},
{
image: src = "http://placehold.it/35x35",
name: 'strawberries',
sku: '66155'
},
{
image: src = "http://placehold.it/35x35",
name: 'string beans',
sku: '112509'
},
{
image: src = "http://placehold.it/35x35",
name: 'apricot',
sku: '112984'
}
];
// Suggest section holder
var $suggestedHL = $('.suggest-holder');
// Suggestions UL
var $suggestedUL = $('ul', $suggestedHL);
// Suggestions LI
var $suggestedLI = $('li', $suggestedHL);
// Selected Items UL
var $selectedUL = $('#selected-suggestions');
// Keyboard Nav Index
var index = -1;
function addSuggestion(el){
$selectedUL.append($('<li>' + el.find('.suggest-name').html() + '</li>'));
}
$('input', $suggestedHL).on({
keyup: function(e){
var m = false;
if(e.which == 38){
if(--index < 0){
index = 0;
}
m = true;
}else if(e.which == 40){
if(++index > $suggestedLI.length - 1){
index = $suggestedLI.length-1;
}
m = true;
}
if(m){
// Remove the active class
$('li.active', $suggestedHL).removeClass('active');
$suggestedLI.eq(index).addClass('active');
}else if(e.which == 27){
index = -1;
// Esc key
$suggestedUL.hide();
}else if(e.which == 13){
// Enter key
if(index > -1){
addSuggestion($('li.active', $suggestedHL));
index = -1;
$('li.active', $suggestedHL).removeClass('active');
}
}else{
index = -1;
// Clear the ul
$suggestedUL.empty();
// Cache the search term
$search = $(this).val();
// Search regular expression
$search = new RegExp($search.replace(/[^0-9a-z_]/i), 'i');
// Loop through the array
for(var i in data){
if(data[i].name.match($search)){
$suggestedUL.append($("<li><span class='suggest-name'>" + data[i].name + "</span><span class='suggest-sku'>" + data[i].sku + "</span><img src=" + data[i].image + " class='suggest-image'/></li>"));
}
}
// Show the ul
$suggestedUL.show();
}
if($(this).val() == ''){
$suggestedUL.hide();
}
},
keydown: function(e){
if(e.which == 38 || e.which == 40 || e.which == 13){
e.preventDefault();
}
},
focus: function(e){
if($(this).val() != ''){
$suggestedUL.show();
}
}
});
$suggestedHL.on('click', 'li', function(e){
addSuggestion($(this));
});
$('body').on('click', function(e) {
if (!$(e.target).closest('.suggest-holder li, .suggest-holder input').length) {
$suggestedUL.hide();
};
});
https://jsfiddle.net/sox0sxmz/1/
Try putting display: inline-block on all of the elements. E.g. form > * { display: inline-block;}. JSfiddle
You could also use float: left to not have the additional margins JSfiddle.
UPDATE:
Use:
.form-control {
float: left;
}
JSfiddle
There is a unordered list just before the select box which is causing the problem. It's defined as display:block and forcing the select box and the button to the next line.
You need another wrapper for the input and ul element which shows the results. Then you need elements with display-inline.
Here your jsfiddle: https://jsfiddle.net/sox0sxmz/8/
<div id-"my-container">
<input class="form-control input-lg suggest-prompt" type="text" placeholder="Search...">
<ul></ul>
</div>
Then apply a float:left to the container.
CSS:
form > * {
display: inline-block;
}
#my-container{
float: left;
}
Related
I am trying to combine Input values. Below is my working code, any help is appreciated.
Here is my code:
getCodeBoxElement(index) {
return document.getElementById("codeBox" + index);
}
onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
console.log((<HTMLInputElement>this.getCodeBoxElement(index)).value);
if ((<HTMLInputElement>this.getCodeBoxElement(index)).value.length === 1) {
if (index !== 6) {
this.getCodeBoxElement(index + 1).focus();
} else {
this.getCodeBoxElement(index).blur();
// Submit code
// for(var i=0; i<6; i++){
// this.verificationCode = (<HTMLInputElement>this.getCodeBoxElement(i)).toString;
// console.log(this.verificationCode);
// }
console.log("submit code ");
}
}
if (eventCode === 8 && index !== 1) {
this.getCodeBoxElement(index - 1).focus();
}
}
onFocusEvent(index) {
for (var item = 1; item < index; item++) {
const currentElement = this.getCodeBoxElement(item);
if (!(<HTMLInputElement>currentElement).value) {
currentElement.focus();
break;
}
}
}
/* Body Styling only end */
section {
display: flex;
/* align-items: center;
width: 100vw;
height: 100vh; */
text-align: center;
}
section form {
display: flex;
align-items: center;
width: auto;
margin-left: 12px;
/* margin: 0 auto; */
}
section form input {
width: 40px;
height: 40px;
text-align: center;
margin-left: -10px;
border: none;
border-radius: 10px;
}
section form input:last-child {
margin-right: 0;
}
section form input::-webkit-inner-spin-button,
section form input::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
section form input:focus,
section form input.focus {
border-color: green;
outline: none;
box-shadow: none;
}
<section>
<form style="margin-top: 10px;">
<input id="codeBox1" type="text" maxlength="1" (keyup)="onKeyUpEvent(1, $event)"
(focus)="onFocusEvent(1)" autocomplete="off">
<input id="codeBox2" type="text" maxlength="1" (keyup)="onKeyUpEvent(2, $event)"
(focus)="onFocusEvent(2)" autocomplete="off">
<input id="codeBox3" type="text" maxlength="1" (keyup)="onKeyUpEvent(3, $event)"
(focus)="onFocusEvent(3)" autocomplete="off">
<input id="codeBox4" type="text" maxlength="1" (keyup)="onKeyUpEvent(4, $event)"
(focus)="onFocusEvent(4)" autocomplete="off">
<input id="codeBox5" type="text" maxlength="1" (keyup)="onKeyUpEvent(5, $event)"
(focus)="onFocusEvent(5)" autocomplete="off">
<input id="codeBox6" type="text" maxlength="1" (keyup)="onKeyUpEvent(6, $event)"
(focus)="onFocusEvent(6)" autocomplete="off">
<!-- <input id="codeBox5" type="text" maxlength="1" (keyup)="onKeyUpEvent(5, $event)"
(focus)="onFocusEvent(5)" autocomplete="off">
<input id="codeBox6" type="text" maxlength="1" (keyup)="onKeyUpEvent(6, $event)"
(focus)="onFocusEvent(6)" autocomplete="off"> -->
</form>
</section>
Inputs return the value of the input as a string by default... So concatenating the values will combine them by default... If you want to add them as you would numbers, you would need to parse the value as an integer... Otherwise you can simply combine their values by using the plus symbol + => input.value + input2.value. Even the input type number value will return a string so by concatenating the values together you will be combining their values into one string, this would include numbers with typeof = string.
See my example inputs and their outputs for reference...
EDIT: For your issue, you can create an array to hold the value of each input through the iteration in your function... Once you have reached the threshold conditional, join the values of your array.
// create an array to hold your values
let code = new Array;
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
// save the value within your array with each selection
code[index] = getCodeBoxElement(index).value
if (index !== 4) {
getCodeBoxElement(index+ 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
// join the array values into a string using .join('');
let codeString = code.join('')
console.log(codeString)
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function getCodeBoxElement(index) {
return document.getElementById('codeBox' + index);
}
let code = new Array;
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
//code[index] = getCodeBoxElement(index).value also works
code.push(getCodeBoxElement(index).value)
if (index !== 4) {
getCodeBoxElement(index + 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
let codeString = code.join('');
let display = document.getElementById('display')
display.style.color = 'darkgreen';
display.textContent = `You have entered: ${codeString}`;
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function onFocusEvent(index) {
for (item = 1; item < index; item++) {
const currentElement = getCodeBoxElement(item);
if (!currentElement.value) {
currentElement.focus();
break;
}
}
}
// Body Styling only Begin ==============
body {
text-align: center;
background-color: lightcyan;
font-family: 'POPPINS', Open-Sans;
background: linear-gradient(to right, #4568dc, #b06ab3);
}
::selection {
color: #8e44ad;
}
// Body Styling only End ================
// Container-fluid Styling only Begin ===
.container-fluid {
.row {
align-items: center;
width: 100vw;
height: 100vh;
}
}
// Container-fluid Styling only End =====
// =====
// Passcode-wrapper Styling only Begin ==
.passcode-wrapper {
display: flex;
justify-content: space-between;
align-items: center;
width: auto;
margin: 0 auto;
input {
width: 50px;
height: 50px;
padding: 0;
margin-right: 5px;
text-align: center;
border: 1px solid gray;
border-radius: 5px;
&:last-child {
margin-right: 0;
}
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
&:focus,
&.focus {
border-color: green;
outline: none;
box-shadow: none;
}
}
}
// Passcode-wrapper Styling only End ====
<section class="container-fluid">
<div class="row">
<div class="col-md-8 offset-md-2">
<form class="text-center">
<div class="form-group">
<label for="password" class="text-white">Enter 4 Digit Password</label>
<div class="passcode-wrapper">
<input id="codeBox1" type="number" maxlength="1" onkeyup="onKeyUpEvent(1, event)" onfocus="onFocusEvent(1)">
<input id="codeBox2" type="number" maxlength="1" onkeyup="onKeyUpEvent(2, event)" onfocus="onFocusEvent(2)">
<input id="codeBox3" type="number" maxlength="1" onkeyup="onKeyUpEvent(3, event)" onfocus="onFocusEvent(3)">
<input id="codeBox4" type="number" maxlength="1" onkeyup="onKeyUpEvent(4, event)" onfocus="onFocusEvent(4)">
</div>
</div>
</form>
</div>
</div>
</section>
<div id="display"></div>
I just did it like this when I did something like this.
document.onkeyup = function() {
ch = document.getElementsByClassName("ch");
x = ch.length;
out = "";
for (y=0;x>y;y++) {
out += ch[y].value;
}
document.getElementById("final").innerHTML = out;
}
<input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'>
<span id="final" style="color: green;"></span>
Using the tags() function, there is a parameter for maximum number of tags (maxTags) you can enter into each input.
I need to hide(); the tags-input when maxTags = 2 and then
show(); when the tag is removed / not at the max.
maxTags :1 isn't working but it should be. Only 2 or more is acceptable. I tried debugging the max tags parameter but couldn't find out why maxTags: 1 is
unacceptable.
How can I change the function to allow maxTags: 1 and also show/hide the tag-input when maxTags is reached?
// max tags in tags() function:
if (opts.maxTags) {
if ($self.val().split(",").length == opts.maxTags) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// Calling the tags() function:
$("#" + formId)
.find(".input--proj")
.tags({
unique: true,
maxTags: 2
})
.autofill({
data: autolist
});
(function($) {
$.fn.tags = function(opts) {
var selector = this.selector;
//console.log("selector",selector);
// updates the original input
function update($original) {
var all = [];
var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
all.push($(this).text());
});
all = all.join(",");
$original.val(all);
}
return this.each(function() {
var self = this,
$self = $(this),
$wrapper = $("<div class='tags-wrapper'><ul></ul></div");
tags = $self.val(),
tagsArray = tags.split(","),
$ul = $wrapper.find("ul");
// make sure have opts
if (!opts) opts = {};
opts.maxSize = 50;
// add tags to start
tagsArray.forEach(function(tag) {
if (tag) {
$ul.append("<li class='tag'><span>" + tag + "</span><a href='#'>x</a></li>");
}
});
// get classes on this element
if (opts.classList) $wrapper.addClass(opts.classList);
// add input
$ul.append("<li class='tags-input'><input type='text' class='tags-secret'/></li>");
// set to dom
$self.after($wrapper);
// add the old element
$wrapper.append($self);
// size the text
var $input = $ul.find("input"),
size = parseInt($input.css("font-size")) - 4;
// delete a tag
$wrapper.on("click", "li.tag a", function(e) {
e.preventDefault();
$(this).closest("li").remove();
$self.trigger("tagRemove", $(this).closest("li").find("span").text());
update($self);
$("[data-search]").keyup();
});
// backspace needs to check before keyup
$wrapper.on("keydown", "li input", function(e) {
// backspace
if (e.keyCode == 8 && !$input.val()) {
var $li = $ul.find("li.tag:last").remove();
update($self);
$self.trigger("tagRemove", $li.find("span").text());
}
// prevent for tab
if (e.keyCode == 9) {
e.preventDefault();
}
});
// as we type
$wrapper.on("keyup", "li input", function(e) {
e.preventDefault();
$ul = $wrapper.find("ul");
var $next = $input.next(),
usingAutoFill = $next.hasClass("autofill-bg"),
$inputLi = $ul.find("li.tags-input");
// regular size adjust
$input.width($input.val().length * (size));
// if combined with autofill, check the bg for size
if (usingAutoFill) {
$next.width($next.val().length * (size));
$input.width($next.val().length * (size));
// make sure autofill doesn't get too big
if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
var list = $next.data().data;
}
// make sure we don't get too high
if ($input.width() < opts.maxSize) $input.width(opts.maxSize);
// tab, comma, enter
if (!!~[9, 188, 13].indexOf(e.keyCode)) {
var val = $input.val().replace(",", "");
var otherCheck = true;
// requring a tag to be in autofill
if (opts.requireData && usingAutoFill) {
if (!~list.indexOf(val)) {
otherCheck = false;
$input.val("");
}
}
// unique
if (opts.unique) {
// found a match already there
if (!!~$self.val().split(",").indexOf(val)) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// max tags
if (opts.maxTags) {
if ($self.val().split(",").length == opts.maxTags) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// if we have a value, and other checks pass, add the tag
if (val && otherCheck) {
// place the new tag
$inputLi.before("<li class='tag'><span>" + val + "</span><a href='#'>x</a></li>");
// clear the values
$input.val("");
if (usingAutoFill) $next.val("");
update($self);
$self.trigger("tagAdd", val);
}
}
});
});
}
})(jQuery);
var uniqueId = 1;
$(function() {
$(".btn--new").click(function() {
var copy = $("#s_item").clone(true, true);
var formId = "item_" + uniqueId;
copy.attr("id", formId);
$("#s_list").append(copy);
$("#" + formId)
.find(".input--proj")
.each(function() {
var autolist = new Array();
$.each($(".studio__project"), function(index, value) {
if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
autolist.push($(value).attr("data-proj").toLowerCase());
}
});
$("#" + formId)
.find(".input--proj")
.tags({
unique: true,
maxTags: 2
})
.autofill({
data: autolist
});
function placeholderproj() {
$(".search__label--proj")
.find(".tags-secret")
.attr("placeholder", "Enter Keyword");
}
$(document).ready(placeholderproj);
});
uniqueId++;
});
});
$(document).on("keyup , keypress", "li input", function(e) {
$.each($(".tag"), function(index, value) {
$.each($(".studio__project"), function(subIndex, subValue) {
if (
$(subValue).attr("data-proj").toLowerCase() ==
$(value).find("span").html()
) {
var itemColor = $(subValue).attr("data-color");
$(value).css("background-color", itemColor);
}
});
});
$("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
$("[data-search]").keyup();
});
$(document).ready(function() {
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
});
::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #8e8e8e;
}
::-moz-placeholder {
/* Firefox 19+ */
color: #8e8e8e;
}
:-ms-input-placeholder {
/* IE 10+ */
color: #8e8e8e;
}
:-moz-placeholder {
/* Firefox 18- */
color: #8e8e8e;
}
.tags-wrapper {
background: white;
display: flex;
position: relative;
width: 100%;
height: 50px;
top: -1px;
border: 1px solid whitesmoke;
overflow: hidden;
}
.tags-wrapper ul {
position: absolute;
display: flex;
flex: 1;
align-items: center;
top: 0;
bottom: 0;
right: 0;
left: 0;
list-style-type: none;
margin: 0;
padding: 0;
}
.tags-wrapper li {
flex-grow: 1;
margin-left: 5px;
}
.tags-wrapper li input {
display: block;
border: none;
width: 100% !important;
}
.tags-wrapper li.tag {
display: flex;
flex-grow: 0;
position: relative;
padding: 10px;
font-size: 14px;
align-items: center;
border-radius: 5px;
list-style: none;
background-image: none;
box-shadow: none;
color: white;
}
.tags-wrapper li a {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-decoration: none;
color: rgba(0, 0, 0, 0);
}
.tags-wrapper li a:hover {
background-color: rgba(0, 0, 0, 0.4);
border-radius: 5px;
color: rgba(0, 0, 0);
background-image: url("http://svgshare.com/i/3yv.svg");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.tags-wrapper input {
display: none;
}
#s_item {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.staticaly.com/gh/moofawsaw/donorport/master/auto-fill.min.js"></script>
<a id="btn_studio" href="#" class="btn btn--new ripple w-button">Create</a>
<div>keywords are: blue, red, green</div>
<div id="s_list">
<div id="s_item" data-item="studio" data-mode="none" class="post__item studio__item">
<div data-item="studio" class="post__itemwrap post__itemwrap--studio">
<div class="search search--proj w-embed"><label class="search__label--proj" data-color="">
<input type="text" class="input--proj" autocomplete="off" placeholder="">
</label></div>
<div class="w-dyn-list">
<div class="w-dyn-items">
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Blue" data-color="blue"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Green" data-color="green"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Red" data-color="red"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I've added code to test maxTags value from 1 to 3. Just replace it.
Removed a tag. Show input.
$wrapper.on("click", "li.tag a", function(e) {
e.preventDefault();
$(this).closest("li").remove();
$self.trigger("tagRemove", $(this).closest("li").find("span").text());
update($self);
$("[data-search]").keyup();
$input.show(); // show input on remove
});
If string has no content, return 0. Else use split to find number of elements.
if (opts.maxTags) {
var len = $self.val();
len = len.trim().length > 0 ? len.split(',').length : 0;
(function($) {
$.fn.tags = function(opts) {
var selector = this.selector;
//console.log("selector",selector);
// updates the original input
function update($original) {
var all = [];
var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
all.push($(this).text());
});
all = all.join(",");
$original.val(all);
}
return this.each(function() {
var self = this,
$self = $(this),
$wrapper = $("<div class='tags-wrapper'><ul></ul></div");
tags = $self.val(),
tagsArray = tags.split(","),
$ul = $wrapper.find("ul");
// make sure have opts
if (!opts) opts = {};
opts.maxSize = 50;
// add tags to start
tagsArray.forEach(function(tag) {
if (tag) {
$ul.append("<li class='tag'><span>" + tag + "</span><a href='#'>x</a></li>");
}
});
// get classes on this element
if (opts.classList) $wrapper.addClass(opts.classList);
// add input
$ul.append("<li class='tags-input'><input type='text' class='tags-secret'/></li>");
// set to dom
$self.after($wrapper);
// add the old element
$wrapper.append($self);
// size the text
var $input = $ul.find("input"),
size = parseInt($input.css("font-size")) - 4;
// delete a tag
$wrapper.on("click", "li.tag a", function(e) {
e.preventDefault();
$(this).closest("li").remove();
$self.trigger("tagRemove", $(this).closest("li").find("span").text());
update($self);
$("[data-search]").keyup();
$input.show(); // show input on remove
});
// backspace needs to check before keyup
$wrapper.on("keydown", "li input", function(e) {
// backspace
if (e.keyCode == 8 && !$input.val()) {
var $li = $ul.find("li.tag:last").remove();
update($self);
$self.trigger("tagRemove", $li.find("span").text());
}
// prevent for tab
if (e.keyCode == 9) {
e.preventDefault();
}
});
// as we type
$wrapper.on("keyup", "li input", function(e) {
e.preventDefault();
$ul = $wrapper.find("ul");
var $next = $input.next(),
usingAutoFill = $next.hasClass("autofill-bg"),
$inputLi = $ul.find("li.tags-input");
// regular size adjust
$input.width($input.val().length * (size));
// if combined with autofill, check the bg for size
if (usingAutoFill) {
$next.width($next.val().length * (size));
$input.width($next.val().length * (size));
// make sure autofill doesn't get too big
if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
var list = $next.data().data;
}
// make sure we don't get too high
if ($input.width() < opts.maxSize) $input.width(opts.maxSize);
// tab, comma, enter
if (!!~[9, 188, 13].indexOf(e.keyCode)) {
var val = $input.val().replace(",", "");
var otherCheck = true;
// requring a tag to be in autofill
if (opts.requireData && usingAutoFill) {
if (!~list.indexOf(val)) {
otherCheck = false;
$input.val("");
}
}
// unique
if (opts.unique) {
// found a match already there
if (!!~$self.val().split(",").indexOf(val)) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// max tags
if (opts.maxTags) {
var len = $self.val();
len = len.trim().length > 0 ? len.split(',').length : 0;
if (len == opts.maxTags - 1) $input.hide();
if (len == opts.maxTags) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// if we have a value, and other checks pass, add the tag
if (val && otherCheck) {
// place the new tag
$inputLi.before("<li class='tag'><span>" + val + "</span><a href='#'>x</a></li>");
// clear the values
$input.val("");
if (usingAutoFill) $next.val("");
update($self);
$self.trigger("tagAdd", val);
}
}
});
});
}
})(jQuery);
var uniqueId = 1;
$(function() {
$(".btn--new").click(function() {
var copy = $("#s_item").clone(true, true);
var formId = "item_" + uniqueId;
copy.attr("id", formId);
$("#s_list").append(copy);
$("#" + formId)
.find(".input--proj")
.each(function() {
var autolist = new Array();
$.each($(".studio__project"), function(index, value) {
if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
autolist.push($(value).attr("data-proj").toLowerCase());
}
});
$("#" + formId)
.find(".input--proj")
.tags({
unique: true,
maxTags: 1
})
.autofill({
data: autolist
});
function placeholderproj() {
$(".search__label--proj")
.find(".tags-secret")
.attr("placeholder", "Enter Keyword");
}
$(document).ready(placeholderproj);
});
uniqueId++;
});
});
$(document).on("keyup , keypress", "li input", function(e) {
$.each($(".tag"), function(index, value) {
$.each($(".studio__project"), function(subIndex, subValue) {
if (
$(subValue).attr("data-proj").toLowerCase() ==
$(value).find("span").html()
) {
var itemColor = $(subValue).attr("data-color");
$(value).css("background-color", itemColor);
}
});
});
$("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
$("[data-search]").keyup();
});
$(document).ready(function() {
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
});
::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #8e8e8e;
}
::-moz-placeholder {
/* Firefox 19+ */
color: #8e8e8e;
}
:-ms-input-placeholder {
/* IE 10+ */
color: #8e8e8e;
}
:-moz-placeholder {
/* Firefox 18- */
color: #8e8e8e;
}
.tags-wrapper {
background: white;
display: flex;
position: relative;
width: 100%;
height: 50px;
top: -1px;
border: 1px solid whitesmoke;
overflow: hidden;
}
.tags-wrapper ul {
position: absolute;
display: flex;
flex: 1;
align-items: center;
top: 0;
bottom: 0;
right: 0;
left: 0;
list-style-type: none;
margin: 0;
padding: 0;
}
.tags-wrapper li {
flex-grow: 1;
margin-left: 5px;
}
.tags-wrapper li input {
display: block;
border: none;
width: 100% !important;
}
.tags-wrapper li.tag {
display: flex;
flex-grow: 0;
position: relative;
padding: 10px;
font-size: 14px;
align-items: center;
border-radius: 5px;
list-style: none;
background-image: none;
box-shadow: none;
color: white;
}
.tags-wrapper li a {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-decoration: none;
color: rgba(0, 0, 0, 0);
}
.tags-wrapper li a:hover {
background-color: rgba(0, 0, 0, 0.4);
border-radius: 5px;
color: rgba(0, 0, 0);
background-image: url("http://svgshare.com/i/3yv.svg");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.tags-wrapper input {
display: none;
}
#s_item {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.staticaly.com/gh/moofawsaw/donorport/master/auto-fill.min.js"></script>
<a id="btn_studio" href="#" class="btn btn--new ripple w-button">Create</a>
<div>keywords are: blue, red, green</div>
<div id="s_list">
<div id="s_item" data-item="studio" data-mode="none" class="post__item studio__item">
<div data-item="studio" class="post__itemwrap post__itemwrap--studio">
<div class="search search--proj w-embed"><label class="search__label--proj" data-color="">
<input type="text" class="input--proj" autocomplete="off" placeholder="">
</label></div>
<div class="w-dyn-list">
<div class="w-dyn-items">
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Blue" data-color="blue"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Green" data-color="green"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Red" data-color="red"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I have three dual listbox, im using jquery and bootstrap, here my problem is, just need to disable selected options one listbox to another two listboxs.
For example
I have 3 dual listbox,like box-1, box-2, box-3, Each box having 3 options like, opt1, opt2, opt3, If i select one option (opt1) from Box-1 then click submit, after submit, then the that option (opt1) going to disabled for remaining two boxs (box-2 and box-3).
I've tried manyway to achive this but i did't get any results.
I hope my question is understandable
EXAMPLE PICTURE..!!
Here is my full code...
FIDDLE or PLAYCODE HERE..
Here is a preview of my page..
Click to preview my page
Here is my example snippet..
(function($) {
function refresh_select($select) {
// Clear columns
$select.wrapper.selected.html('');
$select.wrapper.non_selected.html('');
// Get search value
if ($select.wrapper.search) {
var query = $select.wrapper.search.val();
}
var options = [];
// Find all select options
$select.find('option').each(function() {
var $option = $(this);
var value = $option.prop('value');
var label = $option.text();
var selected = $option.is(':selected');
options.push({
value: value,
label: label,
selected: selected,
element: $option,
});
});
// Loop over select options and add to the non-selected and selected columns
options.forEach(function(option) {
var $row = $('<a tabindex="0" role="button" class="item"></a>').text(option.label).data('value', option.value);
// Create clone of row and add to the selected column
if (option.selected) {
$row.addClass('selected');
var $clone = $row.clone();
// Add click handler to mark row as non-selected
$clone.click(function() {
option.element.prop('selected', false);
$select.change();
});
// Add key handler to mark row as selected and make the control accessible
$clone.keypress(function() {
if (event.keyCode === 32 || event.keyCode === 13) {
// Prevent the default action to stop scrolling when space is pressed
event.preventDefault();
option.element.prop('selected', false);
$select.change();
}
});
$select.wrapper.selected.append($clone);
}
// Add click handler to mark row as selected
$row.click(function() {
option.element.prop('selected', 'selected');
$select.change();
});
// Add key handler to mark row as selected and make the control accessible
$row.keypress(function() {
if (event.keyCode === 32 || event.keyCode === 13) {
// Prevent the default action to stop scrolling when space is pressed
event.preventDefault();
option.element.prop('selected', 'selected');
$select.change();
}
});
// Apply search filtering
if (query && query != '' && option.label.toLowerCase().indexOf(query.toLowerCase()) === -1) {
return;
}
$select.wrapper.non_selected.append($row);
});
}
$.fn.multi = function(options) {
var settings = $.extend({
'enable_search': true,
'search_placeholder': 'Search...',
}, options);
return this.each(function() {
var $select = $(this);
// Check if already initalized
if ($select.data('multijs')) {
return;
}
// Make sure multiple is enabled
if (!$select.prop('multiple')) {
return;
}
// Hide select
$select.css('display', 'none');
$select.data('multijs', true);
// Start constructing selector
var $wrapper = $('<div class="multi-wrapper">');
// Add search bar
if (settings.enable_search) {
var $search = $('<input class="search-input" type="text" />').prop('placeholder', settings.search_placeholder);
$search.on('input change keyup', function() {
refresh_select($select);
})
$wrapper.append($search);
$wrapper.search = $search;
}
// Add columns for selected and non-selected
var $non_selected = $('<div class="non-selected-wrapper">');
var $selected = $('<div class="selected-wrapper" id="selectedList">');
$wrapper.append($non_selected);
$wrapper.append($selected);
$wrapper.non_selected = $non_selected;
$wrapper.selected = $selected;
$select.wrapper = $wrapper;
// Add multi.js wrapper after select element
$select.after($wrapper);
// Initialize selector with values from select element
refresh_select($select);
// Refresh selector when select values change
$select.change(function() {
refresh_select($select);
});
});
}
})(jQuery);
$(document).ready(function() {
$('select').multi({
search_placeholder: 'Search',
});
$('.alltabreset').click(function() {
$('.selected-wrapper').empty();
$('a').removeClass('selected');
});
});
.alltabsubmit {
padding: 8px;
font-size: 15px;
line-height: 0.8;
color: #fff;
background-color: #680779;
border-color: #680779;
border-radius: 4px;
position: relative;
left: 43%;
}
.alltabreset {
padding: 8px;
font-size: 15px;
line-height: 0.8;
border-radius: 4px;
position: relative;
left: 43%;
color: black;
background-color: rgb(220, 215, 215);
border-radius: 4px;
}
nav>.nav.nav-tabs {
border: none;
color: #fff;
background: #272e38;
border-radius: 0;
}
nav>div a.nav-item.nav-link,
nav>div a.nav-item.nav-link.active {
border: none;
padding: 10px 25px;
color: #fff;
background: #680779;
border-radius: 0;
}
nav>div a.nav-item.nav-link.active:after {
content: "";
position: relative;
top: 52px !important;
right: 10% !important;
border: 15px solid transparent;
border-top-color: #680779;
}
.tab-content {
background: #fdfdfd;
line-height: 25px;
border: 1px solid #ddd;
border-top: 5px solid #dda0dd;
border-bottom: 5px solid #dda0dd;
padding: 30px 25px;
}
nav>div a.nav-item.nav-link:hover,
nav>div a.nav-item.nav-link:focus {
border: none;
background: #dda0dd;
color: #fff;
border-radius: 0;
transition: 0.20s linear;
}
.tabContent {
padding-top: 18px;
margin-left: 10px;
margin-right: 10px;
}
/* FIRST TAB*/
.multi-wrapper {
border: 1px solid #ccc;
border-radius: 3px;
overflow: hidden;
width: 70% !important;
position: relative;
left: 15%;
top: 35%;
}
.multi-wrapper .non-selected-wrapper,
.multi-wrapper .selected-wrapper {
box-sizing: border-box;
display: inline-block;
height: 300px !important;
overflow-y: scroll;
padding: 10px;
vertical-align: top;
width: 50%;
}
.multi-wrapper .non-selected-wrapper {
background: #fafafa;
border-right: 1px solid #ccc;
}
.multi-wrapper .selected-wrapper {
background: #fff;
}
.multi-wrapper .item {
cursor: pointer;
display: block;
padding: 5px 10px;
color: #680779;
}
.multi-wrapper .item:hover {
background: #ececec;
border-radius: 2px;
}
.multi-wrapper .search-input {
border: 0;
border-bottom: 1px solid #ccc;
border-radius: 0;
display: block;
font-size: 1em;
margin: 0;
outline: 0;
padding: 10px 20px;
width: 100%;
}
.multi-wrapper .non-selected-wrapper .item.selected {
opacity: 0.5;
cursor: not-allowed !important;
}
.multi-wrapper .non-selected-wrapper .row.selected:hover {
background: inherit;
cursor: inherit;
}
/* Third Tab */
.thirdTab {
position: relative;
left: 35%;
}
.pnl_slet {
width: 22em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body class="hold-transition sidebar-mini layout-fixed">
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<section class="content">
<div class="container-fluid">
<!-- Main content -->
<section class="content">
<div class="card card-default card-merge">
<div class="card-body">
<div class="tab-content">
<div class="tab-pane active" id="bankTab">
<h5>Box-1</h5>
<form class="form" action="##" method="post" id="banktabForm">
<div class="selectContainer" id="bankTab">
<select multiple="multiple" name="bankList" id="firstData">
<option name="opt1" value="AB">Allahabad Bank</option>
<option name="opt2" value="AN">Andhra Bank</option>
<option name="opt3" value="BI">Bank of India</option>
<option name="opt4" name="opt3" value="BB">Bank of Baroda</option>
<option name="opt5" value="BM">Bank of Maharashtra</option>
</select>
</div>
<div class="form-group">
<div class="col-xs-12">
<br>
<button class="btn btn-lg btn-success alltabsubmit" type="submit" id="firstId" onclick="showgroup_id();"><i class="glyphicon glyphicon-ok-sign"></i>Submit</button>
<button class="btn btn-lg alltabreset" type="reset" id="tabReset"><i class="glyphicon glyphicon-repeat"></i> Reset</button>
</div>
</div>
</form>
</div>
<!-- SECOND TAB -->
<div class="tab-pane" id="cashTab">
<h5>Box-2</h5>
<form class="form" action="##" method="post" id="cashtabForm">
<div class="cashContainer" id="cashTab">
<select multiple="multiple" name="cashList" id="cashList">
<option value="AB">Allahabad Bank</option>
<option value="AN">Andhra Bank</option>
<option value="BI">Bank of India</option>
<option value="BB">Bank of Baroda</option>
<option value="BM">Bank of Maharashtra</option>
</select>
</div>
<div class="form-group">
<div class="col-xs-12">
<br>
<button class="btn btn-lg btn-success alltabsubmit" type="submit" onclick="selList();"><i class="glyphicon glyphicon-ok-sign"></i>Submit</button>
<button class="btn btn-lg alltabreset" type="reset" id="tabReset"><i class="glyphicon glyphicon-repeat"></i>Reset</button>
</div>
</div>
</form>
</div>
<!-- LAST TAB -->
<div class="tab-pane" id="tdsTab">
<h5>Box-3</h5>
<form class="form" action="##" method="post" id="tdstabForm">
<div class="cashContainer" id="tdsTab">
<select multiple="multiple" name="tdsSel" id="tdsSel">
<option value="AB">Allahabad Bank</option>
<option value="AN">Andhra Bank</option>
<option value="BI">Bank of India</option>
<option value="BB">Bank of Baroda</option>
<option value="BM">Bank of Maharashtra</option>
</select>
</div>
<div class="form-group">
<div class="col-xs-12">
<br>
<button class="btn btn-lg btn-success pull-right alltabsubmit" type="submit" onclick="tdsList();"><i class="glyphicon glyphicon-ok-sign"></i> Save</button>
<button class="btn btn-lg alltabreset" type="reset" id="tabReset"><i class="glyphicon glyphicon-repeat"></i> Reset</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</div>
</section>
</div>
</body>
</html>
var val = new Array();
(function($) {
function refresh_select($select) {
// Clear columns
$select.wrapper.selected.html('');
$select.wrapper.non_selected.html('');
// Get search value
if ($select.wrapper.search) {
var query = $select.wrapper.search.val();
}
var options = [];
// Find all select options
$select.find('option').each(function() {
var $option = $(this);
var value = $option.prop('value');
var label = $option.text();
var selected = $option.is(':selected');
options.push({
value: value,
label: label,
selected: selected,
element: $option,
});
});
// Loop over select options and add to the non-selected and selected columns
options.forEach(function(option) {
var $row = $('<a tabindex="0" role="button" class="item"></a>').text(option.label).data('value', option.value);
// Create clone of row and add to the selected column
if (option.selected) {
$row.addClass('selected');
var $clone = $row.clone();
// Add click handler to mark row as non-selected
$clone.click(function() {
// to remove disabled class from item
option.element.prop('selected', false);
val.pop(option.label);
$('.non-selected-wrapper .item.selected').each(function() {
var $item_values = $(this).text();
if ($.inArray($item_values, val) == -1) {
$(this).removeClass('selected');
}
});
$select.change();
});
// Add key handler to mark row as selected and make the control accessible
$clone.keypress(function() {
if (event.keyCode === 32 || event.keyCode === 13) {
// Prevent the default action to stop scrolling when space is pressed
event.preventDefault();
option.element.prop('selected', false);
$select.change();
}
});
$select.wrapper.selected.append($clone);
}
if ($.inArray(option.label, val) !== -1) {
$row.addClass('selected');
}
// Add click handler to mark row as selected
$row.click(function() {
// to disable other items of same name in other boxes
if ($.inArray(option.label, val) == -1) {
option.element.prop('selected', 'selected');
$select.change();
val.push(option.label);
}
$('.non-selected-wrapper .item').each(function() {
var $item_values = $(this).text();
if ($.inArray($item_values, val) !== -1) {
$(this).addClass('selected');
}
});
$('.pnl_slet option').each(function() {
var options = $(this).text();
if ($.inArray(options, val) !== -1) {
$(this).attr('disabled','true');
}
});
});
// Add key handler to mark row as selected and make the control accessible
$row.keypress(function() {
if (event.keyCode === 32 || event.keyCode === 13) {
// Prevent the default action to stop scrolling when space is pressed
event.preventDefault();
option.element.prop('selected', 'selected');
$select.change();
}
});
$('.pnl_slet').change(function(){
var selected_text = $('.pnl_slet option:selected').text();
// to disable other items of same name in other boxes
if ($.inArray(selected_text, val) == -1) {
option.element.prop('selected', 'selected');
//$select.change();
val.push(selected_text);
}
$('.non-selected-wrapper .item').each(function() {
var $item_values = $(this).text();
if ($.inArray($item_values, val) !== -1) {
$(this).addClass('selected');
}
});
})
// Apply search filtering
if (query && query != '' && option.label.toLowerCase().indexOf(query.toLowerCase()) === -1) {
return;
}
$select.wrapper.non_selected.append($row);
});
}
$.fn.multi = function(options) {
var settings = $.extend({
'enable_search': true,
'search_placeholder': 'Search...',
}, options);
return this.each(function() {
var $select = $(this);
// Check if already initalized
if ($select.data('multijs')) {
return;
}
// Make sure multiple is enabled
if (!$select.prop('multiple')) {
return;
}
// Hide select
$select.css('display', 'none');
$select.data('multijs', true);
// Start constructing selector
var $wrapper = $('<div class="multi-wrapper">');
// Add search bar
if (settings.enable_search) {
var $search = $('<input class="search-input" type="text" />').prop('placeholder', settings.search_placeholder);
$search.on('input change keyup', function() {
refresh_select($select);
})
$wrapper.append($search);
$wrapper.search = $search;
}
// Add columns for selected and non-selected
var $non_selected = $('<div class="non-selected-wrapper">');
var $selected = $('<div class="selected-wrapper" id="selectedList">');
$wrapper.append($non_selected);
$wrapper.append($selected);
$wrapper.non_selected = $non_selected;
$wrapper.selected = $selected;
$select.wrapper = $wrapper;
// Add multi.js wrapper after select element
$select.after($wrapper);
// Initialize selector with values from select element
refresh_select($select);
// Refresh selector when select values change
$select.change(function() {
refresh_select($select);
});
});
}
})(jQuery);
$(document).ready(function() {
$('select').multi({
search_placeholder: 'Search',
});
$('.alltabreset').click(function() {
$('.selected-wrapper').empty();
$('a').removeClass('selected');
val = [];
});
});
Since all boxes have same options maintain a single json like this
[{name:"Allahabad Bank",id:1,selected:true},{name:"Andhra Bank",id:2,selected:false}]
and render dynamically for all three boxes
hope this helps
We have a goal number that the option tag's values must be greater than. I am using jQuery to keep the option tags hidden. They only appear if the previous siblings' values are not greater than the goal number (in this case 450).
Here is the jQuery to hide or show the select tags with their options
if ($('#maxTPH1').val() < $('#tphNeeded').val()) {
$('#selectedSourceMaterial2, #materialInput2').fadeIn(800).css("display", "inline-block");
$('#sourceMaterialDivImage').css('margin-bottom', "17%");
} else {
$('#selectedSourceMaterial2, #materialInput2').css("display", "none");
$('#sourceMaterialDivImage').css('margin-bottom', "13%");
}
This works and the select elements fade in or hide according to if their siblings' value is less than or greater than the goal number ('#tphNeeded')
The first challenge is, once I select an option (say the 3rd select tag) and it gains a value, if I change any of it's previous sibling's (the first two select tags) values to make them greater than the goal number, the third select tag is hidden, but it's value remains part of the total forms value.
Ex: If
maxTPH1 = 200:
maxTPH2 = 200:
maxTPH3 = 200:
My total value is 600. The select tags keep appearing as long as my total value is less than, in this case 450. If I go back and change select 2 to 300 my total value for the first two select tags is 500 so select 3 is hidden because their value is greater than the goal of 450, however my select tag 3's value will not go to 0 unless I set it to 0 with
if (maxTPH1 + maxTPH2 >= $('#tphNeeded').val() ) {
maxTPH3 = 0;
maxTPH4 = 0;
}
We have a limit of four select tags.
I can set the tags back to 0.
If I was two change the first two tags back to 200 again though and the third tag appeared again, the value of 200 still shows up, but now it's calculated as 0. Even though the number says 200. I believe it has something to do with the scope, or order of operations.
This is the code snippet
var maxTPH1 = 0;
var maxTPH2 = 0;
var maxTPH3 = 0;
var maxTPH4 = 0;
var tphAdditonalNeededValue;
$(document).ready(function() {
jQuery.selectValidator = function selectValidator() {
// If value of #maxTPH1 is less than #tphNeeded add a second bin, if they change option one re-evaluate
if ($('#maxTPH1').val() < $('#tphNeeded').val()) {
$('#selectedSourceMaterial2, #materialInput2').fadeIn(800).css("display", "inline-block");
$('#sourceMaterialDivImage').css('margin-bottom', "17%");
} else {
$('#selectedSourceMaterial2, #materialInput2').css("display", "none");
$('#sourceMaterialDivImage').css('margin-bottom', "13%");
}
// If value of #maxTPH1 + #maxTPH2 is less than #tphNeeded add a third bin
if ((parseInt($('#maxTPH1').val()) + parseInt($('#maxTPH2').val())) < parseInt($('#tphNeeded').val())) {
$('#selectedSourceMaterial3, #materialInput3').fadeIn(800).css("display", "inline-block");
} else {
$('#selectedSourceMaterial3, #materialInput3').css("display", "none");
$('#selectedSourceMaterial4, #materialInput4').css("display", "none");
}
// If value of #maxTPH1 + #maxTPH2 + #maxTPH3 is less than #tphNeeded add a fourth bin
if ((parseInt($('#maxTPH1').val()) + parseInt($('#maxTPH2').val()) + parseInt($('#maxTPH3').val())) < parseInt($('#tphNeeded').val())) {
$('#selectedSourceMaterial4, #materialInput4').fadeIn(800).css("display", "inline-block");
} else {
$('#selectedSourceMaterial4, #materialInput4').css("display", "none");
}
var tphAdditonalNeededValue = parseInt($('#tphNeeded').val()) -
(parseInt(maxTPH1) + parseInt(maxTPH2) + parseInt(maxTPH3) + parseInt(maxTPH4));
$('#tphAdditionalNeeded').val(tphAdditonalNeededValue);
// Puts 0 in #tphAdditionalNeeded as soon as the value becomes less than 1
// if (tphAdditonalNeededValue < 1) {
// $('#tphAdditionalNeeded').val(0);
// }
// Calculations when aggregates are selected
// Reset select options values
// if ( $('#maxTPH4').is(':hidden') ) {
// maxTPH4 = 0;
// }
// Your changes have been reverted
} // end of select Validator
// When select tag changes, take value of selected option and make it #maxTPH1 value
$('#selectedSourceMaterial1').on("change", function() {
$('#maxTPH1').val($('#selectedSourceMaterial1 option:selected').val());
if ($('#maxTPH1').val() != null) {
maxTPH1 = $('#maxTPH1').val();
}
$.selectValidator();
// $.tphAdjustment();
});
// When select tag changes, take value of selected option and make it #maxTPH2 value
$('#selectedSourceMaterial2').on("change", function() {
$('#maxTPH2').val($('#selectedSourceMaterial2 option:selected').val());
if ($('#maxTPH2').val() != null) {
maxTPH2 = $('#maxTPH2').val();
}
$.selectValidator();
});
// When select tag changes, take value of selected option and make it #maxTPH3 value
$('#selectedSourceMaterial3').on("change", function() {
$('#maxTPH3').val($('#selectedSourceMaterial3 option:selected').val());
if ($('#maxTPH3').val() != null) {
maxTPH3 = $('#maxTPH3').val();
}
$.selectValidator();
});
// When select tag changes, take value of selected option and make it #maxTPH4 value
$('#selectedSourceMaterial4').on("change", function() {
$('#maxTPH4').val($('#selectedSourceMaterial4 option:selected').val());
if ($('#maxTPH4').val() != null) {
maxTPH4 = $('#maxTPH4').val();
}
$.selectValidator();
if ((parseInt($('#maxTPH1').val()) + parseInt($('#maxTPH2').val()) + parseInt($('#maxTPH3').val()) + parseInt($('#maxTPH4').val())) < parseInt($('#tphNeeded').val())) {
alert("You do not have enough material to calibrate with the target tons desired!");
}
});
//Removes default select tags after each select is changed
$('#selectedSourceMaterial1').on("change", function() {
$('#defaultSelect1').remove(); // Removes default select tag after person selects option
});
$('#selectedSourceMaterial2').on("change", function() {
$('#defaultSelect2').remove(); // Removes default select tag after person selects option2
});
$('#selectedSourceMaterial3').on("change", function() {
$('#defaultSelect3').remove(); // Removes default select tag after person selects option2
});
$('#selectedSourceMaterial4').on("change", function() {
$('#defaultSelect4').remove(); // Removes default select tag after person selects option2
});
// Opens Calibration LightBox and Overlay
$('.calibrationButton').click(function() {
$("#calibration").css("width", "100%");
$('#sourceMaterialDiv, #sourceMaterialForm').fadeIn(1000);
$('.overlay').css("background-color", "rgba(230,230,0,0.6)"); //Gets noticeCalibrationDiv color
});
// Closes noticeCalibration div and fades in inspect reminder prompt
$('.noticeCalibration').click(function() {
$('#noticeCalibrationDiv').hide();
$('#calibrationInspectDiv').fadeIn(1000);
$('.overlay').css("background-color", "rgba(204,0,0,0.6)"); // Gets calibration Inspect color
});
// Closes calibratioInspect div and fades in configure prompt
$('.calibrationInspect').click(function() {
$('#calibrationInspectDiv').hide();
$('#targetTonsDiv, #targetTonsForm').fadeIn(1000);
$('.overlay').css("background-color", "rgba(0,179,0,0.6)"); // Gets targetTons div's color
});
// Closes calibratioInspect div and fades in configure prompt
$('.targetTons').click(function() {
$('#targetTonsDiv').hide();
$('#sourceMaterialDiv, #sourceMaterialForm').fadeIn(1000);
$('.overlay').css("background-color", "rgba(0,179,0,0.6)"); // Gets sourceMaterial div's color
});
$('.sourceMaterial').click(function() {
$('#sourceMaterialDiv').hide();
$('#adjustedTPH, #adjustedTPHFormDiv').fadeIn(1000);
$('.overlay').css("background-color", "rgba(0,0,204,0.4)"); // Gets adjustedTPH div's color
});
// Cancels calibration and closes overlay
$('.cancelCalibration').click(function() {
$("#calibration").css("width", "0");
$('.calibrationList li div').css("display", "none");
});
$('.testForError').click(function() {
$("body").css("background-color", "green");
});
// Adds class to selected radio button and removes class from sibling radio buttons for enable/disable feature
$('#ttRadioForm input').click(function() {
$(this).addClass('ttRadioSelected').siblings().removeClass('ttRadioSelected');
//Adds and removes classes and disable/enabled on input fields if related radio button is checked or unchecked
if ($('#radioHigh').hasClass('ttRadioSelected')) {
$('#inputHigh').addClass('ttInputEnabled').prop('disabled', false).siblings().removeClass('ttInputEnabled').prop('disabled', true);
}
if ($('#radioMid').hasClass('ttRadioSelected')) {
$('#inputMid').addClass('ttInputEnabled').prop('disabled', false).siblings().removeClass('ttInputEnabled').prop('disabled', true);
}
if ($('#radioLow').hasClass('ttRadioSelected')) {
$('#inputLow').addClass('ttInputEnabled').prop('disabled', false).siblings().removeClass('ttInputEnabled').prop('disabled', true);
}
});
//attach keypress to input
$('#ttInputForm input, #targetTestTons').keydown(function(event) {
// Allow special chars + arrows
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ||
(event.keyCode == 190 && event.shiftKey !== true) ||
event.keyCode == 27 || event.keyCode == 13 ||
(event.keyCode == 65 && event.ctrlKey === true) ||
(event.keyCode >= 35 && event.keyCode <= 39)) {
return;
} else {
// If it's not a number stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});
}); // End of Document.ready
/*#font-face {
font-family: 'Droid-Serif';
src: url(../fonts/Droid_Serif/DroidSerif.ttf);
}*/
body {
background-image: url("../images/scalesbackground.png");
background-size: 100% 100%;
background-repeat: no-repeat;
background-color: black;
}
/* The Overlay (background) */
.overlay {
/* Height & width depends on how you want to reveal the overlay (see JS below) */
height: 100%;
width: 0;
position: fixed;
/* Stay in place */
z-index: 100;
/* Sit on top */
left: 0;
top: 0;
background-color: rgb(0, 0, 0);
/* Black fallback color */
background-color: rgba(0, 0, 0, 0.6);
/* Black w/opacity */
overflow-x: hidden;
/* Disable horizontal scroll */
/*transition: 0.1s;*/
/* 0.5 second transition effect to slide in or slide down the overlay (height or width, depending on reveal) */
}
/* Position the content inside the overlay */
.overlay-content {
position: relative;
top: 25%;
/* 25% from the top */
width: 100%;
/* 100% width */
text-align: center;
/* Centered text/links */
}
.calibrationList {
width: 90%;
margin-top: 15%;
background-color: white;
list-style: none;
margin-left: auto;
margin-right: auto;
padding: 5px;
border: black solid 1px;
}
.calibrationList li div {
/* Stops calibration divs from displaying until jQuery shows them */
display: none;
font-family: "Arial";
font-weight: bold;
}
.calibrationList form {
margin-bottom: .8em;
}
.calibrationList li p {
display: inline-block;
margin: 0px 0px 16px 20px;
width: 75%;
font-size: 12pt;
line-height: 22px;
}
.calibrateDivImage {
display: inline-block;
width: 13%;
padding: 6px;
}
#targetTonsDiv img,
#calibrationInspectDiv img {
margin-bottom: 16%;
}
#sourceMaterialDivImage {
width: 13%;
margin-bottom: 13%;
}
#adjustedTPH img {
width: 11%;
padding: 0px;
}
.buttonDiv {
margin-left: 50%;
}
.buttonDiv button {
background-color: gray;
padding: 5px 23px 5px 23px;
font-size: 16px;
border-radius: 30px;
outline: none;
}
#targetTonsHeader,
#sourceMaterialHeader,
#adjustedTPHHeader {
text-align: center;
display: block;
margin-left: auto;
margin-right: auto;
margin-bottom: 1%;
}
#targetTonsForm {
width: 70%;
display: inline-block;
margin: 5px 0px 15px 15px;
padding: 10px 5px 5px 5px;
}
#targetTonsForm p {
text-align: center;
margin-bottom: 0;
}
#targetTonsForm form {
border: 2px solid black;
display: inline-block;
}
#ttRadioForm {
width: 30%;
line-height: 23px;
margin-right: 0px;
margin-left: 5%;
}
#ttInputForm {
margin-left: -5px;
}
#targetTestTonsForm {
border: none !important;
width: 100%;
margin-left: -7%;
margin-top: 5%;
}
#ttInputForm input {
height: 23px;
border-top: 0px;
border-right: 0px;
border-left: 0px;
border-bottom: 2px solid black;
padding-left: 5px;
outline: none;
font-size: 16px;
}
#targetTestTonsForm input {
height: 23px;
font-size: 16px;
outline: none;
margin-left: -3%;
width: 49%;
border: 2px solid black;
}
#targetTestTonsForm p {
width: 45%;
margin: 0;
padding: 0;
}
.ttTextBottomInput {
border-bottom: 0px !important;
}
#ttInputForm input:disabled {
background-color: gray;
}
#sourceMaterialForm,
#adjustedTPHFormDiv {
width: 85%;
display: inline-block;
margin-left: 1%;
}
#sourceMaterialForm select,
#adjustedTPH select {
width: 51%;
height: 23px;
font-size: 16px;
}
#selectedSourceMaterial2,
#materialInput2,
#selectedSourceMaterial3,
#materialInput3,
#selectedSourceMaterial4,
#materialInput4 {
display: none;
}
.sourceMaterialSelectInputForm,
.adjustedTPHInputForm {
display: inline-block;
width: 47%;
}
.sourceMaterialSelectInputForm input,
.adjustedTPHInputForm input {
width: 48%;
outline: none;
height: 23px;
font-size: 16px;
border: 2px solid black;
}
.maxTPH {
margin-right: -3%;
}
#tphNeededSourceMaterialP,
#tphAdditionalNeededSourceMaterialP {
width: 69%;
text-align: right;
display: inline-block;
}
.tphNeeded {
width: 22%;
display: inline-block;
}
.tphNeeded input {
width: 100%;
border: 2px solid black;
height: 23px;
font-size: 16px;
}
.maxTPHLabel {
margin-left: 8%;
}
.adjTPHLabel {
margin-left: 11%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<html>
<head>
<title>Test Modal</title>
<!-- Stylesheets -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<!-- Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="js/sourceMaterial.js"></script>
</head>
<body>
<div id="calibration" class="overlay">
<!-- Overlay content -->
<ul class="calibrationList">
<li>
<div id="sourceMaterialDiv" class="overlayContent">
<p id="sourceMaterialHeader">Please select the source material</p>
<img id="sourceMaterialDivImage" src="images/questionicon.png">
<div id="sourceMaterialForm">
<select id="selectedSourceMaterial1" name="selectedSourceMaterial1">
<option id="defaultSelect1" value="0" selected>--SELECT--</option>
<option class="selectedOption" value="100">stone</option>
<option class="selectedOption" value="200">gold</option>
<option class="selectedOption" value="300">rainbows</option>
</select>
<form id="materialInput1" class="sourceMaterialSelectInputForm">
<label class="maxTPHLabel">Max TPH</label> <label class="adjTPHLabel">Adj. TPH</label> </br>
<input class="maxTPH" type="text" id="maxTPH1" name="maxTPH1" maxlength="7" disabled>
<input class="adjTPH" type="text" id="adjTPH1" name="adjTPH1" maxlength="7" placeholder=" " disabled>
</form>
<!--Second select and form appear if additional TPH is needed -->
<select id="selectedSourceMaterial2" name="selectedSourceMaterial2">
<option id="defaultSelect2" value="0" selected>--SELECT--</option>
<option class="selectedOption" value="100">stone</option>
<option class="selectedOption" value="200">gold</option>
<option class="selectedOption" value="300">rainbows</option>
</select>
<form id="materialInput2" class="sourceMaterialSelectInputForm">
<input class="maxTPH" type="text" id="maxTPH2" name="maxTPH2" maxlength="7" placeholder=" " disabled>
<input class="adjTPH" type="text" id="adjTPH2" name="adjTPH2" maxlength="7" placeholder=" " disabled>
</form>
<!--Third select and form appear if additional TPH is needed -->
<select id="selectedSourceMaterial3" name="selectedSourceMaterial3">
<option id="defaultSelect3" value="0" selected>--SELECT--</option>
<option class="selectedOption" value="100">stone</option>
<option class="selectedOption" value="200">gold</option>
<option class="selectedOption" value="300">rainbows</option>
</select>
<form id="materialInput3" class="sourceMaterialSelectInputForm">
<input class="maxTPH" type="text" id="maxTPH3" name="maxTPH3" maxlength="7" placeholder=" " disabled>
<input class="adjTPH" type="text" id="adjTPH3" name="adjTPH3" maxlength="7" placeholder=" " disabled>
</form>
<!--Fourth select and form appear if additional TPH is needed -->
<select id="selectedSourceMaterial4" name="selectedSourceMaterial4">
<option id="defaultSelect4" value="0" selected>--SELECT--</option>
<option class="selectedOption" value="100">stone</option>
<option class="selectedOption" value="200">gold</option>
<option class="selectedOption" value="300">rainbows</option>
</select>
<form id="materialInput4" class="sourceMaterialSelectInputForm">
<input class="maxTPH" type="text" id="maxTPH4" name="maxTPH4" maxlength="7" placeholder=" " disabled>
<input class="adjTPH" type="text" id="adjTPH4" name="adjTPH4" maxlength="7" placeholder=" " disabled>
</form>
</br>
<p id="tphNeededSourceMaterialP">TPH Needed</p>
<form class="tphNeeded">
<input type="text" id="tphNeeded" name="tphNeeded" maxlength="7" value="450" disabled>
</form>
</br>
<p id="tphAdditionalNeededSourceMaterialP">Additional TPH Needed</p>
<form class="tphNeeded">
<input type="text" id="tphAdditionalNeeded" name="tphAdditionalNeeded" maxlength="7" placeholder=" " disabled>
</form>
</div>
<!--End of sourceMaterialForm -->
<div class="buttonDiv">
<button class="cancelCalibration">Cancel</button>
<button type="submit" class="sourceMaterial">Ok</button>
</div>
<!--End of buttonDiv -->
</div>
</li>
<li>
<div id="adjustedTPH" class="overlayContent">
<p id="adjustedTPHHeader">The materials were redistributed as shown</p>
<img id="infoIcon" class="calibrateDivImage" src="images/infoicon.png">
<div id="adjustedTPHFormDiv">
<select id="adjustedSourceMaterial1" name="selectedSourceMaterial1">
<?php require 'selectoptions.php'; ?>
</select>
<form id="adjustedTPH1" class="adjustedTPHInputForm">
<label class="maxTPHLabel">Max TPH</label> <label class="adjTPHLabel">Adj. TPH</label> </br>
<input class="maxTPH" type="text" id="adjustedMax1" name="maxTPH1" maxlength="7" disabled>
<input class="adjTPH" type="text" id="adjustedAdj1" name="adjTPH1" maxlength="7" placeholder=" " disabled>
</form>
</br>
<p id="tphNeededSourceMaterialP">TPH Needed</p>
<form class="tphNeeded">
<input type="text" id="tphNeeded" name="tphNeeded" maxlength="7" value="450" disabled>
</form>
</br>
<p id="tphAdditionalNeededSourceMaterialP">Additional TPH Needed</p>
<form class="tphNeeded">
<input type="text" id="tphAdditionalNeeded" name="tphAdditionalNeeded" maxlength="7" placeholder=" " disabled>
</form>
</div>
<!--End of adjustedTPHFormDiv -->
<div class="buttonDiv">
<button class="cancelCalibration">Cancel</button>
<button class="adjustedTPHButton">Ok</button>
</div>
<!--End of buttonDiv -->
</div>
<!--End of adjustedTPH Div -->
</li>
</ul>
</div>
<!--End of #calibration .overlay -->
<!-- Use any element to open/show the overlay navigation menu -->
<button class="calibrationButton"><span>Calibrate</span></button>
</body>
</html>
Let me know if you need me to explain something. This could be a useful trick that a lot of us could use if we figure it out!
You could get the total of the :visible selects...
I used a total variable below... And looped through all the visible selects.
The setTimeout() is needed because of the animation delays of hide/show the selects.
setTimeout(function(){
console.clear();
var total=0;
$("[id^='selectedSourceMaterial']:visible").each(function(){
console.log($(this).val());
total += parseInt($(this).val());
});
console.log(total);
//var tphAdditonalNeededValue = parseInt($('#tphNeeded').val()) - (parseInt(maxTPH1) + parseInt(maxTPH2) + parseInt(maxTPH3) + parseInt(maxTPH4));
var tphAdditonalNeededValue = parseInt($('#tphNeeded').val()) - total;
$('#tphAdditionalNeeded').val(tphAdditonalNeededValue);
},1000);
You can try the below snippet.
var maxTPH1 = 0;
var maxTPH2 = 0;
var maxTPH3 = 0;
var maxTPH4 = 0;
var tphAdditonalNeededValue;
$(document).ready(function() {
jQuery.selectValidator = function selectValidator() {
// If value of #maxTPH1 is less than #tphNeeded add a second bin, if they change option one re-evaluate
if ($('#maxTPH1').val() < $('#tphNeeded').val()) {
$('#selectedSourceMaterial2, #materialInput2').fadeIn(800).css("display", "inline-block");
$('#sourceMaterialDivImage').css('margin-bottom', "17%");
} else {
$('#selectedSourceMaterial2, #materialInput2').css("display", "none");
$('#sourceMaterialDivImage').css('margin-bottom', "13%");
}
// If value of #maxTPH1 + #maxTPH2 is less than #tphNeeded add a third bin
if ((parseInt($('#maxTPH1').val()) + parseInt($('#maxTPH2').val())) < parseInt($('#tphNeeded').val())) {
$('#selectedSourceMaterial3, #materialInput3').fadeIn(800).css("display", "inline-block");
} else {
$('#selectedSourceMaterial3, #materialInput3').css("display", "none");
$('#selectedSourceMaterial4, #materialInput4').css("display", "none");
}
// If value of #maxTPH1 + #maxTPH2 + #maxTPH3 is less than #tphNeeded add a fourth bin
if ((parseInt($('#maxTPH1').val()) + parseInt($('#maxTPH2').val()) + parseInt($('#maxTPH3').val())) < parseInt($('#tphNeeded').val())) {
$('#selectedSourceMaterial4, #materialInput4').fadeIn(800).css("display", "inline-block");
} else {
$('#selectedSourceMaterial4, #materialInput4').css("display", "none");
}
setTimeout(function(){
console.clear();
var total=0;
$("[id^='selectedSourceMaterial']:visible").each(function(){
console.log($(this).val());
total += parseInt($(this).val());
});
console.log(total);
//var tphAdditonalNeededValue = parseInt($('#tphNeeded').val()) - (parseInt(maxTPH1) + parseInt(maxTPH2) + parseInt(maxTPH3) + parseInt(maxTPH4));
var tphAdditonalNeededValue = parseInt($('#tphNeeded').val()) - total;
$('#tphAdditionalNeeded').val(tphAdditonalNeededValue);
},1000);
} // end of select Validator
// When select tag changes, take value of selected option and make it #maxTPH1 value
$('#selectedSourceMaterial1').on("change", function() {
$('#maxTPH1').val($('#selectedSourceMaterial1 option:selected').val());
if ($('#maxTPH1').val() != null) {
maxTPH1 = $('#maxTPH1').val();
}
$.selectValidator();
// $.tphAdjustment();
});
// When select tag changes, take value of selected option and make it #maxTPH2 value
$('#selectedSourceMaterial2').on("change", function() {
$('#maxTPH2').val($('#selectedSourceMaterial2 option:selected').val());
if ($('#maxTPH2').val() != null) {
maxTPH2 = $('#maxTPH2').val();
}
$.selectValidator();
});
// When select tag changes, take value of selected option and make it #maxTPH3 value
$('#selectedSourceMaterial3').on("change", function() {
$('#maxTPH3').val($('#selectedSourceMaterial3 option:selected').val());
if ($('#maxTPH3').val() != null) {
maxTPH3 = $('#maxTPH3').val();
}
$.selectValidator();
});
// When select tag changes, take value of selected option and make it #maxTPH4 value
$('#selectedSourceMaterial4').on("change", function() {
$('#maxTPH4').val($('#selectedSourceMaterial4 option:selected').val());
if ($('#maxTPH4').val() != null) {
maxTPH4 = $('#maxTPH4').val();
}
$.selectValidator();
if ((parseInt($('#maxTPH1').val()) + parseInt($('#maxTPH2').val()) + parseInt($('#maxTPH3').val()) + parseInt($('#maxTPH4').val())) < parseInt($('#tphNeeded').val())) {
alert("You do not have enough material to calibrate with the target tons desired!");
}
});
//Removes default select tags after each select is changed
$('#selectedSourceMaterial1').on("change", function() {
$('#defaultSelect1').remove(); // Removes default select tag after person selects option
});
$('#selectedSourceMaterial2').on("change", function() {
$('#defaultSelect2').remove(); // Removes default select tag after person selects option2
});
$('#selectedSourceMaterial3').on("change", function() {
$('#defaultSelect3').remove(); // Removes default select tag after person selects option2
});
$('#selectedSourceMaterial4').on("change", function() {
$('#defaultSelect4').remove(); // Removes default select tag after person selects option2
});
// Opens Calibration LightBox and Overlay
$('.calibrationButton').click(function() {
$("#calibration").css("width", "100%");
$('#sourceMaterialDiv, #sourceMaterialForm').fadeIn(1000);
$('.overlay').css("background-color", "rgba(230,230,0,0.6)"); //Gets noticeCalibrationDiv color
});
// Closes noticeCalibration div and fades in inspect reminder prompt
$('.noticeCalibration').click(function() {
$('#noticeCalibrationDiv').hide();
$('#calibrationInspectDiv').fadeIn(1000);
$('.overlay').css("background-color", "rgba(204,0,0,0.6)"); // Gets calibration Inspect color
});
// Closes calibratioInspect div and fades in configure prompt
$('.calibrationInspect').click(function() {
$('#calibrationInspectDiv').hide();
$('#targetTonsDiv, #targetTonsForm').fadeIn(1000);
$('.overlay').css("background-color", "rgba(0,179,0,0.6)"); // Gets targetTons div's color
});
// Closes calibratioInspect div and fades in configure prompt
$('.targetTons').click(function() {
$('#targetTonsDiv').hide();
$('#sourceMaterialDiv, #sourceMaterialForm').fadeIn(1000);
$('.overlay').css("background-color", "rgba(0,179,0,0.6)"); // Gets sourceMaterial div's color
});
$('.sourceMaterial').click(function() {
$('#sourceMaterialDiv').hide();
$('#adjustedTPH, #adjustedTPHFormDiv').fadeIn(1000);
$('.overlay').css("background-color", "rgba(0,0,204,0.4)"); // Gets adjustedTPH div's color
});
// Cancels calibration and closes overlay
$('.cancelCalibration').click(function() {
$("#calibration").css("width", "0");
$('.calibrationList li div').css("display", "none");
});
$('.testForError').click(function() {
$("body").css("background-color", "green");
});
// Adds class to selected radio button and removes class from sibling radio buttons for enable/disable feature
$('#ttRadioForm input').click(function() {
$(this).addClass('ttRadioSelected').siblings().removeClass('ttRadioSelected');
//Adds and removes classes and disable/enabled on input fields if related radio button is checked or unchecked
if ($('#radioHigh').hasClass('ttRadioSelected')) {
$('#inputHigh').addClass('ttInputEnabled').prop('disabled', false).siblings().removeClass('ttInputEnabled').prop('disabled', true);
}
if ($('#radioMid').hasClass('ttRadioSelected')) {
$('#inputMid').addClass('ttInputEnabled').prop('disabled', false).siblings().removeClass('ttInputEnabled').prop('disabled', true);
}
if ($('#radioLow').hasClass('ttRadioSelected')) {
$('#inputLow').addClass('ttInputEnabled').prop('disabled', false).siblings().removeClass('ttInputEnabled').prop('disabled', true);
}
});
//attach keypress to input
$('#ttInputForm input, #targetTestTons').keydown(function(event) {
// Allow special chars + arrows
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ||
(event.keyCode == 190 && event.shiftKey !== true) ||
event.keyCode == 27 || event.keyCode == 13 ||
(event.keyCode == 65 && event.ctrlKey === true) ||
(event.keyCode >= 35 && event.keyCode <= 39)) {
return;
} else {
// If it's not a number stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});
}); // End of Document.ready
/*#font-face {
font-family: 'Droid-Serif';
src: url(../fonts/Droid_Serif/DroidSerif.ttf);
}*/
body {
background-image: url("../images/scalesbackground.png");
background-size: 100% 100%;
background-repeat: no-repeat;
background-color: black;
}
/* The Overlay (background) */
.overlay {
/* Height & width depends on how you want to reveal the overlay (see JS below) */
height: 100%;
width: 0;
position: fixed;
/* Stay in place */
z-index: 100;
/* Sit on top */
left: 0;
top: 0;
background-color: rgb(0, 0, 0);
/* Black fallback color */
background-color: rgba(0, 0, 0, 0.6);
/* Black w/opacity */
overflow-x: hidden;
/* Disable horizontal scroll */
/*transition: 0.1s;*/
/* 0.5 second transition effect to slide in or slide down the overlay (height or width, depending on reveal) */
}
/* Position the content inside the overlay */
.overlay-content {
position: relative;
top: 25%;
/* 25% from the top */
width: 100%;
/* 100% width */
text-align: center;
/* Centered text/links */
}
.calibrationList {
width: 90%;
margin-top: 15%;
background-color: white;
list-style: none;
margin-left: auto;
margin-right: auto;
padding: 5px;
border: black solid 1px;
}
.calibrationList li div {
/* Stops calibration divs from displaying until jQuery shows them */
display: none;
font-family: "Arial";
font-weight: bold;
}
.calibrationList form {
margin-bottom: .8em;
}
.calibrationList li p {
display: inline-block;
margin: 0px 0px 16px 20px;
width: 75%;
font-size: 12pt;
line-height: 22px;
}
.calibrateDivImage {
display: inline-block;
width: 13%;
padding: 6px;
}
#targetTonsDiv img,
#calibrationInspectDiv img {
margin-bottom: 16%;
}
#sourceMaterialDivImage {
width: 13%;
margin-bottom: 13%;
}
#adjustedTPH img {
width: 11%;
padding: 0px;
}
.buttonDiv {
margin-left: 50%;
}
.buttonDiv button {
background-color: gray;
padding: 5px 23px 5px 23px;
font-size: 16px;
border-radius: 30px;
outline: none;
}
#targetTonsHeader,
#sourceMaterialHeader,
#adjustedTPHHeader {
text-align: center;
display: block;
margin-left: auto;
margin-right: auto;
margin-bottom: 1%;
}
#targetTonsForm {
width: 70%;
display: inline-block;
margin: 5px 0px 15px 15px;
padding: 10px 5px 5px 5px;
}
#targetTonsForm p {
text-align: center;
margin-bottom: 0;
}
#targetTonsForm form {
border: 2px solid black;
display: inline-block;
}
#ttRadioForm {
width: 30%;
line-height: 23px;
margin-right: 0px;
margin-left: 5%;
}
#ttInputForm {
margin-left: -5px;
}
#targetTestTonsForm {
border: none !important;
width: 100%;
margin-left: -7%;
margin-top: 5%;
}
#ttInputForm input {
height: 23px;
border-top: 0px;
border-right: 0px;
border-left: 0px;
border-bottom: 2px solid black;
padding-left: 5px;
outline: none;
font-size: 16px;
}
#targetTestTonsForm input {
height: 23px;
font-size: 16px;
outline: none;
margin-left: -3%;
width: 49%;
border: 2px solid black;
}
#targetTestTonsForm p {
width: 45%;
margin: 0;
padding: 0;
}
.ttTextBottomInput {
border-bottom: 0px !important;
}
#ttInputForm input:disabled {
background-color: gray;
}
#sourceMaterialForm,
#adjustedTPHFormDiv {
width: 85%;
display: inline-block;
margin-left: 1%;
}
#sourceMaterialForm select,
#adjustedTPH select {
width: 51%;
height: 23px;
font-size: 16px;
}
#selectedSourceMaterial2,
#materialInput2,
#selectedSourceMaterial3,
#materialInput3,
#selectedSourceMaterial4,
#materialInput4 {
display: none;
}
.sourceMaterialSelectInputForm,
.adjustedTPHInputForm {
display: inline-block;
width: 47%;
}
.sourceMaterialSelectInputForm input,
.adjustedTPHInputForm input {
width: 48%;
outline: none;
height: 23px;
font-size: 16px;
border: 2px solid black;
}
.maxTPH {
margin-right: -3%;
}
#tphNeededSourceMaterialP,
#tphAdditionalNeededSourceMaterialP {
width: 69%;
text-align: right;
display: inline-block;
}
.tphNeeded {
width: 22%;
display: inline-block;
}
.tphNeeded input {
width: 100%;
border: 2px solid black;
height: 23px;
font-size: 16px;
}
.maxTPHLabel {
margin-left: 8%;
}
.adjTPHLabel {
margin-left: 11%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<html>
<head>
<title>Test Modal</title>
<!-- Stylesheets -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<!-- Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="js/sourceMaterial.js"></script>
</head>
<body>
<div id="calibration" class="overlay">
<!-- Overlay content -->
<ul class="calibrationList">
<li>
<div id="sourceMaterialDiv" class="overlayContent">
<p id="sourceMaterialHeader">Please select the source material</p>
<img id="sourceMaterialDivImage" src="images/questionicon.png">
<div id="sourceMaterialForm">
<select id="selectedSourceMaterial1" name="selectedSourceMaterial1">
<option id="defaultSelect1" value="0" selected>--SELECT--</option>
<option class="selectedOption" value="100">stone</option>
<option class="selectedOption" value="200">gold</option>
<option class="selectedOption" value="300">rainbows</option>
</select>
<form id="materialInput1" class="sourceMaterialSelectInputForm">
<label class="maxTPHLabel">Max TPH</label> <label class="adjTPHLabel">Adj. TPH</label> </br>
<input class="maxTPH" type="text" id="maxTPH1" name="maxTPH1" maxlength="7" disabled>
<input class="adjTPH" type="text" id="adjTPH1" name="adjTPH1" maxlength="7" placeholder=" " disabled>
</form>
<!--Second select and form appear if additional TPH is needed -->
<select id="selectedSourceMaterial2" name="selectedSourceMaterial2">
<option id="defaultSelect2" value="0" selected>--SELECT--</option>
<option class="selectedOption" value="100">stone</option>
<option class="selectedOption" value="200">gold</option>
<option class="selectedOption" value="300">rainbows</option>
</select>
<form id="materialInput2" class="sourceMaterialSelectInputForm">
<input class="maxTPH" type="text" id="maxTPH2" name="maxTPH2" maxlength="7" placeholder=" " disabled>
<input class="adjTPH" type="text" id="adjTPH2" name="adjTPH2" maxlength="7" placeholder=" " disabled>
</form>
<!--Third select and form appear if additional TPH is needed -->
<select id="selectedSourceMaterial3" name="selectedSourceMaterial3">
<option id="defaultSelect3" value="0" selected>--SELECT--</option>
<option class="selectedOption" value="100">stone</option>
<option class="selectedOption" value="200">gold</option>
<option class="selectedOption" value="300">rainbows</option>
</select>
<form id="materialInput3" class="sourceMaterialSelectInputForm">
<input class="maxTPH" type="text" id="maxTPH3" name="maxTPH3" maxlength="7" placeholder=" " disabled>
<input class="adjTPH" type="text" id="adjTPH3" name="adjTPH3" maxlength="7" placeholder=" " disabled>
</form>
<!--Fourth select and form appear if additional TPH is needed -->
<select id="selectedSourceMaterial4" name="selectedSourceMaterial4">
<option id="defaultSelect4" value="0" selected>--SELECT--</option>
<option class="selectedOption" value="100">stone</option>
<option class="selectedOption" value="200">gold</option>
<option class="selectedOption" value="300">rainbows</option>
</select>
<form id="materialInput4" class="sourceMaterialSelectInputForm">
<input class="maxTPH" type="text" id="maxTPH4" name="maxTPH4" maxlength="7" placeholder=" " disabled>
<input class="adjTPH" type="text" id="adjTPH4" name="adjTPH4" maxlength="7" placeholder=" " disabled>
</form>
</br>
<p id="tphNeededSourceMaterialP">TPH Needed</p>
<form class="tphNeeded">
<input type="text" id="tphNeeded" name="tphNeeded" maxlength="7" value="450" disabled>
</form>
</br>
<p id="tphAdditionalNeededSourceMaterialP">Additional TPH Needed</p>
<form class="tphNeeded">
<input type="text" id="tphAdditionalNeeded" name="tphAdditionalNeeded" maxlength="7" placeholder=" " disabled>
</form>
</div>
<!--End of sourceMaterialForm -->
<div class="buttonDiv">
<button class="cancelCalibration">Cancel</button>
<button type="submit" class="sourceMaterial">Ok</button>
</div>
<!--End of buttonDiv -->
</div>
</li>
<li>
<div id="adjustedTPH" class="overlayContent">
<p id="adjustedTPHHeader">The materials were redistributed as shown</p>
<img id="infoIcon" class="calibrateDivImage" src="images/infoicon.png">
<div id="adjustedTPHFormDiv">
<select id="adjustedSourceMaterial1" name="selectedSourceMaterial1">
<?php require 'selectoptions.php'; ?>
</select>
<form id="adjustedTPH1" class="adjustedTPHInputForm">
<label class="maxTPHLabel">Max TPH</label> <label class="adjTPHLabel">Adj. TPH</label> </br>
<input class="maxTPH" type="text" id="adjustedMax1" name="maxTPH1" maxlength="7" disabled>
<input class="adjTPH" type="text" id="adjustedAdj1" name="adjTPH1" maxlength="7" placeholder=" " disabled>
</form>
</br>
<p id="tphNeededSourceMaterialP">TPH Needed</p>
<form class="tphNeeded">
<input type="text" id="tphNeeded" name="tphNeeded" maxlength="7" value="450" disabled>
</form>
</br>
<p id="tphAdditionalNeededSourceMaterialP">Additional TPH Needed</p>
<form class="tphNeeded">
<input type="text" id="tphAdditionalNeeded" name="tphAdditionalNeeded" maxlength="7" placeholder=" " disabled>
</form>
</div>
<!--End of adjustedTPHFormDiv -->
<div class="buttonDiv">
<button class="cancelCalibration">Cancel</button>
<button class="adjustedTPHButton">Ok</button>
</div>
<!--End of buttonDiv -->
</div>
<!--End of adjustedTPH Div -->
</li>
</ul>
</div>
<!--End of #calibration .overlay -->
<!-- Use any element to open/show the overlay navigation menu -->
<button class="calibrationButton"><span>Calibrate</span></button>
</body>
</html>
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
});