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

Mobile viewing causing problems with website buttons functionality

While my website functions perfectly on desktop, I am facing an issue where the buttons are not working when accessed through mobile devices. Interestingly, these buttons were operating fine in a previous version of the site. Although I have made minimal ...

Discover Vue3's efficient event handling feature that allows you to easily listen to events from dynamically generated child components

I am dynamically creating a Vue component and need to listen to the event it emits. While I know that you can use @eventName in the markup, my component is being created using createApp. const div = document.createElement('div'); this.$refs.logi ...

Looking to retrieve the raw HTTP header string in Node.js using express.js?

Currently, I am utilizing Node.js and express.js for my work. The project I am currently working on requires me to access the raw strings of the HTTP headers (charset and accepted). In express.js, there is a function available that can provide the charset ...

What methods can I use to customize the appearance of the acceptance label in a contact form created with

I am currently developing a WordPress website using the Contact Form 7 plugin. However, I am facing an issue with styling the "I accept" button and text when clicking on the "registrace" button. I would like to center them and create some proper margin aro ...

Disable the ability to click on the indicators in the Bootstrap carousel

Seeking assistance with customizing tweeters bootstrap Carousel functionality. I have removed the controls and now want to switch slides according to my own logic while displaying slide indicators. How can this be achieved? Preferably seeking a solution ...

What is the most effective method for altering HTML form components using PHP?

Can you explain how to manipulate and add form elements using PHP? Let's say I have a form stored in a PHP variable like this: $originalForm = ' <form method="post" action="whatever.php"> <input type="text" name="iamtextfield" id="text ...

The scrollOverflow feature in fullPage.js is not properly detecting the height of dynamically generated content

I have successfully implemented fullpage.js on my website. Everything is working perfectly with fullpage.js, but I am facing an issue when trying to open a div on click of pagination. Specifically, the browser scroll gets disabled when the div containing a ...

`Get the height of a specific element within a FlatList using the index property in React Native`

I'm currently exploring a workaround for the initialScrollIndex issue in FlatList that is not functioning correctly. I attempted to use getItemLayout to address this, but encountered a new problem - my elements inside the FlatList have varying heights ...

Using Google Chart API to create stacked bar charts with annotations using symbols

I am trying to annotate the bars in my stacked bar chart with currency symbols for profit and costs. While I have been able to successfully annotate the bars without currency symbols, I am facing difficulties in displaying them with the $ prefix. Can anyo ...

Passing a parameter to an AngularJS directive, which triggers the opening of an ngDialog, and subsequently updating the value to reflect changes in the root scope

Struggling with a persistent issue here; Essentially, I have a directive that triggers an ngDialog to open. This directive should be able to receive a variable from the root scope. The directive contains a click event that opens an ngDialog which then use ...

What is the best way to retrieve the outcome of a node-sqlite3 query beyond the scope of db.get()?

I'm attempting to validate whether the sha256 hash stored in my sqlite database corresponds with the sha256 hash of the password that the user transmitted to my NodeJS server. The Auth() method is meant to deliver either a true or false result. Is the ...

"Embracing Progressive Enhancement through Node/Express routing and the innovative HIJAX Pattern. Exciting

There may be mixed reactions to this question, but I am curious about the compatibility of using progressive enhancement, specifically the HIJAX pattern (AJAX applied with P.E.), alongside Node routing middleware like Express. Is it feasible to incorporate ...

Tracking User Visits in Codeigniter

Below is the code breakdown: (Step by step) Place counter.txt in APPPATH . 'logs/counter.txt' Set up counter_helper.php in APPPATH . 'helpers/counter_helper.php'; Autoload the newly created helper in APPPATH . 'config/autoload.p ...

The prefixes for Ruby on Rails routes are not properly preprocessed in the .erb.js file

I'm currently working with Rails 4 and encountering an issue with the following file: // apps/assets/javascripts/products.js.erb var getColoursAndMaterialsData = function(onSuccess) { var fd = formdata(); $.post( '<%= data_products_ ...

Establishing a user session with Node.js

I am new to the world of node.js and JavaScript in general. I have a piece of code that currently handles login functionality by checking if a user exists in a MYSQL database. This part is functioning correctly. Now, I wish to improve this feature by crea ...

Encountering an Issue when Updating Rails Model with JSON Data

Having trouble updating a Rails model due to data handling errors despite successful ajax request. The sent parameters are: Parameters: {"{\"slot_allocation\":{\"timeslot_id\":\"3\",\"subject_id\":\"3\",& ...

Submit data in the manner of a curl request

Instead of using a curl command to push a file to a web server, I am attempting to create a simple webpage where I can select the file and submit it. Here is the HTML and JavaScript code I have written for this purpose: <html> <body> <i ...

What could be causing React onclick events to not trigger when wrapped within a Vue application? (No additional libraries)

As I dive into the world of combining React and Vue components, I encountered an interesting challenge... const RootTemplate = () => { return ( <div id="vue-app"> ... <IconButton color="inherit" onClick={thi ...

Converting strings into the right values through parsing

I have a JSON response that contains multiple suggestions, but I only want to parse and extract the 4 "collation" results: jQuery191029421305245357143_1380819227858( { "responseHeader": { "status": 0, "QTime": 127 }, "command": ...

Integrating Express into a React Webpack project

I am currently in the process of integrating express into my React project to establish connections with databases for storing form data. As of now, I am using webpack to create a dev server that displays my React view. My technology stack includes... Web ...