Determining the active status of a class using oTree and JavaScript

Upon running the following code:

    <div id="1-round" class="btn-group btn-group-toggle btn-lg" data-toggle="buttons" >
{% for checkbox in form.players_choice %}
    <label class="btn btn-primary rounded mr-3 active btn-lg 1-round" style="margin-bottom:8px;">
        <script>
           $('label').click(function() {
          $(this).addClass('btn-primary').removeClass('btn-default').siblings().removeClass('btn-primary').addClass('btn-default');
         if ($('#id_players_choice_0').is(':checked')) {
         x = id_players_choice_0.value};
         if ($('#id_players_choice_1').is(':checked')) {
         x = id_players_choice_1.value};
          alert(x);
         });
        </script>
        {{checkbox}}
    </label>
{% endfor %}
</div>

Upon use, the value (the x variable) is only retrieved on the second or third button press.
Is there a solution for this issue?
Thank you!

Answer №1

Utilize the $('label') selector to target labels that are already present in the document. Avoid placing the click handler inside a loop, as this can result in multiple instances of the same handler on various elements. Instead, consider moving the script to the end of the document, just before the closing </body> tag.

Ensure to properly declare the variable x to maintain appropriate scope.

<div id="1-round" class="btn-group btn-group-toggle btn-lg" data-toggle="buttons">
{% for checkbox in form.players_choice %}
    <label class="btn btn-primary rounded mr-3 active btn-lg 1-round" style="margin-bottom:8px;">
        {{checkbox}}
    </label>
{% endfor %}
</div>
<script>
    $('label').click( function() {
        var x;
        $(this).addClass('btn-primary').removeClass('btn-default')
               .siblings().removeClass('btn-primary').addClass('btn-default');
        if ($('#id_players_choice_0').is(':checked')) {
            x = id_players_choice_0.value;
        }
        if ($('#id_players_choice_1').is(':checked')) {
            x = id_players_choice_1.value;
        }
        alert(x);
    });
</script>

If there is uncertainty about the labels being created before the script execution, utilize event delegation:

$(document).on('click', 'label', function() { // ...etc

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

Is there a way to confirm whether or not two files are identical?

Is there a reliable method to determine if two files are identical? I've been using a solution that involves downloading the first part of each file, converting the data to base64, and then comparing them. However, I've encountered an issue wher ...

What is the most efficient way to find the maximum, minimum, and median values in an array?

[ 0: {"carrier": "Spicejet", "value": 2596}, 1: {"carrier": "Spicejet", "value": NaN}, 2: {"carrier": "Spicejet", "value": 2864}, 3: {"carrier": "Indig ...

What could be the reason for my React/HTML select element occasionally failing to display the default selected value?

I am currently working on creating a select element in Reactjs/HTML and I am facing an issue with setting a default value based on a component variable. Essentially, the default value of the select should be the id of a component. This is my current imple ...

Is there a way to customize a package.json file using postinstall?

I've developed a package on npm that generates an "scss directory structure" and my goal is to include custom scripts in the package.json file located at the project's root. MY-PROJECT ├── node_modules ├── scss └── package.json ...

When attempting to use dynamic imports with `react-icons`, NextJS will import all necessary components and dependencies

My current task involves incorporating an Icon from the react-icons package into my project. However, when I attempt to do so using an import statement, the resulting bundle size looks like this: Route (pages) Size First Lo ...

Whenever I declare it, the onclick method is executed

I have been attempting to define an onclick method that would trigger a function to clear and reconstruct the display, revealing more detailed information about the clicked item. However, I am facing an issue where the assigned onclick method is executed i ...

$set { "array.variable.value" :"newvalue"} utilize a different term besides "variable" or implement a new variable

When working with mongoose to store user data, one of the attributes is an array called items. In my additems.js file: const User = require('../models/User'); var array = user.items; array.indexOfObject = function (property, value) { ...

What is the process for dynamically incorporating JavaScript files during compilation to serve as input for browserify?

Within our project's structure, there exists a directory housing multiple js files. The possibility of adding or removing these files later on is present. Currently, we have a file named main.js where each file is imported and a map is created (using ...

Wait until all information has been entered into the database before replying to the request

I have been exploring a way to insert multiple data in one call and only trigger a response after all the data has been inserted. Here is my current implementation: create: function(req, res) { var response = {}; var num = req.body.num; var re ...

Tips for displaying the overlay in a jQuery UI modal dialog

The demonstration shows that the overlay is displayed correctly and all elements below it are disabled: <div class="ui-widget-overlay" style="width: 1920px; height: 650px; z-index: 1001;"></div> However, on my webpage, I am still able to inte ...

Retrieve the `access_token` attribute from local storage

I have stored the token in local storage using: localStorage.setItem('token', JSON.stringify(res.data)). Now, I am attempting to retrieve the access_token property. JSON.parse(localStorage.getItem(token['access_token'])) An error is o ...

Increase the identifier of my input text when a table row is duplicated through Javascript

I have a table with only one row that contains various elements like textboxes and buttons. I want to clone the table row using the append() function when a button is clicked. However, I am facing an issue - how can I increment the id of the textboxes and ...

Using Node.js and Typescript to implement a chain of logical AND operations with an array of any length

Setting: I am developing a versatile function that determines a boolean outcome based on logical AND operations. However, the function is designed to handle various types of objects and arrays, each requiring different conditions. Currently, my code look ...

show an HTML webpage within a <div> container using AJAX technology

I am trying to include an HTML page named Introduction.html (located in the same folder as x.html) within div1. However, it does not seem to be loading properly. Below is a snippet of the code from x.html x.html <!DOCTYPE html> <h ...

Unable to access placeholder information from the controller

I am new to implementing the mean stack. I attempted to view data from the controller, but encountered an error message in the web browser's console. Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.3/$controller/ctrlreg?p0=AppCtrl Stack ...

Generating a JSON tree hierarchy from an array of nested objects

I have a JSON array of objects that looks like this: [{ "vehicleid": 3, "name": "Teste2VDD", "brand": "Scania", "model": "6x2", "class": "class1", "region": "Curitiba", "customer": "Cliente A", "customerid": 1 }, { "veh ...

Autocomplete feature is not functioning properly when trying to use JSON input

Currently, I am utilizing the MUI autocomplete component in my project. The situation involves making an API call and populating 'options' and 'value' with the response from the API. Below is the code snippet. // App.js import { useEff ...

Successfully submitting form_with without experiencing any errors for mandatory fields

I am currently dealing with a form that triggers a sidekiq worker upon submission. The issue I am facing is that even if the form is empty, clicking submit still attempts to run the worker. What I would like is for an alert to notify the user that the fiel ...

The proper way to insert data in JavaScript and PHP

Hello. I have a new function to add a row in my form. However, I recently added a second input field and I am unsure of how to correctly insert it. Below is my JavaScript code: <script type="text/javascript" src="jquery.js"></script> <scri ...

Adding jQuery SVG Sources to SVG Elements

Can the jQuery SVG source code be included in a standalone SVG document? Here is an example: <script type="application/javascript"> <![CDATA[ // jQuery SVG code ]]> </script> I want the SVG document to be self-contained, ...