add select field dynamically (Laravel project)

Asked

Viewed 47 times

0

I am creating a form of a repository and I have several fields like this modality. What I don’t know how to do is create a function so that when a person clicks on the + button next to the select, he creates on the screen another select field of modality exactly the same as the first (in this case, the image) and I can make my loop to feed it with the database data.

I am a door to mess with front end (I believe this is it)

1 answer

0

Use the function .clone() of Jquery, create a select with the default options without id and hidden to serve as a basis, so when you click on the add it copies this select and displays on the screen, already to popular with database data is the same function just put it inside a loop to receive the data.

JS

jQuery('select[name="default"]').hide();
jQuery('#addSelect').on('click', function() {
    var novoSelect = jQuery('select[name="default"]').clone();
    novoSelect.attr('name', 'select1')
    novoSelect.show();
    jQuery('body').append(novoSelect);
});

Html

<select name="default">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>
<button id="addSelect">add</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.