Increase the value of the input's name with JavaScript

I have multiple divs with radio buttons, and the input names are cty_1. If I add more divs, I want the input names inside those divs to become cty_2, cty_3, etc., respectively.

Here is an example of my code:

<div class="category">
    <div class="col-md-6">
        <input type="radio" name="cty_1" id="1" value="car">
        <label for="1">car</label>
    </div>
    <div class="col-md-6">
        <input type="radio" name="cty_1" id="2" value="bike">
        <label for="2">bike</label>
    </div>
</div>

If another div is added, it should look like this:

<div class="category">
    <div class="col-md-6">
        <input type="radio" name="cty_1" id="1" value="car">
        <label for="1">car</label>
    </div>
    <div class="col-md-6">
        <input type="radio" name="cty_1" id="2" value="bike">
        <label for="2">bike</label>
    </div>
</div>

<div class="category">
    <div class="col-md-6">
        <input type="radio" name="cty_2" id="3" value="phone">
        <label for="3">phone</label>
    </div>
    <div class="col-md-6">
        <input type="radio" name="cty_2" id="4" value="computer">
        <label for="4">computer</label>
    </div>
</div>

Note: I do not know JavaScript.

Answer №1

If you are utilizing jQuery, then adding a new level to the "category" element each time you click on the "Go" button is quite simple. By using the code snippet below, the attributes for "name" and "id" will automatically increment:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<body>
  <div class="container">
    <btn class="btn btn-primary">Go</btn>
    <div class="category">
        <div class="col-md-6">
           <input type="radio" name="cty_1" id="1" value="car">
           <label for="1">car</label>
        </div>
        <div class="col-md-6">
           <input type="radio" name="cty_1" id="2" value="bike">
           <label for="2">bike</label>
        </div>
    </div>
  </div>
</body>

<script>
$('.btn-primary').on('click',function(){
  var idx = parseInt($('.category').last().index())+1;
  $('.category')
    .last()
    .clone()
    .find('input[type=radio]')
      .each(function(index){
        $(this)
          .attr('name','cty_' + idx)
          .attr('id','cty_' + idx + "_" + index)
          .parent()
            .find('label')
              .attr('for','cty_' + idx + "_" + index)
              .end()
      })
      .end()
    .insertAfter($('.category').last());
});
</script>

Answer №2

Check out this updated fiddle for a solution: click here

//HTML 
<div id="divMain">      
 </div>

//jQuery Code
var valuesArr=["car","bike","truck","Test4","Test5"];
var cityCounter=1;
var idCounter=1;
var addCategoryFlag=false;
function GenerateHtml(){
    var html="";
    for(var i=0;i<valuesArr.length;i++){    
       if(idCounter%2!=0){
          html+='<div class="category">';          
       }
       else{
          addCategoryFlag=true;
       }
        html+='<div class="col-md-6">';
        html+='   <input type="radio" name="cty_'+cityCounter+'" id="'+idCounter+'" value="'+valuesArr[i]+'">';
        html+='   <label for="'+idCounter+'">'+valuesArr[i]+'</label>';
        html+='</div>';
        if(addCategoryFlag){
                html+='</div>';
          addCategoryFlag=false;
          cityCounter++;
        }
        idCounter++;
    }

    $("#divMain").html(html);
}

GenerateHtml();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigate to the following div elements using the mousewheel in jQuery

Looking to implement a parallax effect where the page scrolls to the next block on each mousewheel rotation. I attempted to achieve this using the code below but it didn't work as expected. Can someone offer any suggestions? Check out the live JSFid ...

The php code managed to infect my website

My website has been infected by a plugin that is generating ads for a company I am not affiliated with. I tried using anti-malware software, but it didn't detect anything. var doc = document.getElementById('ad_iframe').contentWindow.document ...

The menu is loaded dynamically by Ajax from JavaScript once the page is refreshed

$('#subregionListPage').bind('pageinit', function(event){ var output = $('#subregions'); var region = getUrlVars()["reg"]; $.ajax({ url: 'http://localhost:8888/my/getsubregions.php', dat ...

Tips for accessing <Field> values in redux-form version 7.0.0

class CustomForm extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { const { Add, noteList } = this.props; Add('this is title value' , 'this is ...

Arranging several lists in columns with a customized header title

I am looking to have 7 lists displayed side by side, each with a unique styled header title. I want the lists to be neatly organized under their respective titles, including the bullets. I attempted to use text-indent for this purpose, but it seems that ...

Displaying various charts in a single view without the need for scrolling in HTML

How can I display the first chart larger and all subsequent charts together in one window without requiring scrolling? This will eventually be viewed on a larger screen where everything will fit perfectly. Any recommendations on how to achieve this? Here ...

Retrieve the title attribute value by utilizing the parent() function

Check out this snippet of HTML code: <a class="ms-navedit-linkNode" title="Apps" href="url/test"> <span class="menu-item-text">Apps</span> </a> I'm looking to update the title value from "Apps" to a different text. Below ...

The alignment issue arises when using Grid-column-end with items of a set width

I am facing an issue with aligning an item in a specific column while maintaining a fixed width. When I attempt to right-align the item, it overflows the designated space. Removing the width attribute resolves the problem, but that is not a viable solution ...

Deserialization of JSON is not supported at this time

I'm struggling with deserializing an array in .NET MVC5, any assistance would be highly appreciated. JsonList psl = (new JavaScriptSerializer()).Deserialize<JsonList>(id); My object structures [Serializable] public class JsonList { public ...

.forEach returns an undefined value for each length

Having trouble with my if statement. It seems like the else block is working fine, but the if section is not functioning as expected. The variable count1 comes out as undefined. Interestingly, the conditions inside the if statement are working correctly ...

I am looking to incorporate a password recovery page into my login process, but I am facing difficulty navigating to it once the code has been modified

I'm looking to include a forgotten password option on my login page, but I'm facing an issue when trying to navigate to it after updating the code. The website is throwing the following error message: [vue-router] uncaught error during rout ...

In a React application, adjusting the main container height to 100vh results in the window.scrollY position being set to

I was facing problems with flashing on the Safari/Firefox browsers. By setting the main container height to max-height: 100vh, I managed to resolve the flickering issue. However, I am also looking for a solution to keep track of the window.scrollY positi ...

Configuring cloud code on Back4App to automatically trigger a POST API request to update the ESP

I am a beginner when it comes to developing APIs and cloud code, and I need help figuring out how to create an API that can add or update users in my back4app database table to my sendinblue (ESP) contact list. Could someone provide guidance on what shoul ...

Sending the content of a textBox to a JavaScript function

Although my question may be somewhat outdated, after exhausting all possible solutions, I am still unable to find a resolution. I am trying to create a function for verifying input fields: This particular function is functioning correctly: function myFu ...

Is there a way to efficiently remove deleted files from my Google Drive using a customized script?

After creating a function in Google Scripts to clear my trashed files, I ran it only to find that nothing happened. There were no logs generated either. function clearTrashed() { var files2 = DriveApp.getFiles(); while (files2.hasNext()) { var c ...

Issue with undefined object reference in Moment.js when making an ajax request

Currently, I am working on developing a straightforward booking calendar using Eonasdan's bootstrap-datetimepicker, which relies on the moment.js library. To incorporate localization, I have included the necessary file. My setup consists of linked pic ...

To retrieve a property in Vue, you can use either the "this" keyword

Exploring Vue for the first time and navigating through accessing viewmodel data has me puzzled. When should I utilize this.property versus vm.$data.property. In this scenario with a table where I can select rows, there are methods in place to select all ...

Can we preserve the original function header even after the typescript compilation process?

Typically, one can access function information by using the following method: function someFunction(arg1, { a, b, c}){} someFunction.toString() ... compile and run //function someFunction(arg1, { a, b, c}){} However, when TypeScript compiles the code, ...

Receiving an alert in VSCode regarding the usage of CharAt function in conjunction with Vuejs

While attempting to extract the first character of a computed property, I utilized the charAt() function. Despite the fact that it is functioning correctly, I am receiving a warning from VSCode indicating that it is not the correct usage. computed: { ...m ...

Conflicting issue arising from the coexistence of Bootstrap container and CSS footer

I am currently working on creating a website with a footer menu. I have been using the container in my content to ensure proper alignment as I was unsure how to center it otherwise. However, when attempting to add the footer menu without using the containe ...