Use a function for multiple events in JavaScript?
I have several divs tag, each with a button inside. Clicking on each button will show a hidden div tag.
<div class="box-form">
<label class="control-label">name : </label>
<span class="text text-info txt_modelname">@Model.Name</span>
<button class="btn btn-primary btn-sm edit__field">edit</button><br />
<div class="box-edit-name" style="display:none;">
<form id="Frm_EditName" class="frm" method="post">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control input-name" />
<input type="submit" value="save" class="btn btn-success js-btn_submitname mt-1" disabled />
</div>
</form>
</div>
</div>
<div class="box-form">
<label class="control-label">family : </label>
<span class="text text-info txt_modelname">@Model.family</span>
<button class="btn btn-primary btn-sm edit__field">edit</button><br />
<div class="box-edit-name" style="display:none;">
<form id="Frm_EditName" class="frm" method="post">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control input-name" />
<input type="submit" value="save" class="btn btn-success js-btn_submitname mt-1" disabled />
</div>
</form>
</div>
</div>
I want to create a function that displays every button on this div below it
Btn_editName.click(function () {
$('.box-edit-name').toggle();
});
You could select the corresponding div via:
$("button.btn.btn-primary.btn-sm.edit__field").click(function(){
$(this).next().next().toggle()
})
You use two .next()
calls because the div comes after a <br />
$("button.btn.btn-primary.btn-sm.edit__field").click(function() {
$(this).next().next().toggle()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box-form">
<label class="control-label">name : </label>
<span class="text text-info txt_modelname">@Model.Name</span>
<button class="btn btn-primary btn-sm edit__field">edit</button><br />
<div class="box-edit-name" style="display:none;">
<form id="Frm_EditName" class="frm" method="post">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control input-name" />
<input type="submit" value="save" class="btn btn-success js-btn_submitname mt-1" disabled />
</div>
</form>
</div>
</div>
<div class="box-form">
<label class="control-label">family : </label>
<span class="text text-info txt_modelname">@Model.family</span>
<button class="btn btn-primary btn-sm edit__field">edit</button><br />
<div class="box-edit-name" style="display:none;">
<form id="Frm_EditName" class="frm" method="post">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control input-name" />
<input type="submit" value="save" class="btn btn-success js-btn_submitname mt-1" disabled />
</div>
</form>
</div>
</div>