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>
Related
I have a form with 5 questions, in which they are displayed one at a time to the user, as in a quiz, that is, the first question appears on the screen, the user answers and goes to the second, and so on.
However, I have a problem with questions 3 and 4, when I don't type anything and press ENTER, question 2 is also appearing on the screen, like the image below:
[![error in questions 3 and 4][1]][1]
[1]: https://i.stack.imgur.com/63pQC.png
I can't show two questions at the same time, just one at a time, and I don't know where I'm going wrong.
Here's the code inside the form tag:
<form class="questions_box formulario" action="enviar-landing-page-v3.php" method="post">
<div id="question-1">
<h3>The question is: ... ?</h3>
<input type="radio" name="objetivo" id="question-1-answer-a" value=1 required oninput="checkObjective()"> Answer 1.<br>
<input type="radio" name="objetivo" id="question-1-answer-b" value=2 oninput="checkObjective()"> Answer 2.<br>
<input type="radio" name="objetivo" id="question-1-answer-c" value=3 oninput="checkObjective()"> Answer 3.<br>
<div class="text-end mt-3">
<input type="submit" id="submit1" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<script type="text/javascript">
function checkObjective() {
if (document.getElementsByName('objetivo').value == '') {
document.getElementById('submit1').style.display = 'none';
} else {
document.getElementById('submit1').style.display = 'block';
}
}
</script>
</div>
<div id="question-2">
<h3>Quantos anos tem seu filho(a)?</h3>
<div class="input-formulario">
<i class="far fa-calendar-alt"></i>
<input required type="text" name="idade_aluno_lp" id="idade_aluno_lp" placeholder="Digite a idade do aluno" oninput="checkAge()" maxlength="2" />
</div>
<div class="text-center mt-3">
<input type="submit" id="submit2" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous2" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkAge() {
var countAge = document.getElementById('idade_aluno_lp');
countAge.value = countAge.value.replace(/\D/, ''); // Remove caracteres que não sejam números
if (countAge.value.length == 0) { // 0 caracteres digitados
document.getElementById('submit2').style.display = 'none';
} else {
document.getElementById('submit2').style.display = 'block';
}
}
</script>
</div>
<div id="question-3">
<h3>Qual seu nome?</h3>
<div class="input-formulario">
<i class="far fa-user"></i>
<input required type="text" name="nome_lp" id="nome_lp" placeholder="Digite seu nome" oninput="checkName()">
<span id="error-name"></span>
</div>
<div class="text-center mt-3">
<input type="submit" id="submit3" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-center mt-3">
<input type="submit" id="previous3" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkName() {
var countName = document.getElementById('nome_lp');
var errorName = document.getElementById('error-name')
countName.value = countName.value.replace(/[0-9]/g, ''); // Remove numbers
if (countName.value.length < 3) { // 0 chars entered
errorName.innerHTML = "O nome precisa ter ao menos 3 caracteres."
document.getElementById('submit3').style.display = 'none';
} else {
errorName.innerHTML = "";
document.getElementById('submit3').style.display = 'block';
}
}
</script>
</div>
<div id="question-4">
<h3>Qual seu email?</h3>
<div class="input-formulario">
<i class="fas fa-at"></i>
<input required type="email" name="email_lp" id="email_lp" placeholder="Digite seu email" oninput="checkEmail()">
<span id="error-email"></span>
</div>
<div class="text-center mt-3">
<input type="submit" id="submit4" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous4" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
<script type="text/javascript">
function checkEmail() {
var email = document.getElementById('email_lp');
var errorEmail = document.getElementById('error-email');
if (!email.checkValidity()) {
errorEmail.innerHTML = "O email deverá seguir o padrão: meuemail#provedor.com";
document.getElementById('submit4').style.display = 'none';
} else {
errorEmail.innerHTML = "";
document.getElementById('submit4').style.display = 'block';
}
}
</script>
</div>
<div id="question-5">
<h3>Qual seu whatsapp?</h3>
<div class="input-formulario">
<i class="fab fa-whatsapp"></i>
<input required type="text" name="celular_lp" id="celular_lp" placeholder="Digite seu DDD + celular" maxlength="14" onkeypress="return mascaraCelular(event)" oninput="checkMobile()">
<span id="error-mobile"></span>
</div>
<div class="text-end mt-3">
<input type="submit" id="submit5" class="btn btn-primary btn-lg" value="Enviar Resposta" style="display: none;" />
</div>
<div class="text-end mt-3">
<input type="submit" id="previous5" class="btn btn-primary btn-lg" value="Pergunta Anterior" style="display: block;" />
</div>
</div>
<script type="text/javascript">
function checkMobile() {
var countMobile = document.getElementById('celular_lp');
var errorMobile = document.getElementById('error-mobile');
if (countMobile.value.length < 13) {
errorMobile.innerHTML = "Além do DDD, o número do celular precisa ter ao menos 8 dígitos";
document.getElementById('submit5').style.display = 'none';
} else {
errorMobile.innerHTML = "";
document.getElementById('submit5').style.display = 'block';
}
}
</script>
</form>
And the javascript responsible for show/hide the questions:
// Variables
var submit1 = document.getElementById('submit1');
var submit2 = document.getElementById('submit2');
var submit3 = document.getElementById('submit3');
var submit4 = document.getElementById('submit4');
var previous2 = document.getElementById('previous2');
var previous3 = document.getElementById('previous3');
var previous4 = document.getElementById('previous4');
var previous5 = document.getElementById('previous5');
// Next question button
submit1.addEventListener('click', function() {
nextQuestion(2);
growProgressBar('40%');
})
submit2.addEventListener('click', function() {
nextQuestion(3);
growProgressBar('60%');
})
submit3.addEventListener('click', function() {
nextQuestion(4);
growProgressBar('80%');
})
submit4.addEventListener('click', function() {
nextQuestion(5);
growProgressBar('100%');
})
// grow Progress Bar
function growProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows next question, hides current
function nextQuestion(question_number) {
var current_question_number = question_number - 1; //question_number is the next question
var question_number = question_number.toString();
var current_question_number = current_question_number.toString();
document.getElementById('question-' + question_number).style.display = 'block';
document.getElementById('question-' + current_question_number).style.display = 'none';
}
// Previous question button
previous2.addEventListener('click', function() {
previousQuestion(1);
shrinkProgressBar('20%');
})
previous3.addEventListener('click', function() {
previousQuestion(2);
shrinkProgressBar('40%');
})
previous4.addEventListener('click', function() {
previousQuestion(3);
shrinkProgressBar('60%');
})
previous5.addEventListener('click', function() {
previousQuestion(4);
shrinkProgressBar('80%');
})
// Shrink Progress Bar
function shrinkProgressBar(percentage_width) {
var bar = document.getElementById('progress_bar');
bar.style.width = percentage_width;
}
// Shows previous question, hides current
function previousQuestion(question_number) {
var current_question_number = question_number + 1;
var question_number = question_number.toString();
var current_question_number = current_question_number.toString();
var el = document.getElementById('question-' + question_number);
console.log(question_number);
var el2 = document.getElementById('question-' + current_question_number);
el.style.display = 'block';
el2.style.display = 'none';
}
About Carsten Massmann answer:
The problem with the code was just to change the buttons type="submit" to type="button", and leave only the last button as type="submit", however, I really liked your code, I learned a lot, for example, I had never read about closest method. Could you explain to me how these two lines of code work (what they are for I understand):
current = (Q.length + current + inc) % Q.length; // cycle through questions...
Above I don't understand why you use the question length.
And on the next line, I don't understand why I use trim():
(el.value.trim() ? "block" : "none")
I also understand that you cycle between questions, but I need to demarcate the first and last question in the loop, and put something like if Q=0, don't show the "Previous question" button, and if Q=4, that the final button would execute method="POST" and action="next-page". I believe that the "submit" is not being executed because of the loop, but I don't understand why the loop takes precedence over the submit.
The following snippet is still missing your actual validation functions for individual fields but I hope it illustrates the point of how you can avoid unnecessary repetitions in your code and markup. I am using classes to address the various input elements and "delegated event attachment" to combine the click handling for different buttons. For simplicity I allow cycling through the questions. Feel free to change and adapt ...
function changeQ(inc){
current= (Q.length+current+inc)%Q.length; // cycle through questions ...
Q.forEach((q,i)=>q.style.display=(i==current?"":"none"))
}
function showHideOK(el){
let ok=!!el.value.trim();
el.closest(".input-formulario").querySelector("input.ok").style.display=
(ok?"block":"none");
ans[el.name]=ok;
}
document.querySelectorAll("div.input-formulario").forEach((div,i)=>{div.innerHTML+=`<div class="text-end mt-3"><input type="submit" class="btn btn-primary btn-lg back" value="Pergunta Anterior"/></div><div class="text-center mt-3"><input type="submit" class="btn btn-primary btn-lg ok" value="Próxima Pergunta"/></div>`;
div.addEventListener("input",ev=>{ let el=ev.target;
if (el.tagName!=="INPUT") return // only act on input elements ...
showHideOK(el)
btn.style.display=Object.values(ans).filter(a=>a).length==Q.length?"":"none";
});
div.onclick=ev=>{if (ev.target.type=="submit") {
ev.preventDefault();
changeQ( ev.target.classList.contains("back")?-1:1 );
}}
})
const btn = document.querySelector("button"),
Q=document.querySelectorAll(".question"),
ans={};
let current=0;
changeQ(0);
btn.style.display="none";
input.ok {display:none}
<form class="questions_box formulario" action="enviar-landing-page-v3.php" method="post">
<div class="question">
<div class="input-formulario">
<h3>The question is: ... ?</h3>
<label><input type="radio" name="objetivo" value=1 required> Answer 1.</label><br>
<label><input type="radio" name="objetivo" value=2> Answer 2.</label><br>
<label><input type="radio" name="objetivo" value=3> Answer 3.</label><br>
</div>
</div>
<div class="question">
<h3>Quantos anos tem seu filho(a)?</h3>
<div class="input-formulario">
<input required type="number" name="idade_aluno_lp" placeholder="Digite a idade do aluno" maxlength="2" />
</div>
</div>
<div class="question">
<h3>Qual seu nome?</h3>
<div class="input-formulario">
<input required type="text" name="nome_lp" placeholder="Digite seu nome"> <span></span>
</div>
</div>
<div class="question">
<h3>Qual seu email?</h3>
<div class="input-formulario">
<input required type="email" name="email_lp" id="email_lp" placeholder="Digite seu email"> <span></span>
</div>
</div>
<div class="question">
<h3>Qual seu whatsapp?</h3>
<div class="input-formulario">
<input required type="text" name="celular_lp" id="celular_lp" placeholder="Digite seu DDD + celular"
maxlength="14"> <span></span>
</div>
</div>
<br><button>Enviar todas as respostas</button>
</form>
Further explanations:
Why am I using Q.length?
The expression current = (Q.length + current + inc)/Q.length uses Q.length (=total number of questions) to keep current always within the range of existing question indexes. The term Q length+... is necessary to keep values positive for the situation where current=0 and inc=-1 and % Q.length limits the results from 0 to Q.length-1.
Why do I use .trim()?
This is just a simple way of avoiding that an answer containing only blanks would be accepted as a valid answer.
Why is there no "submit"?
I actively disabled the submit action by calling ev.preventDefault() within my event-handling function.
How to submit the answers, and when?
There are many different ways of doing it. My suggestion would be to keep cycling through the questions until all questions are answered in a valid way. At that point an extra button appears that submits all answers at once. I just added that button (btn) to the script. It is hidden at first through btn.style.display="none" but made visible again on the condition that all questions have received an answer:
btn.style.display=Object.values(ans).filter(a=>a).length==Q.length?"":"none";
The (global) object ans is constantly updated in the function showHideOK():
let ok=!!el.value.trim();
...
ans[el.name]=ok;
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>
I'm wondering how to copy one specific list and add it onto multiple UL's. I'm trying to make it so that when the user clicks a button, it will add the task to both List 1 and List 2.
window.onload=function() {
el = document.createElement('li');
el.setAttribute("list2UL", "List2UL");
}
$(() => {
$('input').on('keypress', function(e) {
if (e.keyCode == 13) {
const newList1 = $(this).val();
if (newList1) {
var li = $("<li><input type='checkbox' id='newlist1item' class='right-margin' <label>" + newList1 + "</label> <button type="button" class="deletelist"> </button> <button type="button" class="addtolist2"></button></li>");
$('#tasksUL').append(li);
$('#tasksUL').append(el);
$(this).val("");
}
}
});
$(document).on("click", ".deletelist", function() {
$(this).parent().remove();
});
});
<label for="list1menu">
<input type="text" name="newlist1" value="" spellcheck="false" placeholder="New List" id="newlist1">
<ul id="list1UL">
<li><input type="checkbox" id="newlist1item" class="right-margin"><label>List1</label> <button type="button" class="deletelist"> </button> <button type="button" class="addtolist2"></button></li>
</ul>
</label>
<label for="list2 menu">
<ul id="list2UL" class='list2UL'>
<li><input type="checkbox" id="newlist2item" class="right-margin"><label>List2</label> <button type="button" class="deletelist"></button></li>
</ul>
</label>
Here is solution for your question : https://jsfiddle.net/t09e8326/2/
You made many mistake in your code, such as you were not appending to the second list. Trying to append el element which is out of global scope.
HTML:
<label for="list1menu">
<input type="text" name="newlist1" value="" spellcheck="false" placeholder="New List" id="newlist1">
<ul id="list1UL">
<li><input type="checkbox" id="newlist1item" class="right-margin"><label>List1</label> <button type="button" class="deletelist"> Delete</button> <button type="button" class="addtolist2">Add to List2</button></li>
</ul>
</label>
<label for="list2 menu">
<ul id="list2UL" class='list2UL'>
<li><input type="checkbox" id="newlist2item" class="right-margin"><label>List2</label> <button type="button" class="deletelist">Delete</button></li>
</ul>
</label>
Script:
$(() => {
$('#newlist1').on('keypress', function(e) {
if (e.keyCode == 13) {
const newList1 = $(this).val();
if (newList1) {
var li = "<li><input type='checkbox' id='newlist1item' class='right-margin' <label>" + newList1 + "</label> <button type='button' class='deletelist'> Delete</button> <button type='button' class='addtolist2'>Add to List 2</button></li>";
$('#list1UL').append(li);
$('#list2UL').append(li);
$(this).val("");
}
}
});
$(document).on("click", ".deletelist", function() {
$(this).parent().remove();
});
});
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.
I have one of the components label with the sample class tclick
<label class="btn btn-default tclick" data-tloc="value1" data-tkey="key1" >
<label class="btn btn-default tclick" data-tloc="value2" data-tkey="key2" >
<label class="btn btn-default tclick" data-tloc="value3" data-tkey="key3" >
Whenever click on any one component of label, class "checked" will be automatically added to label :
ex:
<label class="btn btn-default tclick checked" data-tloc="value1" data-tkey="key1" >
<label class="btn btn-default tclick checked" data-tloc="value2" data-tkey="key2" >
but i want get exactly data-tloc, data-tkey when label is click ?
i like code jquery and I need one solution ?
$('label.tclick').click(function() {
$(this).addClass('checked');
var tloc = $(this).data('tloc'),
tkey = $(this).data('tkey');
console.log(tloc, tkey);
});
.checked { color: red; }
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<label class="tclick" data-tloc="value1" data-tkey="key1">Label1</label>
<label class="tclick" data-tloc="value2" data-tkey="key2">Label2</label>
<label class="tclick" data-tloc="value3" data-tkey="key3">Label3</label>
Solution:
$('label.tclick').click(function(){
var tloc = $(this).data('tloc'),
tkey = $(this).data('tkey');
$(this).addClass('checked');
console.log('Tloc:' + tloc + ', Tkey: ' + tkey);
});
After 'checked' is automatically added and you just want the data attributes on click then try on change because if click executes before the checked class is added is(':checked') may not work:
$( "label.tclick" ).on('change', function() {
if($(this).is(':checked')){
console.log($(this).data('tloc'));
console.log($(this).data('tkey'));
}
});