NealR
NealR

Reputation: 10699

Use jQuery to check and see if div element is empty

Below is the code I'm using to place a blur event on a text box in my ASP MVC 3 view. The code works fine if #MailingState is empty, however it cannot tell if #channelName is empty.

For example, if #channelName is empty but #MailingState is not, then when I place a value in #MailingZip the getDrmTerritory Ajax call is fired off every time.

Here is the jQuery

    $('#MailingZip').blur(function () {
        if ($('#AlignmentM').is(':checked')) {
            if ($('#MailingState').val() != "" && $('#channelName').html() != "") {
                getDrmTerritory($('#MailingZip').val(), $('#MailingState').val(), $('#channelName').html());
            }
        }
    });

and here is the HTML for the #channelName segment it is checking

    <div id="channelName" class="M-display-field">
        @*this will be updated via ajax from Market Segment *@
        @Html.DisplayFor(model => model.Channel, new { style = "margin-left: 300px;" } )
    </div>

The section mentioned in the comments is updated via another jQuery method that looks like this

function ChangeChannel() {
    //this function called if Market Segment changes, to update the channel
    var pendistcode = document.getElementById('Pendist');
    if (pendistcode == null) alert('Error: Cannot find Market Segment control');
    //alert('!pendistcode value is ' + pendistcode.value);

    $.ajax({
        type: 'POST',
        url: '/AgentTransmission/GetChannel/',
        data: { pendist: pendistcode.value },
        success: function (data) {
            //                alert("success: " + data);
            $('#channelName').html(data);
            $('#Channel').val(data);
        },
        error: function (data) {
            alert("failure to obtain Channel name");
        }
    });

    CheckTerritory('channel');

} //end ChangeChannel

That jQuery method (ChangeChannel) appends text to the channelName div which, when rendered with a value in it, looks like this

enter image description here

Here is the HTML you get when you inspect the Life Sales from that picture

enter image description here

Upvotes: 1

Views: 859

Answers (2)

NealR
NealR

Reputation: 10699

I put in an alert statment to find out channelName's length and it came back with 35, so there must obviously be some white space that gets rendered each time. I had to change the statement to the following to trim out the whitespace and add the variable to the condition.

            var channel = $.trim($('#channelName').html());
            if ($('#MailingState').val() != "" && channel != "")

Upvotes: 1

palaѕн
palaѕн

Reputation: 73906

You can check if #channelName is empty or not like this:

if ( $('#channelName').is(':empty') )

and combine with your code like this:

if ($('#MailingState').val() != "" && !$('#channelName').is(':empty'))

Upvotes: 2

Related Questions