Wednesday, April 6, 2011

How to get value of textboxes, textareas, and radios in the same way in Javascript?

I want a function/code which will return the value that the user submitted for the field whose name/id is passed on to it. It shouldn't matter whether the field is a textbox, textarea, radio, or select. For example, the field could be:

<input type='radio' name='a_21' value='test' id='a_21_0' />
<input type='radio' name='a_21' value='test2' id='a_21_1' />

Or

<textarea name="a_21" rows="30" cols="6"></textarea>

When I do the call:

function getVal('a_21');

It should return the selected value.

How can I do this? Will:

document.myForm.field.value

work for textareas, dropdowns and radios, too?

From stackoverflow
  • The problem is different widgets have different purposes. For example, a <select> box with multiple selection available, multiple checkboxes, or even single checkboxes (whose value would be just "on" or "off") wouldn't have a single value, so it's ok for them to behave differently from other widgets.

    But if you want to have a single function, you could do something like:

    function getVal(obj){
      if(obj.value){
        return obj.value;
      }
    
      if(obj.selectedIndex){
        return obj.options[obj.selectedIndex];
      }
    
      if(obj.checked){
        return obj.checked;
      }
    
     return null;
    }
    
  • Using jQuery you can do:

    $('[name="a_21"]').val();
    

    This will give you the value on of the field with name a_21, so matter what the type of field.

    Note: The quotes are not needed, but I've gotten in the the practice of adding them because of checkbox arrays:

    <input type="checkbox" name="ids[]" value="1" />
    <input type="checkbox" name="ids[]" value="2" />
    

    I figure it's better to be safe than trying to figure out why it doesn't work.

    Click Upvote : Does 'a_21' need to be in double quotes?
    geowa4 : usually i would downvote a 'use jQuery' answer but this is where it really shines
    geowa4 : @Click Upvote, @Seb: it does not need to be in quotes at all.
    elcuco : "Have you tried JavaScript?" LOL

0 comments:

Post a Comment