0

I am currently working on a form which has to process a data filled in a by a client. It has a few radio groups and I'd like to get the value of it when it's changed.

<input type="radio" name="domain" value="no">
<input type="radio" name="domain" value="yes">

<input type="radio" name="hosting" value="no">
<input type="radio" name="hosting" value="yes">

I found a function like it somewhere, but it does not work the way I want.

    function getSelectedValueFor(name) {
        alert(document.getElementsByTagName(name).length);
        for (var i = 0; i <
            document.getElementsByTagName(name).length; i++) {
            var input = document.getElementsByTagName(name)[i];
                if (input.type == "radio" && input.checked) {
                    return input.value;
                }
        }
        return null;
}

It basically should work like this, and work for "getSelectedValueFor()" should be reusable:

$('input[name="hosting"]').change(function(){
    var x = getSelectedValueFor("hosting");
    console.log(x + " test");
    if(x == "yes") { $('#hosting').slideDown(); }
    else if(x == "yes") { $('#hosting').slideUp(); }
    return;
});

Is there anyone who can help me out? All help is appreciated.

2
  • Can you use JQuery? Less lins of code and more browser compatiblity. - I can write you directly an example for that. Commented Jan 7, 2014 at 10:26
  • Use can not give hosting as a parameter in getElementsByTagName. It can be input and this is the reason your code is not working. Commented Jan 7, 2014 at 10:33

1 Answer 1

3

You can simply get selected value by using this line

var x = $('input[name="hosting"]:checked').val()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is what I was looking for. Actually easier than expected though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.