Parag Parag - 1 month ago 9
HTML Question

Return false if no value is selected (other than heading) from select box

I have a HTML form having select box. On selection of first select box other select box are auto filled using AJAX.

enter image description here

On

Download Records (id="getCsv")
button click event a CSV file is generated. Problem is, I want to make all the fields mandatory. Here is the jquery code

var teacher_name = $("#sel_teacher option:selected").text();
var unittest_name = $("#sel_test1 option:selected").text();

var class_name = $("#sel_class1 option:selected").text();
var class_id = $('#sel_class1').val();

var division_name = $("#sel_div1 option:selected").text();
var division_id = $('#sel_div1').val();

var subject_name = $("#sel_sub1 option:selected").text();

if(teacher_name == "")
{
alert('Please Select Teacher Name.');
return false;
}
else if(class_name == "")
{
alert('Please Select Class Name.');
return false;
}
else if(division_name == "")
{
alert('Please Select Division Name.');
return false;
}
else if(subject_name == "")
{
alert('Please Select Subject Name.');
return false;
}
else if(unittest_name == "")
{
alert('Please Select Unit Test Name.');
return false;
}
else
{
var myObject = new Object();
myObject.class_name = class_name;
myObject.class_id = class_id;
myObject.division_name = division_name;
myObject.division_id = division_id;
myObject.subject_name = subject_name;
myObject.test_name = unittest_name;

var formData = JSON.stringify(myObject);

$('#getCsv').attr('href','csv_generator.php?data='+formData);
}
});


Problem is, when I click
Download Records
, even though the first select box is empty directly alert box for second select box pops up.

I tried to solve this problem using,

if($("#sel_teacher").attr("selectedIndex") == 0)
{
alert("You haven't selected anything!");
return false;
}


But no luck, can anybody please help me with this?

Any help is appreciated.

Thanks

Answer

selectedIndex is a property, use prop:

$("#sel_teacher").prop("selectedIndex")

Also, you can simplify your code by retrieving the selected value using just $("#sel_teacher").val() and compare to empty string (assuming the value of that option is empty).

var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...

if (teacher_name == '') {
   alert("You haven't selected anything!");
   return false;
}

// test other values here...