I want to check the total value in the calculator so that i can show an answer as a chemical formula for example after pressing O which has value of "9" and adding C with value of "8" i would get 17 and i want to make a function that would detect the value and say something in these lines: "You've created CO2"
I just want some directions or a pointer because i really want to learn and i'm still a newbie anyway here's the calculator:
$(document).ready(function(){
var inputs=[""];
var totalString;
var operator1 = ["+"];
var operator2 = ["."];
var nums=[0,1,2,3,4,5,6,7,8,9];
function getValue(input){
if(inputs.length===1 && operator1.includes(input)===false){
inputs.push(input);
}
else if(operator1.includes(inputs[inputs.length-1])===false){
inputs.push(input);
}
else if(nums.includes(Number(input))){
inputs.push(input);
}
update();
}
function update(){
totalString= inputs.join("");
$("#steps").html(totalString);
}
function getTotal(){
totalString= inputs.join("");
console.log(totalString + ": " + eval(totalString));
$("#steps").html(eval(totalString));
}
$("a").on("click",function(){
if(this.id==="deleteAll"){
inputs = [""];
update();
}
else if(this.id==="backOne"){
inputs.pop();
update();
}
else if(this.id==="total"){
getTotal();
}
else{
if(inputs[inputs.length-1].indexOf("+")===-1){
getValue(this.id);
}
else {
getValue(this.id);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-center">
</div>
<div id ="calcOutput">
<span id= "steps"></span>
<hr/>
</div>
<div class="text-center"
id="calculator">
<a class="btn btn-danger"
id="deleteAll">AC</a>
<a class="btn btn-danger"
id="backOne">CE</a>
<br/>
<a class="btn btn-primary"
value="7"
id="7">H</a>
<a class="btn btn-primary"
value="8"
id="8">O</a>
<a class="btn btn-primary"
value="9"
id="9">C</a>
<br/>
<a class="btn btn-primary"
value="4"
id="4">N</a>
<a class="btn btn-primary"
value="5"
id="5">F</a>
<a class="btn btn-primary"
value="6"
id="6">S</a>
<br/>
<a class="btn btn-primary"
value="1"
id="1">Fe</a>
<a class="btn btn-primary"
value="2"
id="2">Na</a>
<a class="btn btn-primary"
value="3"
id="3">Cl</a>
<br/>
<a class ="btn btn-primary bigButton" id="total">=</a>
<a class ="btn btn-primary bigButton" id="+">+</a>
</div>
Thank you for any help, and every other comments!
I am not sure I understand the approach.
Are you trying to map 17 to CO2 ? If that is the case then there could be number of ways to produce 17, like FE+O+O = (1+8+8)= 17, that may not be the result you are expecting. I would say to maintain an array(map) of compounds like co2,o2 etc.
And then append the text instead of adding number while keypress.
Eg: user press C + O, then check in the array with all compounds having CO.
Related
I'm trying to figure out how to display the value of my button in a paragraph. I feel like this is super simple and I'm just doing something dumb.
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<button type="button" class="btn btn-dark" id="0" onclick="Add2list" value="BarBell Bench Press" >BarBell Bench Press</button>
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>
function Add2list() {
var x= document.getElementById("0")
document.getElementById("Workouts2do").innerHTML = x;
}
Add2list is a function, so onclick="Add2list()" and you want the value of the button so var x = document.getElementById("0").value
function Add2list() {
var x = document.getElementById("0").value
document.getElementById("Workouts2do").innerHTML = x;
}
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<button type="button" class="btn btn-dark" id="0" onclick="Add2list()" value="BarBell Bench Press">BarBell Bench Press</button>
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>
You haven't added which attribute you want to get from the button. Also, you can't directly add the whole reference.
Just mention which attribute you want to take from the button
You haven't called the function when passed to onclick attribute
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<button type="button" class="btn btn-dark" id="0" onclick="Add2list()" value="BarBell Bench Press" >BarBell Bench Press</button>
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>
function Add2list() {
var x= document.getElementById("0").value
document.getElementById("Workouts2do").innerHTML = x;
}
OnClick needs a function always
You need to specify what you are going to get from the button
option 1:
var x = document.getElementById("0").value
document.getElementById("Workouts2do").innerHTML = x;
option 2:
var x = document.getElementById("0")
document.getElementById("Workouts2do").innerHTML = x.value;
if you want to have a list and not clear it every time you need to click on the button you could use +=
For new line since it's inner HTML you can use only.
function Add2list() {
var x = document.getElementById("0")
document.getElementById("Workouts2do").innerHTML += x.value + `<br>`;
}
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<button type="button" class="btn btn-dark" id="0" onclick="Add2list()" value="BarBell Bench Press">BarBell Bench
Press</button>
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>
You should probably change your button to "input" but leave it's type at "button". Also, var is no longer used, you should use "let" as so:
<div id="ChestWorkouts" class="text-center">
<h1>Chest workouts</h1>
<input type="button" class="btn btn-dark" id="0" value="BarBell Bench Press" />
</div>
<div>
<h5>LIST OF WORKOUTS TO DO</h5>
<p id="Workouts2do">
</p>
</div>
the js:
document.getElementById("0").addEventListener("click", Add2list);
function Add2list() {
// Selecting the input and get value
let inputVal = document.getElementById("0").value;
// output the value
document.getElementById("Workouts2do").innerHTML = inputVal;
}
I am creating a HTML form for data entry that contains a couple of textboxes and function buttons.
There is also an add button that copies (clones) from a DIV template (id: w) for each "row" and appends to the end of the main DIV (id: t). On each row, there is a "X" button to remove the row and two arrow buttons to visually move the "row" up and down in the DOM.
The form is dynamically created from a database and the elements already on the page when the page is loaded and using jQuery 3.4.1, for the selecting and most of the DOM manipulation using the functionality of each rows buttons.
The "rows" are added to the container DIV and the elements are renamed depending on the counter which is expected. The "X" button deletes the "row", and moves all pre-existing rows up and down in the container DIV.
But for some unknown reason any new rows that are created I have to press the "up" button twice. The "down" button for the bottom row, is redundant and not functional.
I think it might have to do with the previousSibling and nextSibling returning the wrong Object type and causing a problem and failing the first time.
Any thoughts on how to fix or improve this functionality?
var rr = $("[id^=l]").length;
$(".data-up").click(function() {
var e = $(this).first().parent().parent().get(0);
moveUp(e);
});
$(".data-down").click(function() {
var e = $(this).parent().parent().get(0);
moveDown(e);
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rw);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
function moveUp(e) {
if (e.previousSibling) {
if (e.previousSibling === e.parentNode.children[0]) {} else {
e.parentNode.insertBefore(e, e.previousSibling);
}
}
}
function moveDown(e) {
if (e === e.parentNode.children[e.parentNode.children.length - 1]) {} else {
e.parentNode.insertBefore(e.nextSibling, e);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>
With jQuery - use .closest() to find the current parent of the button. The find the .prev() or the .next() sibling. If the sibling exists use .insertBefore() or .insertAfter() to move the current parent before or after the sibling:
var rr = $("[id^=l]").length;
$(".data-up").click(function(e) {
var current = $(this).closest('.form-group'); // find the current parent
var target = current.prev(); // find the relevant sibling
if(target.length) { // if sibling exists
current.insertBefore(target); // insert the current item above it
}
});
$(".data-down").click(function() {
var current = $(this).closest('.form-group'); // find the current parent
var target = current.next(); // find the next sibling
if(target.length) { // if the next sibling exists
current.insertAfter(target); // insert the current item after it
}
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rr);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>
What's wrong in your code
The problem with the up button is e.previousSibling === e.parentNode.children[0] - the 1st element is always the first item in the collection, so this blocks you from moving an item above it. All you have to check is if there is a previousSibling for up, and nextSibling for down.
Fixed code + comments:
var rr = $("[id^=l]").length;
$(".data-up").click(function() {
var e = $(this).parent().parent().get(0); // first() is redundant - this is the only element in the collection
moveUp(e);
});
$(".data-down").click(function() {
var e = $(this).parent().parent().get(0);
moveDown(e);
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rr);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
function moveUp(e) {
if (e.previousSibling) { // just check if there's a previous sibling
e.parentNode.insertBefore(e, e.previousSibling);
}
}
function moveDown(e) {
if (e.nextSibling) { // just check if there's a next sibling
e.parentNode.insertBefore(e.nextSibling, e);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>
New To JQuery, i have the following code which i think is a bit over kill as all i'm trying to do i match a returned value to a selection of buttons and add/remove a class.
HTML for days of the week buttons
<div class="form-horizontal" id="selectWeekdaysSection">
<div class="form-group">
<div class="col-md-offset-2 col-lg-4">
<button id="mon" name="weekdaysbutton" class="btn btn-default" type="button" value="Mon">Mon</button>
<button id="tue" name="weekdaysbutton" class="btn btn-default" type="button" value="Tue">Tue</button>
<button id="wed" name="weekdaysbutton" class="btn btn-default" type="button" value="Wed">Wed</button>
<button id="thur" name="weekdaysbutton" class="btn btn-default" type="button" value="Thur">Thur</button>
<button id="fri" name="weekdaysbutton" class="btn btn-default" type="button" value="Fri">Fri</button>
<button id="sat" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sat">Sat</button>
<button id="sun" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sun">Sun</button>
</div>
</div>
</div>
Gives this on the site
DataTable data
When i do call and get data back from my DataTable it pre-selects the days from the JSON. I have all this working but as i said seems over kill to have to keep repeating the IF just for a different button especially when i have to do this for days '01 - 31'
Jquery
var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',');
splitSelectedDays.forEach(day => {
let val = day.trim();
if(val == 'Mon') {
$('#mon').removeClass('btn-default');
$('#mon').addClass('btn-primary');
}
if (val == 'Tue') {
$('#tue').removeClass('btn-default');
$('#tue').addClass('btn-primary');
}
if (val == 'Wed') {
$('#wed').removeClass('btn-default');
$('#wed').addClass('btn-primary');
}
if (val == 'Thur') {
$('#thur').removeClass('btn-default');
$('#thur').addClass('btn-primary');
}
if (val == 'Fri') {
$('#fri').removeClass('btn-default');
$('#fri').addClass('btn-primary');
}
if (val == 'Sat') {
$('#sat').removeClass('btn-default');
$('#sat').addClass('btn-primary');
}
if (val == 'Sun') {
$('#sun').removeClass('btn-default');
$('#sun').addClass('btn-primary');
}
})
Console.Log of returned data
The technique you want to follow is called Don't Repeat Yourself, or DRY for short.
In this case the day is always the same as the id of the element you want to target, so you can manually build the selector string once from that. You can also use toggleClass() instead of alternate addClass() and removeClass() calls. Try this:
splitSelectedDays.forEach(day => {
let dayName = day.trim().toLowerCase();
$('#' + dayName).toggleClass('btn-default btn-primary');
})
Somehow to onchange fuction does not trigger properly after I Switch the Radio button. Currently I get no log message with "circle uncheck" or "arrow uncheck". The HTML Looks like this:
var drawingArrow = document.getElementById('drawing-arrow-shape'),
drawingCircle = document.getElementById('drawing-circle-shape');
drawingCircle.onchange = function() {
console.log("on change circle btn");
if ($("#drawing-circle-shape").is(":checked")) {
console.log("circle checked");
} else {
console.log("circle uncheck");
}
};
drawingArrow.onchange = function() {
console.log("on change arrow btn");
if ($("#drawing-arrow-shape").is(":checked")) {
console.log("arrow checked")
} else {
console.log("arrow uncheck");
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="btn btn-default btn-lg">
<input type="radio" name="drawing-shape" id="drawing-arrow-shape">
<i class="glyphicon glyphicon-arrow-right"></i>
</label>
<label class="btn btn-default btn-lg">
<input type="radio" name="drawing-shape" id="drawing-circle-shape">
<i class="glyphicon glyphicon-record"></i>
</label>
The issue is because the , after the second variable definition should be a ;. This is confusing the JS interpreter as it thinks the next statement will be a variable definition, when in fact it's a variable setter.
You should however note that you can improve your logic by using addEventListener() on the elements directly. You can then just use the this keyword to reference the element without having to use jQuery to select an element you already have a reference to. Try this:
document.getElementById('drawing-arrow-shape').addEventListener('change', function() {
if (this.checked)
console.log('arrow checked');
});
document.getElementById('drawing-circle-shape').addEventListener('change', function() {
if (this.checked)
console.log('circle checked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="btn btn-default btn-lg">
<input type="radio" name="drawing-shape" id="drawing-arrow-shape">
<i class="glyphicon glyphicon-arrow-right"></i>
</label>
<label class="btn btn-default btn-lg">
<input type="radio" name="drawing-shape" id="drawing-circle-shape">
<i class="glyphicon glyphicon-record"></i>
</label>
you need to change these 2 statements:
var drawingArrow = document.getElementById('drawing-arrow-shape');
drawingCircle = document.getElementById('drawing-circle-shape');
There was a ',' on the end of both which was causing the issue. Replacing that with ';' fixed it.
I made a small change in your Js and now it is working please check below changes I made
var drawingArrow = document.getElementById('drawing-arrow-shape');
var drawingCircle = document.getElementById('drawing-circle-shape');
Just removed comma and made separate variables.
var drawingArrow = document.getElementById('drawing-arrow-shape');
var drawingCircle = document.getElementById('drawing-circle-shape');
drawingCircle.onchange = function() {
console.log("on change circle btn");
if($("#drawing-circle-shape").is(":checked")) {
console.log("circle checked");
} else {
console.log("circle uncheck");
}
};
drawingArrow.onchange = function() {
console.log("on change arrow btn");
if($("#drawing-arrow-shape").is(":checked")) {
console.log("arrow checked")
} else {
console.log("arrow uncheck");
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="btn btn-default btn-lg">
<input type="radio" name="drawing-shape" id="drawing-arrow-shape">
<i class="glyphicon glyphicon-arrow-right"></i>
</label>
<label class="btn btn-default btn-lg">
<input type="radio" name="drawing-shape" id="drawing-circle-shape">
<i class="glyphicon glyphicon-record"></i>
</label>
I have a form, I want to append a entire div every time a button is clicked. The code works but after few seconds the appended div automatically disappears. don't get any errors.
I am using jQuery 2.1.3. Here is my code in JS Fiddle:
https://jsfiddle.net/sathyabaman/jgdLtu4d/
My code:
<form method="POST" id="form_property" enctype="multipart/form-data">
<div class="row">
<div class="span4" id="image">
<h3><strong>4.</strong> <span>Add Images to your Property (Maximum : 6 Images)</span></h3>
<div id="clone_image" class="fileupload fileupload-new ">
<label class="control-label">Image file</label>
<div class="input-append">
<div class="uneditable-input"> <i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div> <span class="btn btn-file">
<span class="fileupload-new">Select file</span>
<span class="fileupload-exists">Change</span>
<input type="file" name="files1" accept="image/*" />
</span>
</div>
</div>
</div>
<!-- /.span4 -->
</div>
<!-- /.row -->
<br/> <a id="another_image" class="btn btn-primary btn-small list-your-property" href="">Add Another Image</a>
<br/>
<br/>
<input type="submit" name="submit" value=" Save images " class="btn btn-primary btn-large" style="float: left; width: 370px; height: 50px; margin-top: 10px">
</form>
jquery
$(document).ready(function(){
var count = 2;
$('#another_image').click (function(){
var clonedEl = $('#clone_image').first().clone()
clonedEl.find(':file').attr('name','files'+count)
if(count < 7){
if(count == 6){ $('#another_image').hide();}
$(clonedEl).appendTo("#image");
count++;
}
});
});
Thank you..
You need to prevent the default action of the anchor click, which is to navigate to the target page.
Since you have specified an empty href it reloads the same page that is why you can see the new element and then it appears to be disappearing.
$(document).ready(function () {
var count = 2;
$('#another_image').click(function (e) {
//e.preventDefault()
var clonedEl = $('#clone_image').first().clone()
clonedEl.find(':file').attr('name', 'files' + count)
if (count < 7) {
if (count == 6) {
$('#another_image').hide();
}
$(clonedEl).appendTo("#image");
count++;
}
});
});
Demo: Fiddle