Update2:
Do you mean to add required
attribute to input only when Ansere2
is selected? You can add a judgment condition:
function test(newValue)
{
var Ansere = newValue.value;
if (Ansere == "Ansere2")
{
var selectName = newValue.name;
var inputName = selectName.replace("Ansere", "Discreption");
var input = $("input[name="+"'"+inputName+"'"+"]");
$(input).prop('required',true);
}
}
Update:
If you want to use the name of input
, you can refer to my code below:
@for(var i = 0; i < 5; i++)
{
<select class="form-control" required name="[@i].Ansere" asp-for="@Model[@i].Ansere" onchange="test(this)">
<option value="" default="" selected="">انتخاب کنید</option>
<option value="Ansere1">Ansere1</option>
<option value="Ansere2">Ansere2</option>
<option value="Ansere3">Ansere3</option>
<option value="Ansere4">Ansere4</option>
<option value="Ansere5">Ansere5</option>
</select>
<td colspan="3"><input class="form-control text-sm" placeholder="شرح مورد ارزیابی ..." name="[@i].Discreption" autocomplete="off"/></td>
}
@section Scripts {
<script>
function test(newValue)
{
var Ansere = newValue.value;
var selectName = newValue.name;
var inputName = selectName.replace("Ansere", "Discreption");
var input = $("input[name="+"'"+inputName+"'"+"]");
$(input).prop('required',true);
}
</script>
}
------------------------------------------------------------------------------------------------------
If you have multiple selects without id to distinguish, you can refer to my code below.
I wrap select
and input
in a div
, then monitor the change of select
:
@model List<TestApp.Models.MyModel>
@for(var i = 0; i < 5; i++)
{
<div>
<select class="form-control" required name="[@i].Ansere" asp-for="@Model[@i].Ansere" onchange="test(this)">
<option value="" default="" selected="">انتخاب کنید</option>
<option value="Ansere1">Ansere1</option>
<option value="Ansere2">Ansere2</option>
<option value="Ansere3">Ansere3</option>
<option value="Ansere4">Ansere4</option>
<option value="Ansere5">Ansere5</option>
</select>
<td colspan="3"><input class="form-control text-sm" placeholder="شرح مورد ارزیابی ..." name="[@i].Discreption" autocomplete="off"/></td>
</div>
}
@section Scripts {
<script>
function test(newValue)
{
var Ansere = newValue.value;
var input = newValue.parentElement.getElementsByTagName('input')[0];
$(input).prop('required',true);
}
</script>
}
TestResult:

Is this what you want?