Menew Menew - 7 months ago 121
HTML Question

Show hide text box from a dynamic element jQuery c#

Below is my code, I am trying to hide and show dynamic elements. The problem I am having is, I only want my hidden div to only show one at a time if only I check "Other". However, the code below will show the hidden div for all number of

#dynamicRows
I have. so it works for initial 1st
#dynamicRow
added, the problem is when I have two or more
#dynamicRows


$('#dynamicRow').on('click', 'input[id^=race]', function () {
if ($(this).is(":checked")) {
if ($(this).val() == "Other") {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});

}
else {
$(".cssclass").each(function () {
$(this).closest("div").hide();

});
}
}
});


Below are dynamic rows, for help purposes i am showing the html code, however, it doesn't exist on the screen, a user will click "ADD" to generate the code below. I have no problem in generating dynamic row and it is not why I am posting. note the name in my radio button is generated by c# and everything works. Again the problem is not how to create a dynamic row, it is nicely taken care of in C#.

Dynamic row one works with the above jQuery:

<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhhh].race"> Other:

<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>


Dynamic row two doesn't work with the above jquery and it takes the above form events as its own, so if i check the radio button in row 2, the 1st dynamic row responds to that event and vice versa:

<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhh].race"> Other:

<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>

Answer

Working Example

id should be unique in same document, replace the duplicate ones by a class :

<input type="radio" value="No" class="race" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" class="race" name="Person[hhhhhh].race"> Other:

Also add class and not id to the dynamic rows generated by your C# code :

<div class="dynamicRow">

Then in your js use this class :

$(".cssclass").hide();
$('.dynamicRow').on('click', '.race', function () {
    if ($(this).val() == "Other") {
      $(this).next(".cssclass").show();
    } else {
      $(this).nextAll(".cssclass").hide();
    }
});

Hope this helps.

Comments