Dhruvil Dave
Dhruvil Dave

Reputation: 109

Rails: How to create a Add more button which add some textfield in erb form with jquery

I am creating a form in which quote_amounts is contains Hash. I want to create a form with a button in which when i click on button new set of textfields opens

for ex: when a form opens there should be one 2 textfields: label & amount, and when i send data to it the params should be "quote_amounts"=> [{"label"=> "website", "amount"=> 1000}]

and when i click on add more button a set of 2 new text fields should open and then i fill the data then params should be

"quote_amounts"=> [{"label"=> "website", "amount"=> 1000}, {"label"=> "website1", "amount"=> 11000}]

and same if i add more text fields.

quote_amounts is a jsonb field

please help me with this, stuck in this for 2 days.

Upvotes: 0

Views: 1847

Answers (2)

Azmat Rana
Azmat Rana

Reputation: 562

You may have to use javascript or jquery for adding dynamic inputs and then have to submit it using ajax. I have created a simple scenario looking at your question. Hope this will work for you.

You can add this to your erb file.

In your controller, you have to define an action method that will handle format.json to return so you can have the response in the ajax either success or error.

I hope you will be able to fix your problem now.

enter image description here

function addMore(){
    $("#dynamic-inputs").append($("#original-inputs").html())
  }

  function submiForm() {
    let data = []
    $("[name='label']").each((i, item)=>
    {
      data.push({'label': item.value, 'amount':  $("[name='amount']")[i].value})
    })
    console.log({'quote_amounts': data})
    $.ajax({
        url: 'urlOfYourActionController',
        data: {'quote_amounts': data},
        type: 'POST',
        success: function(data){
            // handle your success here
            console.log(data);
        }
    });
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="original-inputs">
  <label>Label</label>
  <input name='label' />
  <label>Amount</label>
  <input name='amount' />
  <br/>
</div>

<div id="dynamic-inputs"></div>

<button type='button' onclick="addMore()">Add More (+)</button>
<button id='sendRequest' onclick='submiForm()'>submit</button>

Upvotes: 1

Kuba Kazmierczak
Kuba Kazmierczak

Reputation: 1

You could try adding these additional fields with help of ajax. E.g. the button would asynchronously append the form with new fields.

More info on using JavaScript with rails

Upvotes: 0

Related Questions