Reputation: 7249
I don't know how to put this. This has got a bit messy. I couldn't use the right words to ask the question. Here is my code:
<div id="addfieldcontainerdropdown">
<div id="addDropdownfield">
<div id="div0">
<select name="0" style="margin: 20px" id="0">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input style="margin: 7px" id="1" placeholder="Value" onkeyup="check_if_value_set(this); return false;"
type="text">
<span style="margin: 7px;cursor: pointer;" onclick="remove_fields(this);return false;"><iclass="fa fa-times"></i></span>
</div>
<div id="div2">
<select name="2" style="margin: 20px" id="2">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input style="margin: 7px" id="3" placeholder="Value" onkeyup="check_if_value_set(this); return false;"
type="text">
<span style="margin: 7px;cursor: pointer;" onclick="remove_fields(this);return false;"><i class="fa fa-times"></i></span>
</div>
<div id="div4">
<select name="4" style="margin: 20px" id="4">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input style="margin: 7px" id="5" placeholder="Value" onkeyup="check_if_value_set(this); return false;"
type="text">
<span style="margin: 7px;cursor: pointer;" onclick="remove_fields(this);return false;"><i class="fa fa-times"></i></span>
</div>
</div>
<a href="javascript:void(0)" onclick="show_new_text_field(this);event.preventDefault();return false;" style="cursor:pointer">
<span id="add_new_span" class="addnew" style="float: none;margin-left: 1%;"><i class="fa fa-plus fa-fw"></i>Add New Field</span>
</a>
</div>
You can see there is a function named "show_new_text_field(this)" at the bottom of the code. Using this function, i need to get the id of say, div4 or select box of id 4. How can this be done ? I tried using prent() and closest(). Nothing worked. Any type of suggestions would be appreciated. Thanks in advance !!
Upvotes: 3
Views: 1931
Reputation: 21672
Something like this?
var lastDiv = $("[id^=div]").last(); //Get Last div whose ID begins with "div"
var lastDivId = lastDiv.attr('id'); //Get ID of that div
var firstSelect = lastDiv.find('select').first(); //Get the first 'select' of that div
var firstSelectId = firstSelect.attr('id'); //Get that select's ID
console.log("Last Div: " + lastDivId); // "Last Div: div4"
console.log("First Select in " + lastDivId + ": " + firstSelectId); //"First Select in div4: 4"
In the event your div won't always start with "div", you could just select the last child div
of your parent (addDropdownfield
) by doing this:
var lastDiv = $("#addDropdownfield div").last(); //Get all children divs of addDropdownfield - from that list, just the last one
Upvotes: 5