how to check for existing element before loading variable

Posted on 2011-03-18
Last Modified: 2012-05-11
Attached code. This works, but there are circumstances where the "selectprogram" radio button may not exist on the page (or there could be many with that name). In that case, my function fails, I believe because this becomes invalid:

var inputVal = $("#mainform input[name='selectprogram']:checked").val();

If there is no element with the name "selectprogram" then I want to do this:


This is possible? Do I just need to add another conditional statement? Thank you!
function setprogram(displaycat,task){

	var inputVal = $("#mainform input[name='selectprogram']:checked").val();

	if (undefined==inputVal){
		if ($('#saveandviewbutton').attr("disabled")==true) {
	} else {

Open in new window

Question by:bbdesign
LVL 82

Accepted Solution

leakim971 earned 500 total points
ID: 35168933
$("#mainform input[name='selectprogram']:checked").length return the number of object found.

var $selection = $("#mainform input[name='selectprogram']:checked");
if( $select.length == 1) {
// only one found, phew !!!
else if( $select.length >=1 ) {
// more than one found !!!!
else {
// ok submit !!

Open in new window


Author Comment

ID: 35183777
.length -- great! Easy, too. Thanks.

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

680 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question