Switching the select box value using jQuery based on the radio button selection (or vice versa)

I have developed a platform where users can make predictions about the outcome of sports matches

For a visual representation, take a look at the image below:

The teams that are selected will be showcased at the bottom of the page along with their respective scores (as seen in the bottom circle of the image)

My Objective

  1. In the first circle, when the selected score is 0, I want the radio button to automatically switch to "draw"

  2. In the second circle, if the user chooses draw by 12 points, I would like the select box value to default to zero or display an appropriate message

The Issue I'm Facing

The script I've implemented below displays the chosen team and score inside a div at the bottom of the page

I have managed to resolve the aforementioned problem, but doing so has impacted the primary functionality of my script mentioned above

Any suggestions on how to tackle this issue without affecting the main operation of my script as described before?

Please test out my code snippet to understand the situation better

Code Snippet:

$(document).ready(function () {
$(':radio, select').change(function (e) {
    //clear the div
    $('#dispPicks').html('');
    //update the div
    $(':radio:checked').each(function (ind, ele) {
        var selectBoxVal = $(this).closest('div.team').find('select').val();
        selectBoxVal = selectBoxVal!=''? "By "+selectBoxVal:selectBoxVal;
        $('#dispPicks').append($(ele).val() +"  "+selectBoxVal+ '<br/>');
    });
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="team">
<input type="radio" name="foo" value="Shaks" />
<input type="radio" name="foo" value="Hurricanes" />
<input type="radio" name="foo" value="Draw" />

<select>
        <option value="">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
</select>

<br/>
</div>
<div class="team">
<input type="radio" name="bar" value="Crusaders" />
<input type="radio" name="bar" value="Pioneers" />
<input type="radio" name="bar" value="Draw" />
<select>
        <option value="">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
</select>

<br/>
</div>
<div class="team">
<input type="radio" name="wow" value="Chelsea" />
<input type="radio" name="wow" value="Liverpool" />
<input type="radio" name="wow" value="Draw" />
<select>
        <option value="">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
</select>
</div>
<div id="dispPicks"></div>

Answer №1

Here is the solution I implemented:

$(document).ready(function () {
    $(':radio').change(function (e) {
        //clear the div
        $('#dispPicks').html('');
        //update the div

        if ($(this).val() == "Draw") {
            $(this).siblings("select").val('0');
        }

        $(':radio:checked').each(function (ind, ele) {
            var selectBoxVal = $(this).closest('div.team').find('select').val();
            selectBoxVal = selectBoxVal != '' ? "By " + selectBoxVal : selectBoxVal;
            $('#dispPicks').append($(ele).val() + "  " + selectBoxVal + '<br/>');
        });
    });

    $("select").change(function () {
        //clear the div
        $('#dispPicks').html('');
        //update the div
        if ($(this).val() == '') {
            if ($(this).siblings("input[type='radio']:checked").val() != "Draw") {
                $(this).siblings("input[type='radio']").last().prop('checked', true);
            }
        }
        if($(':radio:checked').val()=="Draw"){
            $(this).val('0');
        }
        $(':radio:checked').each(function (ind, ele) {
            var selectBoxVal = $(this).closest('div.team').find('select').val();
            selectBoxVal = selectBoxVal != '' ? "By " + selectBoxVal : selectBoxVal;
            $('#dispPicks').append($(ele).val() + "  " + selectBoxVal + '<br/>');
        });
    });


});

Check out the JSFiddle demo

Answer №2

It appears that the following example meets your requirements.

$(document).ready(function () {

//Track changes in team/draw selection
$(':radio').change(function (e) {
var selectBox = $(this).siblings("select");
if($(this).val() == "Draw" && selectBox.val() !== ''){
selectBox.val('');
}
updateDiv();
});

//Track changes in select dropdown
$('select').change(function (e) {

var theRadios = $(this).siblings(":radio");

//Check for draw condition
if($(this).val() == '' ){
//Change team/draw radios to draw
theRadios.filter(':input[value="Draw"]').prop('checked', true);

//If select indicates it is not a draw, clear draw status
}else if(theRadios.filter(':checked').val() == "Draw"){
theRadios.prop('checked', false);
}
updateDiv(); 
});
});

/*
* Update the div HTML content
*/
function updateDiv(){
//Clear the div
$('#dispPicks').html('');
//Update the div with selected values
$(':radio:checked').each(function (ind, ele) {
var selectBoxVal = $(this).closest('div.team').find('select').val();
selectBoxVal = selectBoxVal!=''? "By "+selectBoxVal:selectBoxVal;
$('#dispPicks').append($(ele).val() +"  "+selectBoxVal+ '<br/>');
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="team">
<input type="radio" name="foo" value="Shaks" />
<input type="radio" name="foo" value="Hurricanes" />
<input type="radio" name="foo" value="Draw" />

<select>
        <option value="">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
</select>

<br/>
</div>
<div class="team">
<input type="radio" name="bar" value="Crusaders" />
<input type="radio" name="bar" value="Pioneers" />
<input type="radio" name="bar" value="Draw" />
<select>
        <option value="">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
</select>

<br/>
</div>
<div class="team">
<input type="radio" name="wow" value="Chelsea" />
<input type="radio" name="wow" value="Liverpool" />
<input type="radio" name="wow" value="Draw" />
<select>
        <option value="">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
</select>
</div>
<div id="dispPicks"></div>

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

What is the best way to send data from client-side JavaScript to node.js using XMLHttpRequest?

I have some HTML input fields in my index.html file. <input type="text" id="handle" > <input type="text" id="message" > <button id="send">send</button> After filling in the information and clicking "send", I want to pass this data ...

Tips for adjusting the size of a CSS radio button while ensuring the text remains centered

Uncertain about which part to modify in this radio button code to decrease its size while keeping the text aligned with the inner button. Changes made have shifted the text to the top of the button instead. Can you provide guidance on the necessary adjustm ...

Developing Table Structures with Java Script

Struggling with implementing Javascript to generate a table displaying an array? The task involves using an external JavaScript file to define the array and utilizing a for loop to populate the table. However, encountering a problem where nothing seems to ...

tips on adjusting the page results and maximum results for a dataTable

I have retrieved over 100 rows from MySQL, which is the default limit for displaying results in DataTables. I want to change the default limit of Datatables to display 30 rows on each page until all my fetched MySQL results are shown. When querying M ...

Ensure that the jQuery Knob is set to submit any modifications only after the final adjustment

Utilizing jQuery Knob by anthonyterrien, I have configured the step to be 20. My goal is to transmit the knob's value to the server. The issue arises when the change function is triggered every time the user adjusts the knob using either a right or le ...

Transform your CSV data into JSON using Node.js and store it within a variable for easy access

Currently, I have this code snippet as a starting point and my task is to utilize it in order to convert the content of "world_data.csv" into JSON format. I am unsure of how to store this JSON data in a variable. I suspect that the desired data is tempora ...

What is the best way to style an element within an array that uses special characters in its name within JSON format?

I am attempting to include a specific header in the request, but one of them contains special characters. Access-Control-Allow-Origin This header is necessary to ensure that the request can proceed without being blocked by CORS Code: const fetchData = as ...

What could be causing my getAsFile() method to return null?

Below is the code I have been working on: document.getElementById("Image_Panel").addEventListener('paste', (event) => { console.log("Initiating image paste - Step 1"); const clipboardData = event.clipboardData; // Checking ...

Exploring and retrieving JSON objects in multidimensional arrays

I'm facing a challenge with the code snippet provided below. var employees = [ { firstName: "John", lastName :"Doe", qualification: {Diploma: 'IT Software' , Degree: 'Software Engineering'} }, { firs ...

I'm interested in implementing a cooldown feature on my button, but I'm not quite sure how to go about

Working on a React.Js website and looking to improve the Contact Me page by adding a cooldown to the button. Unfortunately, I haven't shared all the code here but feel free to reach out on Discord: uvejs#5162 for more details. import "./contactpa ...

Menu Selector on the Right Side

I am currently working on a drop down menu and trying to align it to the right using HTML and CSS. Below is an example that I have been referencing: http://codepen.io/anon/pen/RNLmvq Attached here is a screenshot of how the menu appears without the text ...

What adjustments should I make for mobile cell phone browsing to enable the player to automatically jump upon tapping the screen?

How can I modify the code to make the player move automatically to the right and jump on tap in a mobile cell phone browser? I've been searching for an answer but haven't found one yet, as I'm still learning. Here is the updated code: updat ...

Using a boolean checkbox with Spring MVC and implementing ajax

On my HTML page, I have a boolean checkbox that looks like this: <input type="checkbox" id="pnrCheckbox" name="includesPnr" value="true"/> <!-- This field is generated by Spring as a workaround for something --> <input type="hidden" name="_ ...

Use script to reset the value of children

I attempted to reset the children of testId, but unfortunately, it did not successfully reset. <div id="testId"> <input type="text" /> <div> <input type="text" /> </div> <select> <o ...

What is the process for determining or managing the missing path attribute of a cookie in a Single Page Application?

According to RFC6265 In case the server does not specify the Path attribute, the user agent will utilize the "directory" of the request-uri's path component as the default value. While this concept primarily applies to the Set-Cookie prot ...

Guide on Testing the Fetch Functionality of useEffect Using Jest in React

Can someone assist me with testing my useEffect Fetch using Jest in React? I've been struggling to make it work and tried various solutions without success. This is my first time using Jest, and I'm currently integrating it into my project. Belo ...

What is the method for adding information to this object?

input: [{ email: 'sassa', password: 'sas' }] output: [{ email: 'sassa', password: 'sas' , valid: true }] I have a response coming from my Node.js server, and I need to add the 'v ...

What is the best way to remove an entire span element that contains contenteditable spans within it?

The issue I'm facing involves a contenteditable div. Inside, there is a span for a 'fraction', following guidance from this source. Below is my current code snippet: <span style="display:inline-block; vertical-align:middle;" contentedita ...

What strategies can I use to ensure that I can successfully send 3,000 requests to the Google Drive API using node.js without surpassing

I'm currently assisting a friend with a unique project he has in mind. He is looking to create 3000 folders on Google Drive, each paired with a QR code linking to its URL. The plan is to populate each folder with photos taken by event attendees, who ...

displaying the local path when a hyperlink to a different website is clicked

fetch(www.gnewsapi.com/news/someID).then(response => newsurl.href = JSON.stringify(data.articles[0].url) fetch('https://gnews.io/api/v3/search?q=platformer&token=642h462loljk').then(function (response) { return response.json(); }).th ...