简体   繁体   中英

Dynamically added input field disappearing rightaway

I am trying to write a jQuery snippet, in which I can add input fields dynamically on click of 'Add Image' button (code below) using jQuery appendTo() function. However, everytime I click on the button the textbox appears and then disappears rightaway. I have noticed that others have also faced this problem, but am not able to find a proper solution for this problem. Can someone please help me out with this?

...
<div class="row">
    <div class="span4" id="images-div">
        <input type="text" name="txt-image[]" class="span4 txt-input-field">
    </div>
    <div class="span1">
        <button class="btn" id="btn-add-image">Add Image</button>
    </div>
</div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
    $(document).ready(function(){
        $('#btn-add-image').click(function() {
            $('<input type="text" name="txt-image[]" class="span4 txt-input-field">').appendTo('#images-div');
        });
    });
</script>
...

Answer provided by DEREK N :


Problem solved by using preventDefault() function, as shown below

<script>
    $(document).ready(function(){
        $('#btn-add-image').click(function(event) {
            event.preventDefault();
            $('<input type="text" name="txt-image[]" class="span4 txt-input-field">').appendTo('#images-div');
        });
    });
</script>

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