1

I have a set of radiobuttons called 'price'. When the '€' radio button is selected, I want to focus on a text input field and that text input field should be required. When I click another option, the requried attribute should be removed.

Is this possible through Javascript or jQuery? I found a jQuery snippet here, but it doesn't seem to be working. This is what I have now:

<input type="radio" name="price" value="value" id="value_radio" onclick="document.getElementById('value_input').focus()" required>

<label for="value_input">&euro;</label>
<input type="text" name="price_value" id="value_input" pattern="\d+(,\d{1,2})?" 
    onclick="document.getElementById('value_radio').checked=true">

<script>
    $('#value_radio').change(function () {
        if($(this).is(':checked')) {
            $('#value_input').attr('required');
        } else {
            $('#value_input').removeAttr('required');
        }
    });
</script>

<input type="radio" name="price" id="free" value="free">
<label for="free">Free</label>

JSFiddle: http://jsfiddle.net/fhfrzn1d/

Wouter C
  • 533
  • 1
  • 6
  • 21

2 Answers2

6

According to this answer, you have to monitor the change on both radio inputs. So move your javascript script after the second radio.

Also there was missing a )

Fiddle updated: http://jsfiddle.net/fhfrzn1d/1/

$('input[name="price"]').change(function () {
    if($("#value_radio").is(':checked')) {
        $('#value_input').attr('required', true);
    } else {
        $('#value_input').removeAttr('required');
    }
});
Community
  • 1
  • 1
Volune
  • 4,324
  • 22
  • 23
  • also you need to change the click of your #value_input element to be something like `document.getElementById('value_radio').click();` to properly trigger the change handler. – James Aug 16 '14 at 12:51
2

You have two (really three) mistakes in your code.

First. The syntax is invalid. You should fix the closing brace as @Hushme recommends in the comments.

First (2). Your usage of jsfiddle is invalid too. You should paste the code to the JavaScript section of the site and also enable jQuery library.

Second. $('#value_input').attr('required') is not creating an attribute; it's a getter. You should use the proper setter there:

$('#value_input').attr('required', true);

Third. The radiobutton change event is not firing when user deselects the radiobutton. So you should handle events on all the buttons:

$('input[name="price"]').change(function () { ... });

I've fixed your jsfiddle, see http://jsfiddle.net/fhfrzn1d/4/

ForNeVeR
  • 6,726
  • 5
  • 24
  • 43