jQuery - Getting Values from Controls

Radio Buttons

Radio Buttons can share the same name.

Option 1

No Filter Male Female


Option 2

This is A This is B

Option 3
This example uses a wrapper div and targets all the input types of radio within the wrapper. This example does not need the name of the 'group' (name attribute).

This is A This is B

    // option 1
    $("input[name='genderOptions']").change(function ()
    {
        let selectedGender = $('input[name=genderOptions]:checked').val();
        $("#radio-selected").html(selectedGender);
    });

    // option 2
    $("input[name='group1']").change(function ()
    {
        alert("group 1 was checked");
        alert("the value selected was: " + $(this).val());
    });

    // option 3
    $('#group3Wrapper input:radio').click(function ()
    {
        if ($(this).val() === 'A')
        {
            alert("group 3 was checked");
            alert("the value selected was: " + $(this).val());
        }
        else if ($(this).val() === 'B')
        {
            alert("group 3 was checked");
            alert("the value selected was: " + $(this).val());
        }
    });

 

Text Boxes


    var name = $("#txtName").val();
    $("#name-provided").html(name);

 

Drop Downs


$("#Fruit").change( function()
{
    let ddlValue = $('#Fruit option:selected').val();
    let ddlText = $('#Fruit option:selected').text();
    $("#drop-down-selected").html(`Value: ${ddlValue}, Text: ${ddlText}`);
});

 

Checkboxes

January February March ...etc...


// checkboxes
// there is definitely better ways to do this...this just "works".
$("#chkJanuary").change(function ()
{
    GetSelectedMonths();
});

$("#chkFebruary").change(function ()
{
    GetSelectedMonths();
});

$("#chkMarch").change(function ()
{
    GetSelectedMonths();
});

function GetSelectedMonths()
{
    var x = 0;
    var html = "";
    let selectedMonths = [];

    if ($("#chkJanuary").is(':checked'))
    {
        selectedMonths.push("January");
    }

    if ($("#chkFebruary").is(':checked'))
    {
        selectedMonths.push("February");
    }

    if ($("#chkMarch").is(':checked'))
    {
        selectedMonths.push("March");
    }

    do
    {
        html += selectedMonths[x] + "<br />";
        x++;
    }
    while (x < selectedMonths.length);

    console.log(selectedMonths);

    $("#checkboxes-selected").html(html);
}