B. Clay Shannon B. Clay Shannon - 7 months ago 8
Javascript Question

How can I exit from a jQuery event when an "unrelated" html select element has had no option selected?

I want to exit from a checkbox's change ([un]check) event if a particular select element has not had an option selected. I tested what the value for the select element was with nothing selected with this code at the start of my "ready" function:

var unitval = $('#unitsselect').val();
alert(unitval);


The alert said "null" so I tried this:

$("#ckbx_produceusage").change(function () {
var unitval = $('#unitsselect').val();
if (unitval == null) {
return;
}
alert('from ckbx_produceusage change event');
});


That, though, caused no beginning of solutions by telling me there was an IIS problem - it didn't even show me an error page. Once I did away with the null check, though:

$("#ckbx_produceusage").change(function () {
var unitval = $('#unitsselect').val();
//if (unitval == null) {
// return;
//}
alert('from ckbx_produceusage change event');
});


...I saw the alert on checking the checkbox in question.

So how can I exit the event handler when the select element has not had a selection made from it?

UPDATE



I tried Horacio Benitez's suggestion:

$("#ckbx_produceusage").change(function () {
var unitval = $('#unitsselect').val();
if (unitval == -1) {
event.stopPropagation();
event.preventDefault();
};
alert('from ckbx_produceusage change event');
});


...but still saw the alert. So I added another one:

$("#ckbx_produceusage").change(function () {
var unitval = $('#unitsselect').val();
alert(unitval);
if (unitval == -1) {
event.stopPropagation();
event.preventDefault();
};
alert('from ckbx_produceusage change event');
});


...and it is "null" (not "-1")

This is the code that adds the options to the units select:

<select class="form-control, dropdown" id="unitsselect" name="unitsselect">
<option disabled selected value="-1">Please choose a Unit</option>
@foreach (var field in units)
{
<option id="selItem_@(field.unit)" value="@field.unit">@field.unit</option>
}
</select>


The "Please choose a Unit" with a value of -1 is what is seen when the page displays. But checking the "ckbx_produceusage" checkbox shows me "null" and then "from ckbx_produceusage change event"

How can I exit/return out of the checkbox's change event when no option from the unit select has been chosen?

Answer

You can use a variable to track if the user has changed the select element.

// If the change event occurs on the select element the user made a selection.
// Set a variable called unitSelectChanged to true if they do.

var unitSelectChanged = false;
$("#unitsselect").change(function(){
    unitSelectChanged = true;
});

$("#ckbx_produceusage").change(function () {
    // Exit from the handler if that variable is true
    if (unitSelectChanged) {
        return;
    }
    alert('from ckbx_produceusage change event');
});
Comments