简体   繁体   中英

Hiding and showing div series using Javascript

I'm making basic GPA calculator using Javascript.

Here is my code:

<div class="list">

    <div class="row">
      <div class="col col-50">Subject 1</div>
      <div class="col"><input type="text" name ="GR1" placeholder="Grade"></div>
      <div class="col"><input type="tel" name="CR1" placeholder="Credits"></div>
    </div>

    <div class="row">
      <div class="col col-50">Subject 2</div>
      <div class="col"><input type="text" name ="GR2" placeholder="Grade"></div>
      <div class="col"><input type="tel" name ="CR2" placeholder="Credits"></div>
    </div>

<button class="button button-positive">
  Add Another Field //it can add uptop 10 fields
</button>

  </div>

It will increment the same div series while incrementing the input name up to 10 fields. User can click Add Another Field and add a new div field.

In every div field, it only changes the subject and input fields' name with an incrementation of 1.

Question:

What is the best way to achieve this without duplicating the same thing over and over? Or do I need to first create 10 div forms and hide all and show them one by one upon each click? Please give me example.

Here is a solution that is in pure Javascript that will allow you to add up to 10 "field blocks". In the HTML file, put:

<div id="list">
    <button onclick="addRow()">Add another field</button>
</div>

And here's the Javascript function to add a new row, and initialise the two first row:

<script type="text/javascript">
window.onload = function() {
    addRow();
    addRow();
};

function addRow() {
    var element = document.getElementById('list');
    var nextId = element.childElementCount;
    if (nextId <= 10) {
        var div = document.createElement('div');
        div.setAttribute('class', 'row');
        div.innerHTML = '<div class="col col-50">Subject ' + nextId + '</div><div class="col"><input type="text" name ="GR' + nextId + '" placeholder="Grade"></div><div class="col"><input type="tel" name="CR' + nextId + '" placeholder="Credits"></div>';
        element.insertBefore(div, element.getElementsByTagName('button')[0]);
    }
}
</script>

You can try it online on the following fiddle: https://jsfiddle.net/w82t30r4/

Try jQuery's clone ( read about it here )

$(document).ready(function(){
    $row = $(".row").clone();
    $("button").click(function(){
         $(".list").append($row.clone());
    })
})

What's happening is that I clone the row to start with (before any data is in it). Then I add a clone of that clone to .list when the button is clicked.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM