I have the following:
<div class="btn-group">
<input disabled="disabled" id="dialogType">
<button data-toggle="dropdown" class="dropdown-toggle">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" id="towns">
<li><a data-value="0Z" href="#">A</a></li>
<li><a data-value="10" href="#">B</a></li>
</ul>
</div>
<div class="btn-group">
<input disabled="disabled" id="dialogStatus">
<button data-toggle="dropdown" class="dropdown-toggle">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" id="places">
<li><a data-value="22" href="#">C</a></li>
<li><a data-value="33" href="#">D</a></li>
</ul>
</div>
In the past I used the following javascript to populate the #town label field when one of the links is clicked:
$('#towns > li > a').click(function (e) {
e.preventDefault();
$('#town').text($(this).html())
});
Now I would like to make this javascript work for any similar ul that’s inside of a DIV with the class dropdown-menu.
So what I would like is:
- When the user clicks on a link such as A then the first input element inside the btn-group is given the value of A and also a data-value of “0Z”
- When the user clicks on a link such as D then the first input element inside that btn-group is given the value of D and also a data-value of “33”
Can someone tell me how I could do this. I just need a more generic version of the function above.
.
I’d suggest, though currently untested:
Essentially the way this works is:
.btn-group(ancestor) element,inputelement within,data-value(assigned to thedValuevariable) to thedata-valueattribute of thatinput, and finallydValueto be thevalueof thatinput.Edited in response to comment left by OP:
Because the
btn-groupelements are added dynamically, I’d suggest the following change:References:
attr().closest().find().on()val().