Ad

How To Add Parent Element Name To Child Element

i have an input Element that Get Name of Helper but Two Element has same id it is incorrect for Edit this problem, i want to Add Parent Div Id to Child Input.how can i Append ParentId to ChildId

 <div class="wrapper-merge-input">
            <div id="Stb" class="col-md-6   ">
                <label  class="control-label">StartDate</label>
                @page.Html.Raw(fromHtml)
            </div>
            <div id="Edb" class="col-md-6  ">
                <label class="control-label">EndDate</label>
                @page.Html.Raw(toHtml)
            </div>
        </div>
    </div>

*And *

<input type="text" dir="ltr"   class="form-control"
   name="@name" id="@name"
   value="@value" 
   onclick="DatePicker.Show(this,'@today');" />

for example @name+Edb

Ad

Answer

The code below shows how you can use .attr("id") to get an element's id. In order to travel up one level to the parent DOM element you should use .parent().

You can also use .attr("id", "new-id") to set an attribute value. This can take strings or variables (as in the code below).

By placing the update code into a function you can call it on page load, after a click or any other event. I have made it run after a click of the button so you can see the id change.

I added some basic styling to make the demo a bit nicer to use.

Let me know if you wanted something else.

WARNING you will likely want to make the updateID() function more specific, so it does not act on every input on the page.

// Click event for button to demonstrate change
$("#startUpdate").click(function() {
  updateID();
});


function updateID() {

  // Cycle through each input - WARNING - you will want to make this more selective
  $("input").each(function() {

    // Update id of input from it's own name and it's immediate parent's id
    $(this).attr("id", $(this).attr("name") + "-" + $(this).parent().attr("id"));

    // Print message to console to demonstrate id
    console.log("new id = " + $(this).attr("id"));

  });
}
.wrapper-merge-input {
  border: 1px solid black;
  border-radius: 5px;
  padding: 8px;
  margin: 20px;
}

#Edb {
  padding-top: 10px;
}

#startUpdate {
  margin-left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper-merge-input">
  <div id="Stb" class="col-md-6   ">
    <label class="control-label">StartDate</label>
    <input name="example1" id="example1" value="example1" onclick="DatePicker.Show(this,'@today');">
  </div>
  <div id="Edb" class="col-md-6  ">
    <label class="control-label">EndDate</label>
    <input name="example2" id="example2" value="example1" onclick="DatePicker.Show(this,'@today');">
  </div>
</div>

<button id="startUpdate">Update IDs</button>

Ad
source: stackoverflow.com
Ad