ZioTonio
ZioTonio

Reputation: 79

Get the value from an element targeted by its name

Let me try to explain my problem. I have a radio button "jform[display]" which allow to display a hidden div "greenRect". With the following code, it does not work.

$("input[name='jform[display]']").on('click', function() {
    if ($("input[name='jform[display]']").val() == 1) {
        greenRect.show();
        alert("Value of the Radio Button="+$("input[name='jform[display]']").val());
        return;
    }
    greenRect.hide();

    //It does not work (always=1)!!!
    alert("Value of the Radio Button="+$("input[name='jform[display]']").val());
});

The elements $("input[name='jform[display]']").val() is always == 1

If I modify $("input[name='jform[display]']").val() to $(this).val(), it works!

$("input[name='jform[display]']").on('click', function() {
    if ($(this).val() == 1) {
        greenRect.show();
        alert("Value of the Radio Button="+$(this).val());
        return;
    }
    greenRect.hide();

    alert("Value of the Radio Button="+$(this).val());
});

Why does it work with the option2 and not with the option1. I thought that both were similar. Here is the code with JSFIDDLE : http://jsfiddle.net/4zmqzecs/2/

Thank you very much for your help

PS: The names of my elements are generated by an API:

name=jform[display]
id=jform_test0
id=jform_test1

They sound strange but it's difficult to modify. Anyway it souldn't be the origin of the problem.

Upvotes: 0

Views: 54

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82231

You should rather get the value for checked radio button using :checked selector:

$("input[name='jform[display]']:checked").val()

Working Demo

Upvotes: 1

Related Questions