Logic Gates using HTML and JavaScript - javascript

New to HTML and JavaScript and I am attempting to make a webpage which let the user choose which gate they would like to use e.g.
AND
OR
XOR
NAND
NOR
The user enters their choice through a dropdown box then they choose the values to enter either 1 or 0.
This is all I have for the function right now, I was using the console.log to test if it was receiving the choice properly which it does, but I don't know how to move forwards from here and how to run the logic gates.
function Logic() {
console.log("Invoked Logic")
if (document.getElementById('gate').value == "1")
console.log("1")
else if (document.getElementById('gate').value == "2") {
console.log("2")
}
else if(document.getElementById('gate').value == "3") {
console.log("3")
}
else if (document.getElementById('gate').value == "4") {
console.log("4")
}
else if (document.getElementById('gate').value == "5") {
console.log("5")
}
else {
alert("Not a valid option.");
}
}
<label>Which Logic Gate would you like?</label> <select id="gate">
<option value ="d"> Please Select</option>
<option value="1" >AND</option>
<option value ="2">OR</option>
<option value="3">XOR</option>
<option value ="4">NAND</option>
<option value="5">NOR</option>
</select> <br> <br>
<label>What value would you like the second input to be?</label> <select id="v2">
<option value ="d"> Please Select</option>
<option value="b1">0</option>
<option value ="b2">1</option>
</select>
and for the value of 1 or 0 I use another drop down (two of them).
How would I go about getting the value of the two dropdowns then inputting them into the corresponding logic gates?
edit seems as though all of my if statements are pushing this error onto me.
Unexpected type coercion
I was able to fix it by using triple equals.
That isn't the main problem, my problem is that I do not understand how I can convert my two dropdown values which are strings into booleans themself and then run that into a logic gate equation.
An example of this if the user chose the "AND" gate and a 1 and 0. The 1 and 0 are converted into booleans so 1 being true and 0 being false and then outputting the result of them being ran through a logic gate so 0.

Attached the logic function to the change event of the select boxes. Checked if they all had a valid value. If so calculate the result based on the used gate.
/*
document.getElementById('gate').addEventListener('change', logic);
document.getElementById('v1').addEventListener('change', logic);
document.getElementById('v2').addEventListener('change', logic);
*/
document.getElementById('buttonId').addEventListener('click', logic);
function logic() {
var elGate = document.getElementById('gate');
var elV1 = document.getElementById('v1');
var elV2 = document.getElementById('v2');
var gateValue = elGate.value !== 'd' ? parseInt(elGate.value) : undefined;
var v1Value = elV1.value === 'b1' ? false : elV1.value === 'b2' ? true : undefined;
var v2Value = elV2.value === 'b1' ? false : elV2.value === 'b2' ? true : undefined;
var result = 'Invalid result';
if (v1Value !== undefined && v2Value !== undefined && gateValue !== undefined && gateValue > 0 && gateValue < 6) {
switch (gateValue) {
case 1:
result = (v1Value && v2Value) ? 'true' : 'false';
break;
case 2:
result = (v1Value || v2Value) ? 'true' : 'false';
break;
case 3:
result = ((v1Value && !v2Value) || (!v1Value && v2Value)) ? 'true' : 'false';
break;
case 4:
result = (!(v1Value && v2Value)) ? 'true' : 'false';
break;
case 5:
result = (!(v1Value || v2Value)) ? 'true' : 'false';
break;
default:
break;
}
}
document.getElementById('result').value = result;
}
<select id="gate">
<option value="d"> Please Select</option>
<option value="1">AND</option>
<option value="2">OR</option>
<option value="3">XOR</option>
<option value="4">NAND</option>
<option value="5">NOR</option>
</select>
<select id="v1">
<option value="d"> Please Select</option>
<option value="b1">0</option>
<option value="b2">1</option>
</select>
<select id="v2">
<option value="d"> Please Select</option>
<option value="b1">0</option>
<option value="b2">1</option>
</select>
<input id="result">
<button id="buttonId">Run Logic</button>

Related

Getting a result after mutliple variables in javascript

I´m pretty new to coding and I´ve been trying to get a website running where there are multiple forms, I want to get different outputs depending on the interaction of the various answers.
As of now I get a change in the console congruent with the selected element, it seems to be working, the variables being:
let a = document.getElementById('CAL');
a.onchange = (ev) =>{
console.log( a.value);} //Gets the CAL value of low,high,medium or naCal
let b = document.getElementById('sev-lev-2');
b.onchange = (ev) =>{
console.log( b.value);} //Gets value of RBL as low, medium or high
let c = document.getElementById('sev-lev-3');
c.onchange = (ev) =>{
console.log( c.value);} //Gets value of tooth loss as low, medium or high
let d = document.getElementById('MPD');
d.onchange = (ev) =>{
console.log( d.value);} //Gets value of maximum pocket depth as low, medium or high
let e = document.getElementById('type-bl');
e.onchange = (ev) =>{
console.log( e.value);} //Gets value of type of bone loss as low or high
let f = document.getElementById('ST3a');
{console.log(f.checked);}
f.onchange = (ev) =>
{console.log(f.checked);} //checks if Furcation is ticked in (true) or not
let g = document.getElementById('ST3b');
{console.log(g.checked);}
g.onchange = (ev) =>
{console.log(g.checked);} //checks if Moderate ridge defects is ticked in (true) or not
let h = document.getElementById('ST4');
{console.log(h.checked);}
h.onchange = (ev) =>
{console.log(h.checked);} //checks if Need complex rehab is ticked in (true) or not
I tried grouping some variables (ab) (ce) (fg), I am missing something to make these work, they always come out as undefined (when connecting a button to as an example console.log (ab), I tried multiple ways but are still stuck with this:
let ab //Gets value for CAL or RBL
if (a === "low"|| b === "low") {ab= "low"}
else if (a === "medium"|| b === "medium") {ab=== "medium"}
else if (a === "hig"|| b === "high") {ab=== "high"}
else {ab=="null"}
let fg;
if (f === "false"&& g === "false"){fg==="false"}
else {fg === "true"} ;
let ce;
if (c === "false"&& e === "false"){ce==="false"}
else {ce === "true"}
The other part of the problem is that when I get results for ab/ce/fg I would like to get the end result from a function,so that I can couple the function to a button click. I structured the function with or without the grouped variables but still could not get to work, the version with grouped variables is:
function debug(){
if (ab == "low" && d == "low" && ce == "low" && fg=="false" && h == "false" ) {console.log;{"I"}}
else if (ab == "low" && d == "medium" && ce == "low" && fg=="false" && h == "false" ) {console.log ("II")}
else if (ab == "medium" && (d == "low"|| d =="medium") && ce == "low" && fg=="false" && h == "false") {console.log ("II")}
else if (ab == "medium" && ((c== "medium" || "high") ||(d=="high")||(e=="high")||(fg=="true"))) {console.log ("III")}
else if (ab == "high" && (c!= "high" || h!="true")) {console.log ("III")}
else if (ab=="high" && d== "high" && e=="high" && fg=="true" && h == "true") {console.log ("IV")}
else {console.log("")}
}
The HTML for the forms is the following:
<div id="staging">
<div id="severity">
<h2>Severity (Site of greater loss)</h2>
<div><label for="CAL">Clinical attachment level:</label>
<select name="CAL" id="CAL" onclick="Severity()">
<option value="">--Interdental CAL--</option>
<option value="low">1-2mm</option>
<option value="medium">3-4mm</option>
<option value="high">>5mm</option>
<option value="naCal" >Not available</option>
</select>
</div>
<div id="RBL" ><label for="rx-bone-loss">Radiographic bone loss (% of root):</label>
<select name="RBL" id="sev-lev-2" onclick="Severity2()">
<option value="">--Select RBL %--</option>
<option value="low"> <15%</option>
<option value="medium">15-33%</option>
<option value="high">>33%</option>
</select>
</div>
<div id="TL"><label for="tooth-loss">Perio caused tooth loss:</label>
<select name="tooth-loss" id="sev-lev-3">
<option value="">--Or planned for extraction--</option>
<option value="low"> None</option>
<option value="medium">≤4</option>
<option value="high">≥5</option>
</select>
</div>
</div>
<div id="Complexity">
<h2>Complexity</h2>
<p><label for="max-probing-depth">Max Probing Depth:</label>
<select name="MPD" id="MPD">
<option value="">--Max PD--</option>
<option value="low"> ≤4mm</option>
<option value="medium">≤5mm</option>
<option value="high">≥6mm</option>
</select>
</p>
<p><label for="type-bl">Type of bone loss:</label>
<select name="type-bl" id="type-bl">
<option value="">--Type--</option>
<option value="low"> Mostly horizontal</option>
<option value="high">Vertical ≥3mm </option>
</select>
</p>
<form> <p><b>Additional Information:</b></p>
<input type="checkbox" id="ST3a" value="ST3a"><label for="Furcation"> Furcation involvement cl II-III</label><br>
<input type="checkbox" id="ST3b" value="ST3b"><label for="Defect"> Moderate ridge defects</label><br>
<input type="checkbox" id="ST4" value="ST4"><label for="Rehab"> Need for complex rehabilitation</label><br>
</form>
</div>
Additional problem:
First of all thanks for the answers, some of it I did understand, a great deal is too complicated for my level...
Now I got the form working on single selections, but when trying to select another value without refreshing the value seems to go to "undefined" and with a second try give an error "Uncaught TypeError: Cannot read properties of undefined (reading 'value')
at a.onchange"
this code shows the error on one variable selection:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Perio Staging and Grading</title>
</head>
<body>
<h2>Severity (Site of greater loss)</h2>
<div><label for="CAL">Clinical attachment level:</label>
<select name="CAL" id="CAL" >
<option value="">--Interdental CAL--</option>
<option value="low">1-2mm</option>
<option value="medium">3-4mm</option>
<option value="high">>5mm</option>
<option value="naCal" >Not available</option>
</select>
</div>
</div>
</div>
<button id="debug">Submit</button>
<div id="result">
</div>
<script>
let a = document.getElementById('CAL');
a.onchange = (ev) =>{
a= (a.value);} //Gets the CAL value of low,high,medium or naCal
</script>
</body>

calling dropdown functions javascript/jQuery

I have a drop down menu that displays different divs based on the selected option.
<select id='building-type'>
<option disabled selected value> -- select an option -- </option>
<option id="residential" value="residential" [...]>Residential</option>
<option id="commercial" value="commercial " [...]>Commercial</option>
<option id="corporate" value="corporate" [...]>Corporate</option>
<option id="hybrid" value="hybrid" [...]>Hybrid</option>
</select>
In those divs I call my function elevatorCalc() like so.
<div class="col-md-4" id="number-of-apartments">
<label for="residential_apartments">Number of apartments *</label>
<input onchange="elevatorCalc()" required type="number" class="form-control" id="resinput_number-of-apartments">
</div>
The function elevatorCalc() worked with radio buttons but when I switched it to a dropdown it stopped working.
this is my function
function elevatorCalc() {
const floors = document.getElementById("resinput_number-of-floors");
if (document.getElementById("commercial").checked == true) {
commercial();
} else if (document.getElementById("residential").checked == true && parseInt(floors.value) <= 20) {
residential();
} else if (document.getElementById("residential").checked == true && parseInt(floors.value) > 20) {
residential20();
} else if (document.getElementById("corporate").checked == true) {
corpo();
} else if (document.getElementById("hybrid").checked == true) {
hybrid();
}
}
My guess was that the problem came from .checked but I really don't know.
You should get the selected value like this:
let value = document.getElementById('building-type').value;
for the logic:
switch(value) {
case 'residential':
residential();
break;
case 'corporate':
corpo();
...

Set select element option on page load

I want the page to auto-select some value ('hot', 'new', etc.) depending on the
$r->category value which is loaded from database. The $r->category value contains some string that could be 'hot', 'new', etc.
Input element:
<input type="text" id="cex" value="<?php echo $r->category?>">
The select option:
<select name="ktgr" onChange="cek();">
<option id='n' value="normal">normal</option>
<option id='h' value="hot">hot</option>
<option id='nw' value="new">new</option>
<option id='u' value="upcoming">upcoming</option>
</select>
The javascript function
function cek()
{
var j = document.getElementById("cex").value;
if(j=='normal')
document.getElementById('n').selected=true;
else if(j=='hot')
document.getElementById('h').selected=true;
else if(j=='new')
document.getElementById('nw').selected=true;
else if(j=='upcomming')
document.getElementById('u').selected=true;
}
Currently, your code will set the value of the select element to the initial value every time any option is selected. For example, if 'hot' is the value from the server, and a user selects 'new', the cek function will execute in the change event and change the value back to 'hot'.
Instead, only set the select element's value to the initial value from the server once. A working example is below.
function cek() {
var j = document.getElementById("cex").value;
if (j == 'normal')
document.getElementById('n').selected = true;
else if (j == 'hot')
document.getElementById('h').selected = true;
else if (j == 'new')
document.getElementById('nw').selected = true;
else if (j == 'upcoming')
document.getElementById('u').selected = true;
}
<body onload="cek()">
<input id="cex" value="new" />
<select name="ktgr">
<option id='n' value="normal">normal</option>
<option id='h' value="hot">hot</option>
<option id='nw' value="new">new</option>
<option id='u' value="upcoming">upcoming</option>
</select>
</body>

Accept value that is not in the list - bootstrap combobox

is there a way that the user can input other values in bootstrap combobox?
from this site: https://github.com/danielfarrell/bootstrap-combobox/
i tried to remove the code below from the javascript and the user can enter any value but when i try to save it in the database the combobox value is not saving.
if (!this.selected && val !== '' ) {
this.$element.val('');
this.$source.val('').trigger('change');
this.$target.val('').trigger('change');
}
Thanks!
I'm using this workaround:
bootstrap-combobox.js line 392:
//if (!this.selected && val !== '' ) {
// this.$element.val('');
// this.$source.val('').trigger('change');
// this.$target.val('').trigger('change');
//}
$('#'+this.$source.attr('id')+'_hidden').val(val);
And in your HTML file add an hidden input text to grab the selected value:
<div class="form-group">
<select class="combobox form-control" name="theinput" id="theinput">
<option value="" selected="selected">Select or enter new</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
.....
</select>
<input type="hidden" id="theinput_hidden" name="theinput_hidden" value="">
</div>
Then in your backend read 'theinput_hidden' value.
I am late to the party. Figured someone else may be trying to use both restricted type ahead and allowing freeform.
Expanding on Alvins' tweaks, which works very well (Thanks!), I needed the combobox to allow freeform entry in some instances and restricted to the options in others.
I accomplished this by adding "allowfreeform" class to the select, then modify the js to check for it. See example below. May not be the most elegant solution but works for me.
Here's how I have it:
HTML - Restricted
<div class="form-group">
<select class="combobox form-control" name="theinput" id="theinput">
<option value="" selected="selected">Select or enter new</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
.....
</select>
</div>
HTML - Allow freeform text
<div class="form-group">
<select class="combobox form-control allowfreeform" name="theinput" id="theinput">
<option value="" selected="selected">Select or enter new</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
.....
</select>
</div>
bootstrap-combobox.js
, blur: function (e) {
var that = this;
this.focused = false;
var val = this.$element.val();
if (!this.selected && val !== '' ) {
//if (!this.selected && val !== '' ) {
// this.$element.val('');
// this.$source.val('').trigger('change');
// this.$target.val('').trigger('change');
//}
if (!this.$element.hasClass("allowfreeform")){
this.$element.val('');
this.$source.val('').trigger('change');
this.$target.val('').trigger('change');
} else {
this.$element.val(val);
this.$target.val(val);
this.$container.addClass('combobox-selected');
}
}
if (!this.mousedover && this.shown) {setTimeout(function () { that.hide(); }, 200);}
}
Edit: This fork has since been added to the main repository.
In case anyone is looking at this in 2018, I think this is a better solution than the workarounds in the other answers.
I added an option to bootstrap-combobox that lets you turn off the behavior that you're talking about. See my fork. Here's how you might use this option to get the desired behavior:
$('.combobox').combobox({clearIfNoMatch: false})
Here are the relevant bits of code that I changed.
Original blur function:
, blur: function (e) {
var that = this;
this.focused = false;
var val = this.$element.val();
if (!this.selected && val !== '' ) {
this.$element.val('');
this.$source.val('').trigger('change');
this.$target.val('').trigger('change');
}
if (!this.mousedover && this.shown) {setTimeout(function () { that.hide(); }, 200);}
}
My change:
, blur: function (e) {
var that = this;
this.focused = false;
var val = this.$element.val();
if (!this.selected && val !== '' ) {
if(that.clearIfNoMatch)
this.$element.val('');
this.$source.val('').trigger('change');
this.$target.val('').trigger('change');
}
if (!this.mousedover && this.shown) {setTimeout(function () { that.hide(); }, 200);}
}
Added this to the constructor at line 41:
...
this.clearIfNoMatch = this.options.clearIfNoMatch;
...
Added this to the defaults at line 463:
...
, clearIfNoMatch: true
...
A grand total of 3 lines. Much shorter than the workarounds ;-)

Store a clicked option link within a select using jquery

ok, so I have this code:
$(function(){
// TODO make this work
$('select#selList').change(function(){
if($(this).val()=="alpha"||$(this).val()=="date"|$(this).val()=="nil")
$selectedValue=0;
else
$selectedValue=$(':selected').val();
$options=$('#selList').children('option');
$arrVals=[];
$options.each(function({
if($(this).val()=="alpha"||$(this).val()=="date"|$(this).val()=="nil")
{
return true;
}
else
{
$arrVals.push({
valx:$(this).val(),
txtx:$(this).text(),
datex:$(this).attr('date')
});
}
});
var sort_by = function(field, reverse, primer)
{
var key = function (x) {return primer ? primer(x[field]) : x[field]};
return function (a,b) {
var A = key(a), B = key(b);
return ((A < B ? -1 :(A > B) ? +1 : 0)) * [-1,1][+!!reverse];
}
}
switch($(':selected').attr('id'))
{
case 'alpha':
$arrVals.sort(sort_by('txtx',true,false));
break;
case 'date':
$arrVals.sort(sort_by('datex',true,false));
break;
}
$(this).html("");
for(var i=0, m=$arrVals.length;i<m;i++)
{
$($options[i]).text($arrVals[i].txtx);
$(this).append($options[i]);
}
$(this).append('<option value="nil" id="nil">---------------------------</option><option value="alpha" id="alpha">Sort alphabeticaly</option><option value="date" id="date">Sort by date</option>')
$(this).val($selectedValue);
});
});
Now all I want is to store the selected option if it defers from the "----", "Sort alphabeticaly" and "Sort by date" option, and keep it selected now matter what my succesive clicks are and the order of the options in the list.
The HTML is as follows:
<select id="selList" multiple style="height:150px">
<option value="1" date="20120126">A</option>
<option value="2" date="20120124">D</option>
<option value="3" date="20120125">B</option>
<option value="4" date="20120129">C</option>
<option value="nil" id="nil">---------------------------</option>
<option value="alpha" id="alpha">Sort alphabeticaly</option>
<option value="date" id="date">Sort by date</option>
</select>
Thanks for your help :)
Give it a try:(you may prepend the function-body to your existing function)
$('#selList')
.change(function()
{
var col=$('option:selected',this)
.filter(function(){return !isNaN(this.value);});
if(col.length)
{
$(this).data('selected',col);
}
}
);
Onchange it collects all selected options that have a numeric value. If there are any, it stores this collection as data inside the select.

Categories