2
  • MyJSP

    <td id="CardNumLabel" colspan="2" width="300px" align="left">
      <input readonly="readonly" type="text" name="Names1" id="cNames1" size="25"
        value="Cardnumber1" />
      <input type="text" name="Values1" id="cValues1" size="25" value="" maxlength="6"/
      <input type="hidden" name="Cardnumbersay" id="Cardnumbersay" value="1">
      <input type="button" value="+" onClick="addCardnumber();">
    </td>
    
  • My JavaScript

    function addCardnumber()
    {
        var cardsay;
        cardsay = parseInt(document.getElementById('Cardnumbersay').value);
        if(document.getElementById('cNames'+cardsay.toString()).value=="" || document.getElementById('cValues'+cardsay.toString()).value=="")
        {
            alert('NULL');
        }else{
            cardsay = cardsay+1;
            CardNumLabel.innerHTML = CardNumLabel.innerHTML+"<input type='text' readonly='readonly' name='Names"+say+"' id='cNames"+cardsay+"' size='25' value='Cardnumber"+cardsay+"' />"+"&nbsp;"+
            "<input type='text' name='Values"+say+"' id='cValues"+cardsay+"' size='25' maxlength='6'/><br>";
             document.getElementById('Cardnumbersay').value = cardsay;
        }
    }
    

Hi guys, When I click the "+" button the javascript function adds new textboxes for filling. This part is running normally. The problem is when I click the button for adding second textboxes js adds them but deletes the value which I entered to the first textbox. I dont want lose the data when I click add button. How to solve it? Thanks

1 Answer 1

1

You are losing the data which the user already entered in the textboxes because the entire textboxes are getting replaced by newer ones when you modify the innerHTML using the following js code:

CardNumLabel.innerHTML = CardNumLabel.innerHTML+"<some_html_goes_here>";

Due to the above statement the entire contents of the td having id="CardNumLabel" are replaced by a newer value. The newer innerHTML put in has the number of textboxes increased by one but no provision to retain the content previously entered by the user in the textboxes.

To retain the previous entered data content:

  1. Use appendChild() method instead of modifying innerHTML directly
  2. Or, Write a loop in js to copy the data entered by the user and store it in an array. Then use the same innerHTML way to increase the number of textboxes and then write another loop to put back the data from the array into the text-boxes

Hope I helped!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.