I have few input fields in a container and user can multiply these fields. I need to change the name of the input fields based on the container.
<div class="stations">
<input type="radio" name="pp[prc][0][station][0][id]">
<input type="radio" name="pp[prc][0][station][1][id]">
</div>
This is my HTML form.
$(".stations").each(function(sIndex){
//Loop thru all .station
$("input:radio", $(this)).each(function(rIndex){
//Loop thru all radio buttons inside that container and change their names accordingly
$("input:radio", $(this)).attr('name','pp[prc]['+sIndex+'][stations]['+rIndex+'][id]');
});
});
When I do this, for some reason when the user duplicated <div class="station">
and its content the name of the radio buttons are not changed accordingly. Where do I do wrong?
您正在使用$(selector, context)
并且输入元素不能有子元素,您应该编写以下代码:
$(this).attr('name', '...');
Looks like you have some issues with the selectors. Try it like this:
//Loop through each .station
$(".stations").each(function(sIndex){
//Loop through each radio buttons inside the container
$(this).find("input:radio").each(function(rIndex){
// Change the radio name attribute
$(this).attr('name','pp[prc]['+sIndex+'][stations]['+rIndex+'][id]');
});
});
Here's a jsFiddle with the names on the screen for quicker viewing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.