Remove the div of the previous selection in jQuery and add the current selection by appending it, ensuring only one selection per row is allowed when

Here is a code snippet that includes buttons appending selections to the "cart" div upon clicking.

The first script ensures only one selection per row when multiple buttons in the same row are clicked.

In the second script, selections are appended to the "cart" div and removed if they have been unselected.

An issue arises when clicking on multiple buttons in the same row. The first script works as intended, deactivating the previous selection and activating the current button. However, the second script is meant to update the new selection for the active button and remove the previous one in the same row.

How can I amend the second script to address this functionality?

<body style="margin:10px;">


  <div class="cart">
  
    <div id="box" class="boxlit"></div><br>
  
  </div>


  <table id="Table1" class="Fixtures-Table">


    <thead class="disnon">
      <tr>   
          <th>League</th>
          <th>Home [1]</th>
          <th>Draw [x]</th>
          <th>Away [2]</th>
          <th>Kickoff</th>
      </tr>
  </thead>


  <tr class="items" style="display: table-row;">
            
    <td class="addItem">Almagro-Temperley</td> 
    <td id="bbox"><input type="button" class="decimals" id="3" value="1.95" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="4" value="2.95" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="5" value="3.90" data-selected="false"></td>
    <td id="date">8/1/2022 8:00:00 PM</td> 
    
  </tr>

  <tr class="items" style="display: table-row;">
              
    <td class="addItem">Guillermo Brown-Santamarina</td> 
    <td id="bbox"><input type="button" class="decimals" id="6" value="1.65" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="7" value="3.25" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="8" value="5.10" data-selected="false"></td>
    <td id="date">8/1/2022 8:00:00 PM</td> 
    
  </tr>

  <tr class="items" style="display: table-row;">
              
    <td class="addItem">Nueva Chicago-CSD Flandria</td> 
    <td id="bbox"><input type="button" class="decimals" id="9" value="2.25" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="10" value="2.85" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="11" value="3.15" data-selected="false"></td>
    <td id="date">8/1/2022 8:00:00 PM</td> 
    
  </tr>

</table>


</body>

</html>

The first script allows one selection per row upon clicking multiple buttons within the same row.

<script>

$(document).ready(function(){

$('.decimals').click(function() { 

if ($(this).attr('data-selected') === 'true') {

$(this).attr('data-selected', 'false');

$(this).removeClass('active');

} else {

$(this).closest('tr').find('.decimals').not(this)

.removeClass('active').attr('data-selected', 'false');

$(this).attr('data-selected', 'true');

$(this).addClass('active');

}

});
});

</script>

The second script appends selections to the "cart" div and updates them when choices change or get deselected.

It should replace the previous selection in the same row with the current active button's choice.

<script>


  let $th = $('#Table1 thead th');
  
  $(".decimals").on('click', e => {
    
  let $btn = $(e.target);
  let $option = $(`.box[data-id="${$btn.prop('id')}"]`);
  
  let $tr = $btn.closest('tr');
  let selectionIndex = $btn.closest('td').index();
  
  let kickoff = $tr.find('td:last').text().trim();
  let match = $tr.find('td:first').text().trim();
  
  let result = $th.eq(selectionIndex).text().trim();
  let value = $btn.val();
  
  if ($option.length){
  $option.remove();
  
  return;
  }
  
  $("#box").append(`<div class="box" data-id="${$btn.prop('id')}">${match}<br>${result}<div class="crtTotal">${value}</div><input type="hidden" name="kickoff[]" value="${kickoff}"/><input type="hidden" name="match[]" value="${match}"/><input type="hidden" name="result[]" value="${result}" readonly/><input type="hidden" name="value[]" value="${value}"/></div>`);
  
  
  });
  
  
  </script>



.decimals {
    background-color: rgb(31, 31, 31);
    color: rgb(255, 255, 255);
    border: 2px solid #0e1516;
    border-radius: 4px;
    font-size: 13px;
    padding: 4px 10px;
    font-weight: bold;
    border-width: 1px;
    cursor: pointer;
}

.decimals:hover {
     background: rgb(51, 51, 51);
}

.active,
.active:hover {

    background: rgb(161, 0, 0);
    color: rgb(255, 255, 255);
    border-color: rgb(156, 0, 0);
    
}

Answer №1

The problem was traced back to the set timeout function, which was causing issues. I made some adjustments in the code snippet below:

Now, when the stake is changed, it updates accordingly after adding a small line of code.

let $th = $('#Table1 thead th');

$('.decimals').click(function(e) { 

let $btn = $(e.target);
  let $option = $(`.box[data-id="${$btn.prop('id')}"]`);
  
  let $tr = $btn.closest('tr');
  let selectionIndex = $btn.closest('td').index();
  
  let kickoff = $tr.find('td:last').text().trim();
  let match = $tr.find('td:first').text().trim();
  
  let result = $th.eq(selectionIndex).text().trim();
  let value = $btn.val();

var knowit = $(this).closest('.items').find('.addItem').text();

var radiovalue = $(this).attr('value');


if ($('.boxlit .box:contains("'+knowit+'")').length < 1) {


  $("#box").append(`<div class="box" data-id="${$btn.prop('id')}">${match}<br><span>${result}</span><div class="crtTotal">${value}</div><input type="hidden" name="kickoff[]" value="${kickoff}"/><input type="hidden" name="match[]" value="${match}"/><input type="hidden" name="result[]" value="${result}" readonly/><input type="hidden" name="value[]" value="${value}"/></div>`);}

else if ($(this).hasClass('active')) {
$('.boxlit .box:contains("'+knowit+'")').remove()
}


else {
$('.boxlit .box:contains("'+knowit+'") .crtTotal').text(radiovalue);

$('.boxlit .box:contains("'+knowit+'") span').text(result);
}

})
.decimals {
    background-color: rgb(31, 31, 31);
    color: rgb(255, 255, 255);
    border: 2px solid #0e1516;
    border-radius: 4px;
    font-size: 13px;
    padding: 4px 10px;
    font-weight: bold;
    border-width: 1px;
    cursor: pointer;
}

.decimals:hover {
     background: rgb(51, 51, 51);
}

.active,
.active:hover {

    background: rgb(161, 0, 0);
    color: rgb(255, 255, 255);
    border-color: rgb(156, 0, 0);
    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body style ="margin:10px;">


  <div class="cart">
  
    <div id="box" class="boxlit"></div><br>

<div class="shift">

  <div>Total Odds: <b id="ct1">0.00</b></div><br>

  <div>(N$)Stake: <input id="stake" type ="number" name="stake[]" value="5"> NAD</div><br>

  <div>Payout: N$ <b id="payout">0.00</b></div>

  <input class="bet1" type="submit" name="submit" value="Bet">

</div>
  
  </div>


  <table id="Table1" class="Fixtures-Table">


    <thead class="disnon">
      <tr>   
          <th>League</th>
          <th>Home [1]</th>
          <th>Draw [x]</th>
          <th>Away [2]</th>
          <th>Kickoff</th>
      </tr>
  </thead>


  <tr class="items" style="display: table-row;">
            
    <td class="addItem">Almagro-Temperley</td> 
    <td id="bbox"><input type="button" class="decimals" id="3" value="1.95" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="4" value="2.95" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="5" value="3.90" data-selected="false"></td>
    <td id="date">8/1/2022 8:00:00 PM</td> 
    
  </tr>

  <tr class="items" style="display: table-row;">
              
    <td class="addItem">Guillermo Brown-Santamarina</td> 
    <td id="bbox"><input type="button" class="decimals" id="6" value="1.65" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="7" value="3.25" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="8" value="5.10" data-selected="false"></td>
    <td id="date">8/1/2022 8:00:00 PM</td> 
    
  </tr>

  <tr class="items" style="display: table-row;">
              
    <td class="addItem">Nueva Chicago-CSD Flandria</td> 
    <td id="bbox"><input type="button" class="decimals" id="9" value="2.25" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="10" value="2.85" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="11" value="3.15" data-selected="false"></td>
    <td id="date">8/1/2022 8:00:00 PM</td> 
    
  </tr>

</table>


<script>

$(document).ready(function(){

$('.decimals').click(function() { 

if ($(this).attr('data-selected') === 'true') {

$(this).attr('data-selected', 'false');

$(this).removeClass('active');

} else {

$(this).closest('tr').find('.decimals').not(this)

.removeClass('active').attr('data-selected', 'false');

$(this).attr('data-selected', 'true');

$(this).addClass('active');

}

});
});

</script>



<script>

$(document).ready(function(){

$('.decimals').click(function(e) { 
 updateoddsnpayout();
})

$('body').on('change', '#stake', function(e){
 updateoddsnpayout();
})

var updateoddsnpayout =  function(e) {
let values = $('.crtTotal').map((i, el) => parseFloat(el.textContent)).get();
let total = values.reduce((a, b) => a * b, values.length > 0 ? 1 : 0);
let eq = 0
let tot = eq += total


$('#ct1').text(tot.toFixed(2)).val()
$('#todds').val(tot.toFixed(2)).val()


var z = 0
var x = parseFloat($('#ct1').text()?? 0);
var y = parseFloat($('#stake').val()?? 0);
var net = z + x * y
$("#payout").text(net.toFixed(2)).val();
$("#inp").val(net.toFixed(2)).val();

}
})


</script>

</body>

Answer №2

It seems that the main issue stemmed from trying to remove the existing appended cart div. In my attempt to resolve this, I made some changes in the hopes of fixing the problem. However, it might be more effective to simply update the values directly within the code to avoid any flickering issues.

let $th = $('#Table1 thead th');

$('.decimals').click(function(e) { 

let $btn = $(e.target);
  let $option = $(`.box[data-id="${$btn.prop('id')}"]`);
  
  let $tr = $btn.closest('tr');
  let selectionIndex = $btn.closest('td').index();
  
  let kickoff = $tr.find('td:last').text().trim();
  let match = $tr.find('td:first').text().trim();
  
  let result = $th.eq(selectionIndex).text().trim();
  let value = $btn.val();

var knowit = $(this).closest('.items').find('.addItem').text();

var radiovalue = $(this).attr('value');


if ($('.boxlit .box:contains("'+knowit+'")').length < 1) {

setTimeout ( function () { 
  $("#box").append(`<div class="box" data-id="${$btn.prop('id')}">${match}<br><span>${result}</span><div class="crtTotal">${value}</div><input type="hidden" name="kickoff[]" value="${kickoff}"/><input type="hidden" name="match[]" value="${match}"/><input type="hidden" name="result[]" value="${result}" readonly/><input type="hidden" name="value[]" value="${value}"/></div>`); },0) }

else if ($(this).hasClass('active')) {
$('.boxlit .box:contains("'+knowit+'")').remove()
}


else {
$('.boxlit .box:contains("'+knowit+'") .crtTotal').text(radiovalue);

$('.boxlit .box:contains("'+knowit+'") span').text(result);
}

})
.decimals {
    background-color: rgb(31, 31, 31);
    color: rgb(255, 255, 255);
    border: 2px solid #0e1516;
    border-radius: 4px;
    font-size: 13px;
    padding: 4px 10px;
    font-weight: bold;
    border-width: 1px;
    cursor: pointer;
}

.decimals:hover {
     background: rgb(51, 51, 51);
}

.active,
.active:hover {

    background: rgb(161, 0, 0);
    color: rgb(255, 255, 255);
    border-color: rgb(156, 0, 0);
    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body style ="margin:10px;">


  <div class="cart">
  
    <div id="box" class="boxlit"></div><br>
  
  </div>


  <table id="Table1" class="Fixtures-Table">


    <thead class="disnon">
      <tr>   
          <th>League</th>
          <th>Home [1]</th>
          <th>Draw [x]</th>
          <th>Away [2]</th>
          <th>Kickoff</th>
      </tr>
  </thead>


  <tr class="items" style="display: table-row;">
            
    <td class="addItem">Almagro-Temperley</td> 
    <td id="bbox"><input type="button" class="decimals" id="3" value="1.95" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="4" value="2.95" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="5" value="3.90" data-selected="false"></td>
    <td id="date">8/1/2022 8:00:00 PM</td> 
    
  </tr>

  <tr class="items" style="display: table-row;">
              
    <td class="addItem">Guillermo Brown-Santamarina</td> 
    <td id="bbox"><input type="button" class="decimals" id="6" value="1.65" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="7" value="3.25" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="8" value="5.10" data-selected="false"></td>
    <td id="date">8/1/2022 8:00:00 PM</td> 
    
  </tr>

  <tr class="items" style="display: table-row;">
              
    <td class="addItem">Nueva Chicago-CSD Flandria</td> 
    <td id="bbox"><input type="button" class="decimals" id="9" value="2.25" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="10" value="2.85" data-selected="false"></td>
    <td id="bbox"><input type="button" class="decimals" id="11" value="3.15" data-selected="false"></td>
    <td id="date">8/1/2022 8:00:00 PM</td> 
    
  </tr>

</table>


<script>

$(document).ready(function(){

$('.decimals').click(function() { 

if ($(this).attr('data-selected') === 'true') {

$(this).attr('data-selected', 'false');

$(this).removeClass('active');

} else {

$(this).closest('tr').find('.decimals').not(this)

.removeClass('active').attr('data-selected', 'false');

$(this).attr('data-selected', 'true');

$(this).addClass('active');

}

});
});

</script>



</body>

Answer №3

After much thought, I decided to enhance the shopping cart by incorporating a feature that computes total odds and payout using the reduce method. However, I encountered a minor issue with the calculation process when adding the first selection. It seems like the total is only calculated after the second button click. Each subsequent button click triggers the calculation to start from the second click onwards, giving the impression of taking one step back when appending additional selections.

Below is the code snippet for the shopping cart:

<div id="box" class="boxlit"></div><br>
  <div class="shift">
    <div>Total Odds: <b id="ct1">0.00</b></div><br>
    <div>(N$)Stake: <input id="stake" type ="number" name="stake[]" value="5"> NAD</div><br>
    <div>Payout: N$ <b id="payout">0.00</b></div>
    <input class="bet1" type="submit" name="submit" value="Bet">
</div>

This section contains the code responsible for calculating the total odds and payout of multiple selections:

<script>
  $(document).ready(function() {
    $('.decimals').click(function(e) { 
      let values = $('.crtTotal').map((i, el) => 
        parseFloat(el.textContent)).get();

      let total = values.reduce((a, b) => a * b, values.length > 0 ? 1 : 0);
      let eq = 0
      let tot = eq += total

      $('#ct1').text(tot.toFixed(2)).val()
      $('#todds').val(tot.toFixed(2)).val()


      var z = 0
      var x = parseFloat($('#ct1').text()?? 0);
      var y = parseFloat($('#stake').val()?? 0);
      var net = z + x * y
      $("#payout").text(net.toFixed(2)).val();
      $("#inp").val(net.toFixed(2)).val();
    })
  })
</script>

I attempted to identify the source of the problem and it appears to be within the setTimeout segment:

setTimeout(function() { 
  $("#box").append(`<div class="box" data-id="${$btn.prop('id')}">${match}<br><span>${result}</span><div class="crtTotal">${value}</div></div>`);
},0)

The above code fragment appends values to the cart. How can I adjust my code to ensure the calculation starts from the first button click?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Editing HTML using the retrieved jQuery html() content

I need to modify some HTML that is stored in a variable. For example: var testhtml = $('.agenda-rename').html(); console.log($('input',testhtml).attr('name')); I also tried the following: console.log($(testhtml).find(' ...

Using React for Right-to-Left (RTL) Support

How can RTL (Right-to-Left) support be effectively implemented in React applications? Is there a method to customize default <p> and <span> components for RTL support without the need to rewrite existing components? For instance, using a global ...

What is the best way to customize bootstrap styles?

Currently, I am attempting to modify basic CSS attributes within the default theme that is included with a new ASP.NET MVC 5 application in Visual Studio 2013. Specifically, my goal is to change the background color of the navigation menu. With the help o ...

Callback function not being triggered in Jquery's getJson method

I am currently faced with a javascript conundrum. Below is the snippet of code that I have been working on: $.get("categories/json_get_cities/" + stateId, function(result) { //code here }, 'json' ); ...

I am frustrated because the csvtojson converter keeps replacing my file name with "undefined."

Despite running the csvtojson module on node.js successfully without any additional code, I encounter an issue when attempting to include it within a function. The result returns as undefined, even though the file path remains intact. Check out the JavaSc ...

Unable to get Angular ng-click to function properly when used in conjunction with $

I am encountering an issue with triggering a click event in my Angular app using code similar to the example below. Can anyone help me understand why the event is not being triggered? var app = angular.module("myApp", []) app.directive('myTop', ...

What steps do I need to follow to upload an image file through Socket.IO?

For my school project, I am developing a chat application and facing a challenge with implementing an onClick event to trigger a function that utilizes socket-io-file-upload to prompt the user to select a file for upload. This functionality is detailed in ...

The background image does not have the body padding applied

When creating a fixed top nav bar, I added padding to the body tag so that the nav bar always stays on top like this: body { padding-top: 70px; } Now, I want to set a background image for the body that covers the entire screen, so I added the foll ...

Guidelines for placing an HTML element in relation to another HTML element using CSS or JavaScript

Is there a way to position an HTML element in relation to another using CSS or JavaScript? I have attempted to copy the inner HTML of the "second-element" and append it inside the "first-element", but this approach is causing issues with other functional ...

Vue Js: Creating an array of checkboxes

I have a collection of checkboxes sourced from the main system object where I store all system settings (referred to as getSystem{}). Within this form, I am retrieving information about a User, who possesses an array of roles []. How can I cross-reference ...

React - Error: you have a syntax problem because there is an unexpected token <

I am working on a project using Express, pg, and react. However, I have encountered some issues with React. Here is the directory of my project index.js var express = require('express'); var server = express(); var path = require('path&ap ...

The function Jquery.html() seems to be malfunctioning in IE7, however, innerHTML is working correctly in the

One of my recent implementations involves populating a div using an ajax response. Take a look at the code snippet below for better understanding: jQuery.ajax({ type: 'POST', url: url, dataType: 'json', data:data, s ...

OptinMonster's innovative feature - the Pardot form with an inline button

Having trouble integrating an HTML Pardot form into OptinMonster's floating footer option. I'm looking to align all three fields inline, along with the button. Can anyone assist me in placing the button inline with the fields? HTML: <fo ...

Storing intricate items in a JavaScript database can be tricky. Using JSON.stringify() can sometimes lead to unexpected errors

In my project, I have a class called Player and a list of players named gameData. My goal is to save and retrieve this gameData from a database so that user information remains intact even after the bot restarts or crashes. However, when attempting to use ...

"Discovering the data-id of an active class is essential - here

<ul class="deal-menu"> <li class="active" data-id="today-spl"><a href="#" class="first">Special<span class="active"></span></a></li> <li class="" data-id="today-deal"><a href="#">Deal</a>< ...

The PHP content form is malfunctioning and not processing email submissions properly, resulting in the PHP code being

Following a tutorial, I attempted to create a basic contact form using PHP. As a beginner in PHP, I found the process fairly straightforward, but encountered some bugs in the code. Upon integrating the code on my website, clicking the submit button redirec ...

How come my jQuery validation needs two clicks to activate?

I am experiencing an issue with a comments form that has 2 fields: Author and Message. Upon clicking the submit button, the validation does not trigger initially. However, if I click the submit button again, then the validation works as expected. Any tho ...

Tips for including a footer element in React:How can a footer division be

I need help with implementing a footer in my React web app. Currently, the body section in index.html looks like this: <body> <div id="root"></div> <script src="index.js"></script> </body> Inside index.js, the rend ...

The error was thrown at line 800 in the loader.js file of the internal modules

When I ran yarn install in my project folder, I encountered the following error: internal/modules/cjs/loader.js:800 throw err; ^ Error: Cannot find module 'ts-node/register' Require stack: - internal/preload ?[90m at Function.Module._resolveF ...

State update failing to modify arrays

Shown below is an array that contains boolean values: const [state, setState] = React.useState({ [`${"checkedA"+index}`]: false, [`${"checkedB"+index}`]: false, [`${"checkedC"+index}`]: false, [`${"checkedD"+index}`]: false, }); ...