Simplify JavaScript code. document.getElementById - javascript

I have this code. The goal is to write the number when needed in a specific field. The problem is that the code is large. Can I simplify the code more?
HTML code
<div class="btn-group mr-2" role="group" aria-label="First group">
<button type="button" onclick="e1()" class=" btn">01</button>
<button type="button" onclick="e30()" class="btn">30</button>
</div>
JavaScript code
function e1() {
document.getElementById("epis_n").value = "1";
document.getElementById("order").value = "1";
}
function e30() {
document.getElementById("epis_n").value = "30";
document.getElementById("order").value = "30";
}

You could make a function that takes an argument instead.
HTML:
<button type="button" onclick="e(1)" class="btn">01</button>
...
<button type="button" onclick="e(30)" class="btn">30</button>
JavaScript:
function e(n) {
document.getElementById("epis_n").value = n.toString();
document.getElementById("order").value = n.toString();
}

Related

Change color button when click with Razor Page

This is the button that needs to change color when click. This is from a Razor page. I have tried the javascript code but it gives an error when I put in & I tried css code too(focus & active), didn't work. I'm new to this code. Please help. I just want something like this
<div class="row">
<div class="column" style="width:30%">
<div class="btn-group">
<button type="button" class="btn btn-primary" style="outline-color:red" #onclick="() => UpdateTheChart(11)">#Language.T35</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(12)">#Language.T36</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(13)">#Language.T37</button>
</div>
</div>
<div class="column" style="width:70%">
<div class="btn-group">
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(21)">#Language.T138</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(22)">#Language.T38</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(23)">#Language.T39</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(24)">#Language.T40</button>
</div>
</div>
</div>
</div>
This is the full code here. Im new with this code. Please tell me how to put a js code without error ( error no component )
#page "/results"
#inject Blazored.LocalStorage.ISyncLocalStorageService localStore
#inject IJSRuntime JSRuntime;
#inject Toolbelt.Blazor.I18nText.I18nText I18nText
<h1>#Language.T8</h1>
<div>
<div class="row">
<div class="column" id="chartColumn" style="width:80%;text-align:center">
<canvas id="myChart"></canvas>
</div>
<div class="column" style="width:20%;text-align:center;font-size:1.5vw">
<br />
<br />
<br />
<br />
<span>
#ResultInText <br />
</span>
<h1 style="font-weight:bolder">#FilterSavings</h1>
<br />
<br />
<span>
#WasteTextPaper<br />
#WasteTextPlastic
</span>
#if (SelectedChartCategory == 13)
{
<br />
<br />
<br />
<br />
<br />
}
<span style="font-size:0.4vw">#DisclaimerText</span>
</div>
</div>
<hr />
<div class="row">
<div class="column" style="width:30%">
<b>#Language.T33</b>
</div>
<div class="column" style="width:70%">
<b>#Language.T34</b>
</div>
</div>
<div class="row">
<div class="column" style="width:30%">
<div class="btn-group">
<button type="button" class="btn btn-primary" style="outline-color:red" #onclick="() => UpdateTheChart(11)">#Language.T35</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(12)">#Language.T36</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(13)">#Language.T37</button>
</div>
</div>
<div class="column" style="width:70%">
<div class="btn-group">
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(21)">#Language.T138</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(22)">#Language.T38</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(23)">#Language.T39</button>
<button type="button" class="btn btn-primary" #onclick="() => UpdateTheChart(24)">#Language.T40</button>
</div>
</div>
</div>
</div>
#code {//handles initialization
I18nText.Language Language = new I18nText.Language();
List<float> retResultMHC = null;
List<float> retResultCom = null;
string retResultMHCProduct = "";
string retResultCOMProduct = "";
double retResultCostSavings = 0;
double retResultTimeSavings = 0;
double retResultWasteReduction = 0;
double retResultWastePaper = 0;
double retResultWastePlastic = 0;
string retResultWasteFlag = "";
string retResultCostFlag = "";
string retResultTimeFlag = "";
string FilterSavings = "";
string WasteTextPaper = "";
string WasteTextPlastic = "";
string retCurrency = "";
string DisclaimerText = "";
string ResultInText = "Cost savings for all patients during a year";
int SelectedChartCategory = 11;
int SelectedChartPeriod = 24;
int CalChartPeriod = 1;
string SelectedResultFlag = "savings";
string PeriodUOM = "year";
protected override void OnInitialized()
{
InitializeLocalStorage();
if (retResultMHC != null && retResultCom != null)
{
UpdateTheChart(11);
}
}
protected override async Task OnInitializedAsync()
{
Language = await I18nText.GetTextTableAsync<I18nText.Language>(this);
ResultInText = Language.T118 + Language.T127;
}
private void InitializeLocalStorage()
{
retResultMHCProduct = localStore.GetItemAsString("Result-MHC-Product");
retResultCOMProduct = localStore.GetItemAsString("Result-COM-Product");
retResultMHC = localStore.GetItem<List<float>>("Result-MHC");
retResultCom = localStore.GetItem<List<float>>("Result-COM");
retResultCostSavings = localStore.GetItem<double>("Result-Cost-Savings");
retResultTimeSavings = localStore.GetItem<double>("Result-Time-Savings");
retResultWasteReduction = localStore.GetItem<double>("Result-Waste-Reduction");
retResultCostFlag = localStore.GetItemAsString("Result-Cost-Flag");
retResultTimeFlag = localStore.GetItemAsString("Result-Time-Flag");
retResultWasteFlag = localStore.GetItemAsString("Result-Waste-Flag");
retResultWastePaper = localStore.GetItem<double>("Result-Waste-Paper");
retResultWastePlastic = localStore.GetItem<double>("Result-Waste-Plastic");
retCurrency = localStore.GetItemAsString("CurrencyKey");
}
}
#code{//handles chart
private IJSObjectReference _jsModule;
//this will be the live code
private async Task UpdateTheChart(int clickedButton)
{
//assign the selected parameters
if (clickedButton == 11 || clickedButton == 12 || clickedButton == 13)
SelectedChartCategory = clickedButton;
else
SelectedChartPeriod = clickedButton;
if (SelectedChartPeriod == 21)
{
PeriodUOM = Language.T124;
CalChartPeriod = 365;
}
else if (SelectedChartPeriod == 22)
{
PeriodUOM = Language.T125;
CalChartPeriod = 52;
}
else if (SelectedChartPeriod == 23)
{
PeriodUOM = Language.T126;
CalChartPeriod = 12;
}
else if (SelectedChartPeriod == 24)
{
PeriodUOM = Language.T127;
CalChartPeriod = 1;
}
else
{
PeriodUOM = Language.T127;
CalChartPeriod = 1;
}
ResultInText = "";
//things to do before showing the selected chart
if (SelectedChartCategory == 11)
{
if (retResultCostFlag == "savings")
ResultInText = Language.T118 + PeriodUOM;
else
ResultInText = Language.T119 + PeriodUOM;
WasteTextPaper = "";
WasteTextPlastic = "";
FilterSavings = string.Format(retCurrency + "{0:n0}", retResultCostSavings / CalChartPeriod);
DisclaimerText = "";
}
else if (SelectedChartCategory == 12)
{
if (retResultCostFlag == "savings")
ResultInText = Language.T120 + PeriodUOM;
else
ResultInText = Language.T121 + PeriodUOM;
WasteTextPaper = "";
WasteTextPlastic = "";
FilterSavings = string.Format("{0:n0}", retResultTimeSavings / CalChartPeriod) + " " + Language.T134;
DisclaimerText = "";
}
else if (SelectedChartCategory == 13)
{
if (retResultCostFlag == "reduction")
ResultInText = Language.T122 + PeriodUOM;
else
ResultInText = Language.T123 + PeriodUOM;
WasteTextPaper = Language.T128 + string.Format("{0:n2}", retResultWastePaper / CalChartPeriod) + " " + Language.T135;
WasteTextPlastic = Language.T129 + string.Format("{0:n2}", retResultWastePlastic / CalChartPeriod) + " " + Language.T135;
FilterSavings = string.Format("{0:n2}", retResultWasteReduction / CalChartPeriod) + " " + Language.T135;
DisclaimerText = Language.T136;
}
//calling js to make the chart
_jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/MakeChart.js");
if (SelectedChartCategory == 11)
{
await _jsModule.InvokeVoidAsync("showChartCost", CalChartPeriod, Language.T131, Language.T132, Language.T133);
}
else if (SelectedChartCategory == 12)
{
await _jsModule.InvokeVoidAsync("showChartTime", CalChartPeriod, Language.T130);
}
else
{
await _jsModule.InvokeVoidAsync("ShowChartPic");
}
}
}
Are you sure you want to use Javascript? You can use variables to update properties in Blazor:
<button style="background-color:#bgcolor" #onclick=SetColor>Click</button>
#code
{
string bgcolor {get; set;} = "00f"; // (starting value)
void SetColor(){
bgcolor = "#fd7"; (will update instantly)
StateHasChanged(); // may not be required, but I'm at work right now, so can't check
}
}
Better would be to use a variable to set the CLASS of the object:
<button class="#buttonclass" #onclick=SetColor>Click</button>
#code
{
string buttonclass{get; set;} = "btn btn.primary"; // (starting value)
void SetColor(){
buttonclass= "btn btn.secondary";
StateHasChanged(); // may not be required, but I'm at work right now, so can't check
}
}
Also, it looks like you have a lot of repeated entries. In Blazor, consider having a List with all your various languages, and do this in your markup:
<div>
#foreach (item in LanguageItems){
<button class="btn btn-primary" >#item.Language</button>
}
</div>
#code
{
List<MyLanguageClass> LanguageItems {get; set;}
protected override async Task OnInitializedAsync(){
// Loadup your list of items from a database or whatever
}
}
I use css(.btn:focus) and it can work.Here is a demo:
<div>
<div class="row">
<div class="column" style="width:30%">
<div class="btn-group">
<button type="button" class="btn btn-primary">Language.T35</button>
<button type="button" class="btn btn-primary">Language.T36</button>
<button type="button" class="btn btn-primary">Language.T37</button>
</div>
</div>
<div class="column" style="width:70%">
<div class="btn-group">
<button type="button" class="btn btn-primary">Language.T138</button>
<button type="button" class="btn btn-primary">Language.T38</button>
<button type="button" class="btn btn-primary">Language.T39</button>
<button type="button" class="btn btn-primary">Language.T40</button>
</div>
</div>
</div>
</div>
<style>
.btn:focus {
background-color: #ff6e40;
}
</style>
result:
Ok. So what you can do in javascript is to write `document.getElementById("id of button").backgroundColor="whatever color you need to set in button"'
<button onclick="updateColor(this)">click me</button>
inside of javascript
function updateColor(btn){
btn.style.backgroundColor = 'red';
btn.style.color = 'white';
}
I'll explain what's going on here.
Inside the button the onclick attribute takes a function (or a javascript instruction) and you can pass the clicked button inside the arguments as this.
then you can modify the clicked element in javascript function.
edit:
to use JavaScript you use the script tag as follows...
<script>
// your JavaScript code
</script>
just put the above script tag at the end of the body.
It's not good to write all JavaScript code inside the html script tag.
So instead you can just add src to the script tag and link to a separate javascript file like...
<script src="./yourpath/filename.js"></script>

Condense IF Statement As Seems Over Kill

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');
})

jQuery multiple plus/minus Counter

I want to have multiple plus/minus counters on my page.
I have one working counter but want to make it generic so that multiple counters can have a different initial value and increase and decrease as clicked.
$('.counter-btn').click(function(e) {
e.preventDefault();
var $btn = $(this);
$('.output').html(function(i, val) {
val = val * 1 + $btn.data('inc');
return (val <= 0 ? '' : '+') + val;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>
<hr />
<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>
Fiddle Link:
http://jsfiddle.net/u2Lh7dbp/
Thanks
Each output element should be unique so it can be called by itself.
$('.counter-btn').click(function(e) {
e.preventDefault();
var $btn = $(this);
$('#output-' + $btn.data('index')).html(function(i, val) {
val = val * 1 + $btn.data('inc');
return (val <= 0 ? '' : '+') + val;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-index="1" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-index="1" data-inc="-1">-</button>
<div class="output" id="output-1">+30</div>
<hr />
<button class="counter-btn" id="increase2" type="button" data-index="2" data-inc="1">+</button>
<button class="counter-btn" id="decrease2" type="button" data-index="2" data-inc="-1">-</button>
<div class="output" id="output-2">+30</div>
I've added a new data attribute: index. You can use that index to specify the exact output element you're looking for by its id.
Keeping it simple, you can have two functions and directly associate the onClick callback to these functions, making it more clear on the html side.
function add(id) {
var newCount = parseInt($(id).text()) + 1;
$(id).text(newCount);
}
function substract(id) {
var newCount = parseInt($(id).text()) - 1;
$(id).text(newCount);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="add('#output1')">+</button>
<button type="button" onclick="substract('#output1')">-</button>
<div id="output1">30</div>
<hr />
<button type="button" onclick="add('#output2')">+</button>
<button type="button" onclick="substract('#output2')">-</button>
<div id="output2">30</div>

One function for two buttons (increment, decrement)

I want to be able to increment and also decrement a value (5) and I would like to cover this with one function (I know how to do it with two).
Unfortunately I am not able to get it done and can't figure out what is wrong.
Here is my code:
HTML:
<form>
<button type="button" value="minus" onclick="updateAmount();">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount();">
+
</button>
</form>
JS:
var num = parseInt(document.getElementById('number');
var btn = document.querySelector('button');
btn.addEventListener('click', updateAmount);
function updateAmount(){
btn.value === "minus" ? num-- : num++;
document.getElementById('number').value = num;
}
Also at JSfiddle
I would prefer a vanilla JS solution if possible, but any suggestion is welcome :)
Thanks!
The minimal-changes to your approach is to pass an argument to the function:
function updateAmount(value) {
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(-1);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(1);">
+
</button>
</form>
Or use your value attribute and pass this into the function:
function updateAmount(btn) {
var value = btn.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>
That latter approach combines nicely with modern event handling:
// Scoping function so our `updateAmount` isn't global
(function() {
document.querySelector("button[value=minus]").addEventListener("click", updateAmount);
document.querySelector("button[value=plus]").addEventListener("click", updateAmount);
function updateAmount() {
var value = this.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
})();
<form>
<button type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus">
+
</button>
</form>
You could hand over the action as a parameter
<form>
<button type="button" value="minus" onclick="updateAmount('minus');">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount('plus');">
+
</button>
</form>
and then
function updateAmount(action) {
var num = parseInt(document.getElementById("number").innerHTML, 10);
switch(action) {
case 'minus':
num--;
break;
case 'plus':
num++;
break;
}
document.getElementById("number").innerHTML = num;
}
You can try this ...
<html>
<form>
<button type="button" value="minus" onclick="updateAmount(this.value);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this.value);">
+
</button>
</form>
<script>
function updateAmount(value){
var num = parseInt(document.getElementById('number').innerHTML);
value=='plus'?num++:num--;
document.getElementById('number').innerHTML = num;
}
</script>
</html>
You were close, as you have multiple elements use document.querySelectorAll() with valid selector to get there reference and bind event handlers.
As you are using <SPAN> element, it doesn't have value property, need to use textContent property.
var btns = document.querySelectorAll('button');
btns.forEach(function(btn) {
btn.addEventListener('click', updateAmount);
});
function updateAmount() {
var num = parseInt(document.getElementById('number').textContent.trim(), 10);
this.value === "minus" ? num-- : num++;
document.getElementById('number').textContent = num;
}
<button type="button" value="minus">-</button>
<span id="number">5</span>
<button type="button" value="plus">+</button>
Note: Get rid of ugly inline click handlers.
simply use like this updateAmount(this)
function updateAmount(that) {
var number = document.getElementById('number');
var num = parseInt(number.innerHTML);
num = (that.value == "minus") ? --num : ++num;
number.innerHTML = num;
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>
var minusBtn = document.querySelector('#minus');
var plusBtn = document.querySelector('#plus');
minusBtn.addEventListener('click', updateAmount('minus'));
plusBtn.addEventListener('click', updateAmount('plus'));
function updateAmount(action) {
return function() {
var numberElem = document.getElementById('number');
var number = numberElem.innerText;
number = parseInt(number, 10);
if (action === 'minus') {
number--;
} else if(action === 'plus') {
number++;
} else {
throw new Error('invalid operator');
}
numberElem.innerText = number;
};
}
<form>
<button id = "minus" type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button id = "plus" type="button" value="plus">
+
</button>
</form>
this is a good example for curry function, you can currify your updateAmount to accept action as a part of argument
Your code has just two small flaw, rest is perfect.
Firstly Your variable num is evaluating to NaN.
Secondly you should use textContent instead of value .
I am sharing correct way to evaluate num and then it will work.
var el =document.getElementById('number')
var num = parseInt(el.textContent);
Again, while updating
document.getElementById('number').textContent = num
Hope it helped.

Javascript - Toggle Visibility

I am trying to display a button when the input is valid.
It doesn't work, it just displays all the buttons.
Here is the JavaScript:
var toggleVisibility = function ()
{
hasOccurred = validate(textEntry);
if (hasOccurred == false) {
$("addBtn").style.visibility = "visible";
$("deleteBtn").style.visibility = "hidden";
}
else if (hasOccurred == true) {
$("addBtn").style.visibility = "hidden";
$("deleteBtn").style.visibility = "visible";
}
}
This is the HTML for the buttons:
<button type="button" class="btn btn-success" id="addBtn" oninput="toggleVisibility()"><i class="glyphicon glyphicon-plus-sign"></i> Add to Array</button><br/>
<button type="button" class="btn btn-danger" oninput="toggleVisibility()" id="deleteBtn"><i class="glyphicon glyphicon-remove-sign"></i> Delete from Array</button><br/>
<button type="button" class="btn btn-info" id="sumBtn">Sum of Array</button>
You're using the $ as if you're using jQuery (but with incorrect CSS selectors). Without jQuery you need document.getElementById("...")
Note: I changed hasOccurred so that the snippet works.
var toggleVisibility = function() {
hasOccurred = false;
if (hasOccurred == false) {
document.getElementById("addBtn").style.visibility = "visible";
document.getElementById("deleteBtn").style.visibility = "hidden";
} else if (hasOccurred == true) {
document.getElementById("addBtn").style.visibility = "hidden";
document.getElementById("deleteBtn").style.visibility = "visible";
}
}
toggleVisibility();
<button type="button" class="btn btn-success" id="addBtn" oninput="toggleVisibility()"><i class="glyphicon glyphicon-plus-sign"></i> Add to Array</button>
<br/>
<button type="button" class="btn btn-danger" oninput="toggleVisibility()" id="deleteBtn"><i class="glyphicon glyphicon-remove-sign"></i> Delete from Array</button>
<br/>
<button type="button" class="btn btn-info" id="sumBtn">Sum of Array</button>

Categories

Resources