I'm working on a small project and I have an array with 4 numbers. I want to display them on 4 buttons. I tried this code but it doesn't seem to be working. Do you have any ideas where I could make a mistake ?
<div id="results">
<button type="button" class="btn btn-primary button-result" id="button1">Result</button>
<button type="button" class="btn btn-primary button-result" id="button2">Result</button>
<button type="button" class="btn btn-primary button-result" id="button3">Result</button>
<button type="button" class="btn btn-primary button-result" id="button4">Result</button>
</div>
var rnum1 = generateRandomNumber1();
var rnum2 = generateRandomNumber2();
var rnums = [rnum1, rnum2];
var rnumsSort = rnums.sort(function(a, b) {
return b - a
});
//pass the random numbers to the function
var data = generateRandomOperatorAndCorrectResult(rnumsSort[0], rnumsSort[1]);
//data=["+", [5]]
var operator = data[0];
var corResult = data[1][0][0];
var ranResult = [data[1][0][1], data[1][0][2], data[1][0][3]];
var allResults = data[1][0];
var sortAllResults = allResults.sort(function(a, b) {
return a - b
});
var buttonText = buttonResult();
function buttonResult() {
for (var i = 0; i < sortAllResults.length; i++) {
document.querySelectorAll(".button-result").textContent = sortAllResults[i];
}
}
You're attempting to set the textContent of a NodeList in this line:
document.querySelectorAll(".button-result").textContent= sortAllResults[i];
You need to select the index of the current button:
document.querySelectorAll(".button-result")[i].textContent= sortAllResults[i];
just a small working example how you can fill your Buttons.
const randomNumber = Math.floor(1000 + Math.random() * 9000);
[...myArray] = randomNumber.toString();
const insertResult = (origArray) => {
const myButtons = Array.from(document.getElementsByClassName('button-result'));
origArray.sort((a, b) => b - a);
myButtons.forEach((button, index) => button.textContent = myArray[index]);
};
insertResult(myArray);
<div id="results">
<button type="button" class="btn btn-primary button-result" id="button1">Result</button>
<button type="button" class="btn btn-primary button-result" id="button2">Result</button>
<button type="button" class="btn btn-primary button-result" id="button3">Result</button>
<button type="button" class="btn btn-primary button-result" id="button4">Result</button>
</div>
Related
I want to make the third button graph disabled at first and after the first 2 buttons (button1 and button2) is pressed and hidden, third will be enabled and can click on it.
<button type="button" class="btn btn-primary" id="button1" onclick="dataButton1(); this.style.visibility= 'hidden'; this.disabled=true">Data1</button>
<button type="button" class="btn btn-primary" id="button2" onclick="dataButton2();this.style.visibility= 'hidden'; this.disabled=true">data2</button>
<button type="button" class="btn btn-primary " id="button3" onclick="chart1();this.style.visibility= 'hidden'; this.disabled=true">Graph</button>
Have a go with this
const dataButton1 = () => console.log("1")
const dataButton2 = () => console.log("2")
const chart1 = () => console.log("chart 1")
const container = document.getElementById("container");
const buttons = [...container.querySelectorAll("button")];
container.addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.id === "button1") {
dataButton1();
}
else if (tgt.id === "button2") {
dataButton2();
}
else if (tgt.id === "button3") {
chart1();
}
tgt.setAttribute("hidden",true); // hide
const show = buttons.map(btn => btn.getAttribute("hidden")); // cannot use hasAttribute here
if (show[0] && show[1] && !show[2]) buttons[2].removeAttribute("disabled");
})
<div id="container">
<button type="button" class="btn btn-primary" id="button1">Data1</button>
<button type="button" class="btn btn-primary" id="button2">Data2</button>
<button type="button" class="btn btn-primary" id="button3" disabled>chart</button>
</div>
First add disable attribute to third button. Then on each click of button 1 and 2 check for hasAttribute("disabled") of other button to see both of them are clicked (and disabled) or not
Here is working sample:
function dataButton1() {
if (document.getElementById("button2").hasAttribute("disabled"))
document.getElementById("button3").setAttribute("disabled", false);
}
function dataButton2() {
if (document.getElementById("button1").hasAttribute("disabled"))
document.getElementById("button3").removeAttribute("disabled");
}
<button type="button" class="btn btn-primary" id="button1"
onclick="dataButton1(); this.style.visibility='hidden'; this.disabled=true">
Data1
</button>
<button type="button" class="btn btn-primary" id="button2"
onclick="dataButton2();this.style.visibility= 'hidden'; this.disabled=true">
data2
</button>
<button disabled type="button" class="btn btn-primary " id="button3">
chart
</button>
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>
I have 10 different buttons each have a common class and a unique class.
<button type="button" class="topic btn1" data-target="desc1">Safety</button>
<button type="button" class="topic btn2" data-target="desc2">Environment</button>
<button type="button" class="topic btn3" data-target="desc3">Climate change</button>
<button type="button" class="topic btn4" data-target="desc4">Sustainability</button>
<button type="button" class="topic btn5" data-target="desc5">Business strategy</button>
<button type="button" class="topic btn6" data-target="desc6">Performance data</button>
<button type="button" class="topic btn7" data-target="desc7">Working for Shell</button>
<button type="button" class="topic btn8" data-target="desc8">Working together</button>
<button type="button" class="topic btn9" data-target="desc9">Social performance</button>
<button type="button" class="topic btn10" data-target="desc10">Human rights</button>
A function is applied on that which will add one extra unique class to each button.
for (let i = 0; i <= 12; i++) {
$( ".btn" + i ).click(function() {
$( this ).toggleClass( "act-btn" + i );
});
}
Now i want to create two buttons:-
Show All: When some one click on this, third unique class act-btn1 to act-btn10 will be added in the same order.
Reset: When someone click on that reset button, only the extra added class will be removed, rest will be same.
$('.add').click(function() {
for (let i = 1; i <= 10; i++) {
$('.btn' + i).addClass( "act-btn" + i);
}
});
$('.remove').click(function() {
for (let i = 1; i <= 10; i++) {
$('.btn' + i).removeClass( "act-btn" + i);
}
});
<button class="add">Add class</button>
<button class="remove">remove class</button>
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.
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>