Trying to turn onclick to enter key - html

I'm a beginner and I'm trying to help some special education students with a very basic budget calculator. I've seen similar questions to mine posted, but when I try those methods something always breaks and I'm having some trouble figuring it out.
Basically I need the onclick portion of the button that calls the function into action to actually respond to the enter key and not a click :-( Thank you very much in advance for any help that might be provided!!
<script>
function addTwoNumbers () {
var number1 = document.getElementById('box1').value;
var number2 = Number(document.getElementById('box2').value);
var sum = Number(number1) + number2;
document.getElementById('resultBox').value = sum;
if(sum<0) {
document.getElementById('resultBox').style.color = "red";
}
else{
document.getElementById('resultBox').style.color = "green";
}
document.getElementById('resultBox').style.visibility = 'visible';
document.getElementById('resultBox').value = sum
}
</script>
<script>
function subtractTwoNumbers () {
var number1 = document.getElementById('box1').value;
var number2 = Number(document.getElementById('box2').value);
var difference = Number(number1) - number2;
document.getElementById('resultBox').value = difference;
if(difference<0) {
document.getElementById('resultBox').style.color = "red";
}
else{
document.getElementById('resultBox').style.color = "green";
}
document.getElementById('resultBox').style.visibility = 'visible';
document.getElementById('resultBox').value = sum
}
</script>
<script>
function clearall() {
document.getElementById('box1').value = "";
document.getElementById('box2').value = "";
document.getElementById('resultBox').value = "";
}
</script>
<div id='calc' align="center"></div>
<h1>Calculator</h1>
<p>Enter budget <input type="text" id="box1"></p>
<p>Enter price   <input type="text" id="box2"></p>
<p>Press the equation key to see your results</p>
<div class="btn-group" style="width:100%">
<button style="width:33.3%" onclick="addTwoNumbers()">+</button>
<button style="width:33.3%" onclick="subtractTwoNumbers()">-</button>
<p>
<button style="width:67.5%" onclick="clearall()">clear</button>
</div>
<h3>Do you have enough?</h3>
<input type="text" id="resultBox"> <br/>

Instead of using the onclick attribute in the HTML, a more modern approach would be to create an event listener in your javascript.
I would give the buttons an ID. Then do something like this:
document.getElementById("clearBtn").addEventListener("click", clearAll);
There are all kinds of events you can listen for and I would guess you could find one that provides the behavior you are after.

Related

How to display var from javascript to html?

I keep getting an error for the last line in generatePassword()," document.getElementById(output).innerHTML = outHash;" Any ideas on how to display this variable?
<html>
<body>
<p>Enter your text here </p>
<input type="text" value="Enter password here" id="userInput">
<button onclick="generatePassword()">Generate</button>
<p>Hash output <span id="output"></span></p>
<script>
function generatePassword() {
var Input = document.getElementById("userInput");
var outHash = digestMessage(Input);
var displayHash = [];
document.getElementById(output).innerHTML = outHash;
}
async function digestMessage(message) {
var encoder = new TextEncoder();
var data = encoder.encode(message);
var hash = await crypto.subtle.digest('SHA-256', data);
return hash;
}
</script>
</body>
Change output in document.getElementById(output) to a string ("output") and it should work. Your javascript is trying to call a variable that doesn't exist.

jQuery sentence case function keeps replacing my text

I'm trying to make a input sentence case tool but when I type anything different it keeps returning the value="" text.
I'd like to make an exception for pasted or replaced text. So when I type a new value in input it should return that string into sentence case.
Here is the code snippet I've made:
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var title = $("#essay-title").val();
var sentenceCaseTitle = capitalizeFirstLetter(title.toLowerCase());
//alert( lowerCaseTitle );
function sentencecase() {
$("#essay-title").trigger("change paste");
$("#essay-title").val(sentenceCaseTitle);
}
https://jsfiddle.net/c105vedo/
var title = $("#essay-title").val(); is executed immediately on page visit, so it's always empty and not updated. Move that part inside sentencecase:
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function sentencecase() {
var title = $("#essay-title").val();
var sentenceCaseTitle = capitalizeFirstLetter(title.toLowerCase());
$("#essay-title").trigger("change paste");
$("#essay-title").val(sentenceCaseTitle);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="essay-title" value="TEST TITLE">
<button type="button" onclick="sentencecase()">OK
</button>
You have to move the following code into your sentencecase function,
var title = $("#essay-title").val();
var sentenceCaseTitle = capitalizeFirstLetter(title.toLowerCase());
Problem is that if the above code is outside of the function it will only be executed once, so that is why you keep getting the same value.
Demo
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
//alert( lowerCaseTitle );
function sentencecase() {
var title = $("#essay-title").val();
var sentenceCaseTitle = capitalizeFirstLetter(title.toLowerCase());
$("#essay-title").trigger("change paste");
$("#essay-title").val(sentenceCaseTitle);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="essay-title" value="TEST TITLE">
<button type="button" onclick="sentencecase()">OK
</button>

Apps script return values from server function to html form

I need help of professionals at Apps script. I have the project implemented by web-app.
I wrote script on server-part
var url = "https://docs.google.com/spreadsheets/d/1s8l-8N8dI-GGJi_mmYs2f_88VBcnzWfv3YHgk1HvIh0/edit?usp=sharing";
var sprSRCH = SpreadsheetApp.openByUrl(url);
let sheetSRCHSSCC = sprSRCH.getSheetByName("PUTAWAY_TO");
function GetQ(){
var QPLAN = sheetSRCHSSCC.getRange("M2:M").getValues().filter(String).length;
var myArray = sheetSRCHSSCC.getRange("O2:O" + (QPLAN + 1)).getValues();
var QFACT = 0;
for (i = 0; i < myArray.length; i++) {
if (myArray[i] != "") {
QFACT += 1
}
}
}
I need to return values from this function to inputs:
QFACT to FACT
QPLAN to PLAN
<div class="input-field col s3">
<input disabled value="" id="PLAN" type="text" >
<label for="disabled">PLAN</label>
</div>
<div class="input-field col s3">
<input disabled value="" id="FACT" type="text" >
<label for="disabled">FACT</label>
</div>
I will be grateful for the help. I'm new at this))
If you are using Apps Script deploying Web App, I can see 2 possibilities :
1/ Get data at the loading of the page (and only at the loading) :
In code.gs :
function doGet() {
var tmp = HtmlService.createTemplateFromFile('page');
tmp.QFACT = "hello";
tmp.PLAN = "World!";
return tmp.evaluate();
}
In page.html :
<html>
<body>
<h5><?= QFACT ?></h5>
<h5><?= QPLAN ?></h5>
</body>
</html>
2/ If you need to refresh the data by click button, or something else, you will need to operate diffently :
Add a page-js.html to your project, and bind it at the end of your page.html
<html>
<body>
<h5 id="QFACT"></h5>
<h5 id="QPLAN"></h5>
</body>
<?!= include("page-js"); ?>
</html>
then in your page-js.html :
<script>
function refresh() {
google.script.run.withSuccessHandler(callback).refresh();
}
function callback(e) {
document.getElementById('QPLAN').innerHTML = e.QPLAN;
document.getElementById('QFACT').innerHTML = e.QFACT;
}
</script>
and finally add the refresh() function in your code.gs :
function refresh() {
var obj = {};
obj.QPLAN = "QPLAN";
obj.QFACT = "QFACT";
return obj;
}

Calculate a total from autocomplete suggestion.data

I'm trying to write a small Jquery program with an autocomplete searchform. I would like the user to be able to add items from the autocomplete form to a sort of shopping list. I have difficulties finding a way to calculate and update the total price of all added products, I tried to store the prices, which are in suggestion.data and tot add it recusively to a total as in
total = total + suggestion.data, but this seems not to be the way. Could someone help me to produce and display this total? My jQuery code is as follows:
var Price = {};
var Name = {};
var Totaal = {};
$(function () {
var currencies = [
{value:'TEXT-STRING',data:'5.50)'},
{value:'TEXT-STRING2',data:'3.10)'},
];
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
Price.fff = suggestion.data;
Name.fff = suggestion.value;
},
});
});
function addListItem() {
var write2 = Price.fff;
var write = $('#autocomplete').val();
var list = $('#itemList');
var item = $('<li><span class="list">' + write + '</span><button
class="delete">X</button></li>');
var autocomplete = $("#autocomplete");
if (write.length === 0 || write.length > 88) {
return false;
}
if (write == Name.fff) {
list.append(item);
list2.append(item2);
$(autocomplete).val('');
}
$(autocomplete).val('');
}
function deleteItem() {
$(this).parent().remove();
}
$(function () {
var add = $('#addItem');
var autocomplete = $('#autocomplete');
var list = $('#itemList');
add.on('click', addListItem);
list.on('click', '.delete', deleteItem);
autocomplete.on('keypress', function (e) {
if (e.which == 13) {
addListItem();
}
}
And my HTML looks like:
<body>
<div id="box-1"> </div>
<div id="box-2"> </div>
<div id="page">
<h1>Shop</h1>
</div>
<div id="main">
<div id="top">
<div id="form">
<div id="searchfield">
<input type="text" id="autocomplete" name="currency" class="biginput" placeholder="ADD ITEMS BELOW">
<input type="submit" id="addItem" value="+">
</div>
<div class="line"> </div>
</div>
<div id="bottom">
<div class="items">
<ul id="itemList">
</ul>
</div>
</div>
Keep added item in array with prices, so you can recalculate total at any time. Don't forget to remove it from array when removing from the list.
Don't keep data in DOM, use DOM only to display info that is in your model.

getelementbyid issue with radio button

I'm trying to make an alert with the value of the selected radio button, but I allways get the first of them, regardless the one I choose...(Acompanhado);
html:
<form/>
<input type="radio" class="simple_form" name="grupo_1" value="Acompanhado" id="saida"/>
<span class="texto">Acompanhado</span>
<input type="radio" class="simple_form" name="grupo_1" value="Individual" id="saida"/>
<span class="texto">Individual</span>
</form>
js:
function save() {
var saida_js = document.getElementById('saida').value;
alert("Tipo de saida: " + saida_js);
}
Any idea ?
#Quentin: I have alot of alerts, cause Im trying to get all data from a form. I used your code, and I get no alert at all.
function save() {
var morada_js = document.getElementById('morada').value;
var data_js = document.getElementById('data').value;
var hora_js = document.getElementById('hora').value;
var radio_saida = document.getElementsByName('name_saida');
var notas_js = document.getElementById('notas').value;
var condicoes_atm_js = document.getElementById('condicoes_atm').value;
alert("Morada: " + morada_js);
alert("Data: " + data_js);
alert("Hora: " + hora_js);
function get_checked_radio(radio_saida) {
for (var i = 0; i < radio_saida.length; i++) {
var current = radio_saida[i];
if (current.checked) {
return current;
}
}
}
alert(get_checked_radio(radio_saida).value);
alert("Notas: " + notas_js);
}
An id must be unique in a document.
To find the value of a selected radio button in a group, get the group by its name…
var radios = document.getElementsByName('radio_name'); // or
var radios = document.forms.formId.elements.radio_name;
Then loop over them until you find the one with the true checked property.
function get_checked_radio(radios) {
for (var i = 0; i < radios.length; i++) {
var current = radios[i];
if (current.checked) {
return current;
}
}
}
alert(get_checked_radio(radios).value);
Makes sense because you've got two input tags with the same id saida