Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Find next select element

What I am trying to do is populate data in a select element. I'm using the following code, where a user selects a SubjectCategory from one drop down, which then should populate the next select element's html. The handler itself is working just fine, it returns the correct html I need to place inside the select element.

Also, keep in mind that I eventually clone both of these select elements and will need to populate them accordingly.

The problem is that $elem is always returning null.

I'm guessing that it's a problem with this line of code, however not quite sure (keeping in mind that I'm also cloning these two select elements):

var $elem = $this.closest('div').prev().find('select');

$(".SubjectCategory").live("click", function () {
    var $this = $(this);
    var $elem = $this.closest('div').next().find('select');
    var a = $this.val();

    $.get("/userControls/BookSubjectHandler.ashx?category=" + a, {}, function (data) {
        $elem.html(data);
    });
});

<div class="singleField subjectField">
  <label id="Category" class="fieldSml">Subject Matter</label>
  <div class="bookDetails ddl"><select id="ddlSubjectMatter" class="fieldSml SubjectCategory"></select></div>

  <label id="Subjects" class="fieldSml">Category</label> 
  <div class="bookDetails ddl" id="subjectMatter"><select id="ddlSubjects" class="fieldSml Subjects"></select></div>
</div>
like image 465
fulvio Avatar asked Oct 03 '11 05:10

fulvio


2 Answers

You're searching inside the <label>, not the next <div> as you want. next only gets one element after the current one.

Try this: It searches for the first div next to your parent element.

var $elem = $this.closest('div').nextAll('div').first().find('select');
like image 62
Digital Plane Avatar answered Sep 28 '22 14:09

Digital Plane


Given that the source element has an id of ddlSubjectMatter and the target select element has an id of subjectMatter, it may be a lot simpler to capitalise the first letter of the second id (i.e. make SubjectMatter) then you get the second element by:

var elem = document.getElementById(this.id.replace(/^ddl/,''));

It makes the element relationship independent of the document layout.

Incidentally, it is invalid HTML to have select elements with no options, not that it is a big issue.

like image 25
RobG Avatar answered Sep 28 '22 15:09

RobG