undefined value when accessing an element by its name

In the following function I try to validate that an appropriate select value is chosen by a user. The alert popup box displays 'undefined' when I run the script. I need to get the element using its name rather than ID.

Sort table in =
<select name="SortIn">
<option value="Please Choose">Please Choose</option>
<option value="asc">Ascending order</option>
<option value="desc">Descending order</option>
</select>

<input type="submit" name="submit" value="Submit" onclick="return validateForm()"/>
</form>

<script type="text/javascript">
/* <![CDATA [ */

function validateForm()
{
    //Validates that form elements are not empty
            var test = document.getElementsByName('SortIn').value;
    alert(test1);
    if(test1 == null || test == "")
    {
        alert("Please select sorting order");
        return false;
    }
    else
        {
            return true;
        }
}

/* ]]> */
</script>

Answers


document.getElementsByName('SortIn') returns a nodelist. You need to get the first element of that nodelist like so:

var test = document.getElementsByName('SortIn')[0].value;

You need to refer to the element like this:

var test1 = document.getElementsByName('SortIn')[0].value;
                                                 ^

jsFiddle example

getElementsByName returns an array-like collection of elements, so you need to specify the index of the one you want.


Need Your Help

JqueryUI Slider, slide div with increments

jquery-ui uislider

i want to use the jqueryUI slider (slide to increments) and have it slider a div for it.

Camera is being rotated 90 degree in air for android

android actionscript-3 air camera rotation

In my AS3 Flex Mobile application for Android, I am using camera and it is being automatically rotated 90 degrees before I even done any video rotation by myself, it seems like it's a known bug in ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.