thadeuszlay thadeuszlay - 20 days ago 6
Javascript Question

How to get current element in order to select with javascript?

I've got the follwoing HTML structure (I do not have the IDs of the following elements because they are dynamically created):

<fieldset>
<div class="classA">
<select onchange="updateInputBox()">
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
</selects>
</div>
<div class="classB">
<input data-myAttribute="case1">
</div>
<div class="classC">
<a type="button">
<i class="fa fa-remove">x</i>
</a>
</div>
</fieldset>


The filedset and it's children is dynamically created. I want to change the attribute in the inputBox depending on what the user selected in the selectBox.

Here is an example how I would have done if the element fieldset would not have been dynamic (the following contains elements have IDs, but only because I want to demonstrate what I want; in reality I don't have IDs because they are dynamically created by clicking a button, that I do not show here):
https://jsfiddle.net/thadeuszlay/6bsgazvv/4/

But unfortunately I don't have the id of the fieldset, because it is dynamically created. Is there a way how you can get the position of the current element?

I tried to pass itself in the updateInputBox-function:

<select id="selectBox" onchange="updateInputBox('+ this +')">


I also tried with jQuery:

$(this).parent().parent()


but in both cases the console would say


"Unexpected identifier"


Update:
Inside the function doing something like this (currentElement is the selectBox/DropDownBox):

currentElement.parent().parent().setAttribute("data-myAttribute", "hello");


Uncaught TypeError: selectBox.parent is not a function

Answer

You can use jquery 'closest' for this as below.

HTML

<select id="selectBox" onchange="updateInputBox(this)">

JS

function updateInputBox(selectElm) {
   var inputElm = $(selectElm).closest('fieldset').find('input');

inputElm.attr('data-myAttribute', $(selectElm).val());

}

// instead of inline onchange event and the above code, you can use the below to trigger the event

$(document).on('change', 'fieldset select', function () {
       var inputElm = $(this).closest('fieldset').find('input');

    inputElm.attr('data-myAttribute', $(this).val());

    });