Removing element by value from array - javascript

I am working on the following problem:
If user selects any of Toyota, Mazda, and Nissan Then remove All from makeArr array if exist
and
If user selects All Then remove any of Toyota, Mazda, and Nissan from makeArr array if they exist
I tried to use this code
makeArr.splice($.inArray("All", makeArr), 1);
in the else part but it is not working!
var makeArr = [];
$(".btn-primary").on("click", function() {
let make = $(this).data('make');
if (make === "All") {
var idx = $.inArray(make, makeArr);
if (idx == -1) {
makeArr.push(make);
} else {
makeArr.splice(idx, 1);
}
} else {
// makeArr.splice($.inArray("All", makeArr), 1);
var idx = $.inArray(make, makeArr);
if (idx == -1) {
makeArr.push(make);
} else {
makeArr.splice(idx, 1);
}
}
console.log(makeArr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="container p-2">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-primary" data-make="Toyota">Toyota</button>
<button type="button" class="btn btn-primary" data-make="Mazda">Mazda</button>
<button type="button" class="btn btn-primary" data-make="Nissan">Nissan</button>
<button type="button" class="btn btn-primary" data-make="All">All</button>
</div>
</div>

Your issue is that when you select All, you're not checking if there are any other models in the array already. It's simplest in that case just to check for All in the array, and if it is there, empty the array, otherwise set it to ['All']. Likewise, when a specific model is selected, you need to remove 'All' from the array if it is in there before adding/removing the selected model.
var makeArr = [];
$(".btn-primary").on("click", function() {
let make = $(this).data('make');
if (make === "All") {
idx = makeArr.indexOf('All');
makeArr = idx == -1 ? ['All'] : [];
} else {
idx = makeArr.indexOf('All');
if (idx != -1) {
makeArr.splice(idx, 1)
}
idx = makeArr.indexOf(make);
if (idx != -1) {
makeArr.splice(idx, 1)
} else {
makeArr.push(make);
}
}
console.log(makeArr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="container p-2">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-primary" data-make="Toyota">Toyota</button>
<button type="button" class="btn btn-primary" data-make="Mazda">Mazda</button>
<button type="button" class="btn btn-primary" data-make="Nissan">Nissan</button>
<button type="button" class="btn btn-primary" data-make="All">All</button>
</div>
</div>

Related

How do I disable multiple buttons when I click a button

<script type="text/javascript">
function button1() {
var elem = document.getElementById("button1");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
function button2() {
var elem = document.getElementById("button2");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
function button3() {
var elem = document.getElementById("button3");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
function button4() {
var elem = document.getElementById("button4");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
function button5() {
var elem = document.getElementById("button5");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
</script>
How do disable all the buttons if I select one button. Do I have to disable all the buttons one by one or is there a way to do all the buttons.
Alright, with whatever you have given, maybe you're looking for something like a radio button. I am using Bootstrap and jQuery - it's much easier than vanilla JavaScript to achieve something that you're trying to do:
$(function () {
$(".btn").click(function () {
$(".btn").prop("disabled", true);
$(this).prop("disabled", false).addClass("active");
$("p").text("You have clicked on button #" + $(this).data("id") + ".");
$(this).text("Selected");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous" />
<div class="p-5">
<button class="btn btn-primary button-1" data-id="1">Choose 1</button>
<button class="btn btn-primary button-2" data-id="2">Choose 2</button>
<button class="btn btn-primary button-3" data-id="3">Choose 3</button>
<button class="btn btn-primary button-4" data-id="4">Choose 4</button>
<button class="btn btn-primary button-5" data-id="5">Choose 5</button>
<p id="status" class="py-3"></p>
</div>
On clicking of any button above, the respective button will be activated and the others will be disabled.
Resetting...
Option One: Using the same button!
$(function () {
$(".btn").click(function () {
if ($(this).hasClass("active")) {
$(".btn").prop("disabled", false);
$("p").text("");
$(this).text("Choose " + $(this).data("id"));
} else {
$(".btn").prop("disabled", true);
$(this).prop("disabled", false).addClass("active");
$("p").text("You have clicked on button #" + $(this).data("id") + ".");
$(this).text("Selected");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous" />
<div class="p-5">
<button class="btn btn-primary button-1" data-id="1">Choose 1</button>
<button class="btn btn-primary button-2" data-id="2">Choose 2</button>
<button class="btn btn-primary button-3" data-id="3">Choose 3</button>
<button class="btn btn-primary button-4" data-id="4">Choose 4</button>
<button class="btn btn-primary button-5" data-id="5">Choose 5</button>
<p id="status" class="py-3"></p>
</div>
Option Two: Using a Cancel Button
$(function () {
$(".btn-primary").click(function () {
$(".btn-primary").prop("disabled", true);
$(this).prop("disabled", false).addClass("active");
$(".btn-info").prop("disabled", false);
$("p").text("You have clicked on button #" + $(this).data("id") + ".");
$(this).text("Selected");
});
$(".btn-info").click(function () {
$(".btn").prop("disabled", false);
$("p").text("");
$(".btn-primary").text(function () {
return "Choose " + $(this).data("id");
});
$(this).prop("disabled", true);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous" />
<div class="p-5">
<button class="btn btn-primary button-1" data-id="1">Choose 1</button>
<button class="btn btn-primary button-2" data-id="2">Choose 2</button>
<button class="btn btn-primary button-3" data-id="3">Choose 3</button>
<button class="btn btn-primary button-4" data-id="4">Choose 4</button>
<button class="btn btn-primary button-5" data-id="5">Choose 5</button>
<p id="status" class="py-3"></p>
<button class="btn btn-info" disabled>Cancel</button>
</div>
I hope the above two solutions are something that you're looking for! 😁
Always avoid repetitive code.
By "disabling all buttons", I guess you mean set their value back to "Choose".
<script type="text/javascript">
function buttonBehavior(num) {
// reset all buttons
let i=1;
while(document.getElementById("button"+i)!==null) {
document.getElementById("button"+i).value = 'Choose';
i++;
}
// set selected button
var elem = document.getElementById("button"+num);
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
</script>

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>

Save values of multiple clicks and get all values inline

I have multiple buttons on my page. I want to get the values for those and displayed in one line. How do I do that.
I have 3 buttons, onclick they return these values:
Dark : returns 'scoop'
Danger : returns 'swoosh'
Warning : returns 'spoon'
I have one big button (info), on clicking that I want that to return: scoop&swoosh&spoon
How do I do that?
let val;
$('#one').on('click', function(){
val = 'scoop';
});
$('#two').on('click', function(){
val = 'swoosh';
});
$('#three').on('click', function(){
val = 'spoon';
});
$('#main').on('click', function(){
console.log(val);
//Expected value: scoop&swoosh&spoon
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<div><button id="one" type="button" class="btn btn-dark m-3">Dark</button></div>
<div><button id="two" type="button" class="btn btn-danger m-3">Danger</button></div>
<div><button id="three" type="button" class="btn btn-warning m-3">Warning</button></div>
<hr />
<div><button id="main" type="button" class="btn btn-info btn-block">Info</button></div>
Currently, each click resets the variable, assigning a new value. Consider using an Array and updating it with a new item for each click.
Example:
let val = [];
$('button').on('click', function() {
switch ($(this).attr("id")) {
case "one":
val.push('scoop');
break;
case "two":
val.push('scoop');
break;
case "three":
val.push('scoop');
break;
}
});
$('#main').on('click', function() {
console.log(val.join(" & "));
// Example Value: scoop & swoosh & spoon
// Clear the array
val = [];
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<div><button id="one" type="button" class="btn btn-dark m-3">Dark</button></div>
<div><button id="two" type="button" class="btn btn-danger m-3">Danger</button></div>
<div><button id="three" type="button" class="btn btn-warning m-3">Warning</button></div>
<hr />
<div><button id="main" type="button" class="btn btn-info btn-block">Info</button></div>

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>

Categories

Resources