Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bootstrap select doesn't send field data on form submit #1342

Closed
webpixels opened this issue Mar 26, 2016 · 59 comments
Closed

Bootstrap select doesn't send field data on form submit #1342

webpixels opened this issue Mar 26, 2016 · 59 comments

Comments

@webpixels
Copy link

Hi,

I am having an issue with this plugin and I can't find a solution. I am using this with Laravel (even though I don't think it is relevant)

I have a multiple select which is works perfectly fine and it sends data on form submit. After I added the selectpicker class, the submitted value returns null. I really can't see why, because I used it many times and it worked perfectly fine.

`

<select id="user_categories" class="selectpicker" multiple="multiple" name="user_categories[]">  
<option value="1" selected="selected">Option 1</option>
<option value="2" selected="selected">Option 2</option>
</select>

`

Thanks!

@illbehere
Copy link

I have the same issue, using Bootstrap form-control class sends value properly, once I add selectpicker class this stops sending the value.

@caseyjhol
Copy link
Member

See guidelines for contributing.

Bug reports

A bug is a demonstrable problem that is caused by the code in the repository.
Good bug reports are extremely helpful - thank you!

Guidelines for bug reports:

  1. Use the GitHub issue search. Check if the issue has already been reported.
  2. Check if the issue has been fixed. Try to reproduce it using the latest master or development branch in the repository.
  3. Provide environment details. Provide your operating system, browser(s), jQuery version, Bootstrap version, and bootstrap-select version.
  4. Create an isolated and reproducible test case. Create a reduced test case.
  5. Include a live example. Make use of jsFiddle or jsBin to share your isolated test cases.

@louis-marchant
Copy link

I have the exact same issue. Upon removing the "selectpicker" class, the form data sends fine, adding the class again stops the data being sent with the form.

@emresaracoglu
Copy link

I have the exact same issue, .

@caseyjhol
Copy link
Member

See guidelines for contributing.

Bug reports

A bug is a demonstrable problem that is caused by the code in the repository.
Good bug reports are extremely helpful - thank you!

Guidelines for bug reports:

  1. Use the GitHub issue search. Check if the issue has already been reported.
  2. Check if the issue has been fixed. Try to reproduce it using the latest master or development branch in the repository.
  3. Provide environment details. Provide your operating system, browser(s), jQuery version, Bootstrap version, and bootstrap-select version.
  4. Create an isolated and reproducible test case. Create a reduced test case.
  5. Include a live example. Make use of jsFiddle or jsBin to share your isolated test cases.

@nate-robo
Copy link

nate-robo commented Aug 31, 2016

Same issue, bump

The form doesn't pass any data, using Django the server spits an error "This field is required" indicating absolutely nothing was passed from the form fields when the submit button was clicked. Only happens when I'm using the selectpicker class on a ModelChoiceForm and DateField.

Once I remove the selectpicker class and use the out of the box selects the issue is resolved.

Form class
`
class DonationForm(MySiteForm):

donor = forms.ModelChoiceField(queryset=Donor.objects.all(), widget=forms.Select(attrs={'class': 'selectpicker', 'data-live-search':'true', 'data-width':'350px'}))
date = forms.DateField(widget=SelectDateWidget(attrs={'class':'selectpicker', 'data-width':'114px'}))


class Meta:
    model = Donation
    fields = ('donor', 'date', 'type', 'est_val', 'description')`

`
def donation_new(request):

if request.method == "POST":
    form = DonationForm(request.POST)
    if form.is_valid():
        donation = form.save(commit=False)
        #Manual form work here
        form.save()
        messages.success(request, 'New Donation succesfully added to database')
        return redirect('donations')
    else:
        print form.errors
else:
    form = DonationForm()
return render(request, 'habitatApp/donation_new.html', {'form': form})`

The HTML:
`

<tr>

  <td><label for="id_donor">Donor</label>  <span class="asterik">* <span></td>

  <td>
      <select class="selectpicker" data-live-search="true" data-width="350px" id="id_donor" name="donor">

     <option value="" selected="selected">---------</option>

     <option value="3">Alec Robinson</option>

     <option value="4">Robinson Lyons</option>

     <option value="5">Reed Baum</option>

    </select> 
  </td>
  <td> </td>
  </tr>
  </div>`

@caseyjhol
Copy link
Member

Browser? OS? Version of bootstrap-select? Example? Any more information about your setup? I've tested this and can't recreate it. If anybody can follow any of the guidelines for contributing, I'll be happy to look into this further.

@nate-robo
Copy link

nate-robo commented Sep 1, 2016

Chrome, OSX 10.11.1, bootstrap-select v 1.11.0

I'm using Django

The form.error output is as follows:
Error: This field is required
Error: this field is required
This makes sense for the Django model because when I check the
POST command after the submit button is clicked by the user, these two fields are showing up empty. The data from the selectpicker isn't being passed to the POST command despite selections being made. When I remove the class='selectpicker' from the html select, there is no longer issues passing the data.

Let me know if there's any other info you'd like

@nate-robo
Copy link

Curious if you're still looking into this, please let me know. If you'd like me to submit some more details also more than willing, I couldn't follow your guidelines as it's impossible to create a JsFiddle that mimics the behavior in the Django framework.

@caseyjhol caseyjhol reopened this Sep 3, 2016
@caseyjhol
Copy link
Member

Would you be willing to email me a link to your site so I can demo it?

@nate-robo
Copy link

nate-robo commented Sep 7, 2016

My site is running locally e.g. (127.0.01/...), I could zip up my entire project and have you run it locally to debug it if you'd like?

@byrman
Copy link

byrman commented Oct 2, 2016

I ran into the same problem using Django and had a hard time debugging it. It appeared to be a typo in my template: I didn't properly close a table tag and used <table> instead of </table>. This wasn't so obvious, because the page layout still looked all right. Adding just 1 character solved my problem. Perhaps you should double check your HTML.

@caseyjhol
Copy link
Member

@carlituxman So, the form submits properly when the elements are not inside a table? Is it possible you have the same issue as @byrman? I really can't think of anything that would be causing this issue other than an error in your HTML.

@carlituxman
Copy link

I test some options but only fails inside a table.
Without table it works

@caseyjhol
Copy link
Member

What about other elements? For example, if you leave the code as is, but use a div tag instead of a table tag?

@carlituxman
Copy link

carlituxman commented Oct 26, 2016

This is my code:

<table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th class='col-xs-4'>Product</th>
                    <th class='col-xs-4'>Days</th>
                    <th class='col-xs-2'></th>
                </tr>
            </thead>

            <tbody>
                @foreach($data->products as $prod)
                    {!! Form::model($prod, array('files'=> true,'route' => array('myroute', $data->id))) !!}
                        {!! Form::hidden('producto_id',$prod->pivot->id) !!}
                        <tr>
                            <td>{{$prod->name}}</td>
                            <td>

                                {!! Form::select('dias[]', ['Lunes','Martes','Miércoles'], null, array('class'=> 'form-control selectpicker','multiple') )!!}

                            </td>
                            <td>
                                <button type="submit" class="btn btn-info btn-sm"><i class="fa fa-refresh"></i></button>
                            </td>
                        </tr>
                    {!! Form::close() !!}
                @endforeach
            </tbody>
        </table>

if quit the table then works, inside the table not send the post

@carlituxman
Copy link

I add name attribute to the form and Its not working

2016-11-14 15:36 GMT+01:00 brizov43 notifications@github.com:

This happens when you do not add a name attribute of the form: ". Note the
square bracket, it's important...


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
#1342 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/ACBJyqiANds8LXlM-FrKPEOtbDCIHPWtks5q-HHRgaJpZM4H5WIT
.

Carlos Jiménez Mora
INFORMATIK SOLUCIONES
Tlf: 950 42 62 68 - Serón (Almería)
@carlituxman https://twitter.com/carlituxman - carlos@informatik.es

Este mensaje y sus anexos pueden contener información confidencial, por lo
que se informa de que su uso no autorizado está prohibido por la ley. Si
Vd. considera que no es el destinatario pretendido por el remitente o no
desea recibir información comercial, por favor póngalo en su conocimiento
por esta misma vía o por cualquier otro medio y elimine esta comunicación y
los anexos de su sistema, sin copiar, remitir o revelar los contenidos del
mismo a cualquier otra persona. Cualquier información, opinión, conclusión,
recomendación, etc. contenida en el presente mensaje no relacionada con la
actividad empresarial de INFORMATIK BC SOLUCIONES S.L. y/o emitida por
persona sin capacidad para ello, deberá considerarse como no proporcionada
ni aprobada por INFORMATIK BC SOLUCIONES S.L. pone los medios a su alcance
para garantizar la seguridad y ausencia de errores en la correspondencia
electrónica, pero no puede asegurar la inexistencia de virus o la no
alteración de los documentos transmitidos electrónicamente, por lo que
declina cualquier responsabilidad a este respecto.

@brizov43
Copy link

brizov43 commented Nov 14, 2016

@carlituxman Hi, I actually removed my post, because I noticed the others had the right name. It seems it's another problem.
You should still check

  • <select name="somename[]">
  • <option value="uniqueValue">
  • if the fields are inside the form (between the form tags)
  • when the fields are in a <fieldset> tag don't forget the form="yourForm" attribute
    I worked through my problem with these steps.

@miranos
Copy link

miranos commented Dec 1, 2016

Any one solved this issue !
I have the exactly same issue as you, someone found a solution about this please ?

@ka-sh
Copy link

ka-sh commented Jan 9, 2017

Guys I had the same issue later to realize that I am missing the name attribute, I have attached a sample code and it is working fine on both browsers Firefox 50.1.0, and Chrome 55.0.2883.87 (64-bit) running ubuntu 64-bit 16.04 LTS.
http://stackoverflow.com/questions/27216187/bootstrap-select-plugin-how-to-submit-the-form-with-it
<form role="form" id="form" action="/action" method="post">
<table class="table"
<tr>
<th>
<select class="selectpicker form-control" title="colour" id="type" name="colour">
<option>red</option>
<option>black</option>
/select>
</th>
</tr>
</table>
<div class="col-sm-12">
<button type="submit" class="btn btn-success btn-block" id="add_colour">ADD</button>
</div>
</form>

@toramanlis
Copy link

Possible solution for the table element issue. Apparently nesting a form element inside a table is not proper nesting. I mean:

<table>
    <form>
        <thead>
            <th><select ...>...</select></th>
        </thead>
    </form>
</table>

This is not nested properly. so the browser takes all the input, select, radio, checkbox etc with the form and consider they are all right before the thead.

Then the problem starts. bootstrap-select takes our select element, constructs its new markup and returns them just where it found them which is where the select element was. However that is not in a form element as far as the browser is concerned.

Now you end up with a perfectly working select tool which has nothing to do with the form you submit. Thus no data is sent with the form.

@rstegeby
Copy link

I have the same problem.. everything in the form works great but when I only add the one class called "selectpicker" it just do not send the selected option value in the $_POST-variable.. nada.. removing the class makes it work again and I get my desired variable in the $_POST and I can use it as before.

Very strange bug indeed. To bad, I just found the plugin and seems like a good one, except that I can't really use it.

Using Chrome 56.0.2924.87

@caseyjhol
Copy link
Member

Can you link me to an example?

@robertbarros
Copy link

I'm having similar issue. But the problem occur only if you select your option with mouse click without type nothing. It sounds like the $post will be post ONLY if you type something otherwise it will consider as Null if you avoid the keyboard and look for your option scrolling down and select with mouse click.

@phantomlinux
Copy link

Same issue, I just use request.POST.getList for the moment. Append prefix in the value if sub group is needed. Then filter the list on your views.

@costra
Copy link
Contributor

costra commented Feb 24, 2019

I had the same issue. The problem is when you have crossed tags over form tag.
Like this:
<div>
<form ...>
</div>
</form>

@You2s
Copy link

You2s commented Feb 27, 2019

Same Issue, did you find out where the bug came from?
I don't use any tables. My form works perfectly without the use of the "selectpicker" class but once I add this class, the data is no longer sent in POST. I have tested with several browsers I think the problem comes from the JS code of the library

@GUTIERRES-RS
Copy link

GUTIERRES-RS commented Aug 14, 2019

O problema e a hierarquia dos elementos, pra funcionar dentro de uma tabela tem que colocar o select dentro de uma <-tr-><-td->Coloque aqui o select que o "js" acha ele<-/td-><-/tr->
;)

@phillf
Copy link

phillf commented Dec 7, 2019

I seem to be having a similar issue. Upon selection of value of select the workflow is initiated and completes successfully but no data is submitted therefor nothing is altered in the database.

CODE: https://repo.opencad.io/users/pfernandes/repos/opencad-app/browse/oc-apps/mdt.php
BS VERSION: 4.3.1
BS SELECT VERSION: 1.13.9

If you would like a demo site I can quickly stand one up. Please let me know.

@caseyjhol

@caseyjhol
Copy link
Member

@phillf If you could set up a demo that would be great. It would be amazing to finally get this one resolved.

@phillf
Copy link

phillf commented Dec 11, 2019

@caseyjhol, please check your inbox for details of the demo site.

@phillf
Copy link

phillf commented Dec 12, 2019

This turned out not be an issue with selectpicker but a problem with the PHP function responsible for stripping the classes before the "unit" identifier is passed.

Thank you @caseyjhol!

@mehorter
Copy link

This was driving me crazy as well. From hints gleaned in this thread I solved the issue.

My <form> - </form> tags crossed over various <div> tags that had the col, row and container classes.

In other words, I had nested <form> and </form> tags within different <div> hierarchies.

@ordimans
Copy link

ordimans commented Mar 10, 2020

I have the problem too.
It's strange, because i already used on another page, and this time, it doesn't work....

My code :

<body class="container">
    <div class="form-group">
    <form action="/close" method="post">
    <input type="hidden" name="method" value="filter"/>
    <div class="form-row">
      <div class="col-2">
        <input type="text" class="form-control"  name="login" id="login" value="" class="sr-only" placeholder="Pseudo ">
      </div>
      <div class="col-2">
        <input type="text" class="form-control"  name="customer" id="customer" value="" class="sr-only" placeholder="customer">
      </div>
      <div class="col-2">
        <select class="browser-default selectpicker" name="state" id="state" data-live-search="true" multiple>               
          <option valeur="0" selected>--state--</option>
           <% globalData.etat.forEach(function(data) { %>
              <option value="<%= data.valeur %>"  > <%= data.libelle %> </option>
          <% }); %>
      </select>
      </div>
      <button type="submit" class="btn btn-primary">Filter</button>        
  </div>
  </form>
</div>

Some one have a fix or an idea ??

It work if i remove select picker...

EDIT: I solved....

It's strange, but i had a problem with order tag...

and don't know how (i am not expert with HTML), but my select appear above the thead.... So now i change and put select before table and post data is OK.... it's very strange...

@mehorter
Copy link

Does moving the <button type="submit" class="btn btn-primary">Filter</button> below the </div> just above the </form> help?

@caseyjhol
Copy link
Member

Looks like every incidence of this issue has been the result of improper code formatting (e.g. not properly closing a tag) or by placing a form inside a table. I'll see if I can recreate or if there's anything I can do to fix this, but there might not be anything that can be done on bootstrap-select's side of things.

@LasanthaSudeera
Copy link

Facing the same issue, anything to overcome this?

@daniel-r-cross
Copy link

Hi all - I managed to solve this by specifying the form in the select input (form="form123") HTH

caseyjhol added a commit that referenced this issue May 20, 2020
…ect gets moved inside newElement, its previously associated form gets unlinked (so it's not included when the form is submitted) (#1342)
@lucamariani
Copy link

@carlituxman So, the form submits properly when the elements are not inside a table? Is it possible you have the same issue as @byrman? I really can't think of anything that would be causing this issue other than an error in your HTML.

Same issue within an HTML table. Moving the form outside the table works fine!!

@caseyjhol
Copy link
Member

Released in v1.13.18!

@EduardoNave
Copy link

@carlituxman Hi, I actually removed my post, because I noticed the others had the right name. It seems it's another problem.
You should still check

  • <select name="somename[]">
  • <option value="uniqueValue">
  • if the fields are inside the form (between the form tags)
  • when the fields are in a <fieldset> tag don't forget the form="yourForm" attribute
    I worked through my problem with these steps.

A M A Z I N G

@ClemensRau1337
Copy link

ClemensRau1337 commented Dec 27, 2020

still the same issue with the newest 1.13.18 release

image

@caseyjhol
Copy link
Member

You've got two elements with the same ID (test), which isn't allowed. Try changing one of the ID attributes.

@BlairCurrey
Copy link

BlairCurrey commented Feb 2, 2021

Hi all - I managed to solve this by specifying the form in the select input (form="form123") HTH

@daniel-r-cross thanks for sharing - this is a good solution. This worked for me. I also have multiple forms so it was necessary to use a unique id, otherwise it returned the select values for all forms. This also allowed me to keep the form within the table.

This was a real head-scratcher - thank you everyone for sharing your experience.

@daparicio33
Copy link

I was Facing same the problem 😟 after banging head with a head ache !FINALLY got solution at first i was using <-form->/ tag over the <-tr-> but when i placed from tag inside <-tr-> i.e over the selectpicker it worked for me (quite strange 😖 )

So what i changed!!

from :

<-form method="post" action="target"> <-tr> <-td><-select class="selectpicker" name="select[]" multiple> <-/tr> <-/form>

TO: <-tr> <-td> <-form method="post" action="target"> <-select class="selectpicker" name="select[]" multiple> <-/form> <-/td> <-/tr-> 👍 😄

thx work for meee

@AkhmadRamadani
Copy link

AkhmadRamadani commented Apr 21, 2022

I did it guys, just specify the form id for <select> and <input submit>

@sadashivdalvi
Copy link

I think it's a lot of comment reading and a lot of trial and error.

I got it fixed because of one comment https://stackoverflow.com/questions/27216187/bootstrap-select-plugin-how-to-submit-the-form-with-it

All it needs a name to the select tag. Can anyone add this to the documentation, it was crazy searching this.

Thanks,
Sadashiv

@LeonardoYF
Copy link

Para aquellos que les sucedio el problema del selectpickert de la libreria de boostrap, puede generar problemas en el envio del formulario al backend, por lo que buscando alguna otra alternativa que funcione igual o parecido, encontre https://danisanchez.net/crear-un-select-con-buscador-integrado-gracias-a-select2/ , esta libreria de Jquery, que es bastante parecida e igual de buena, SALUDOS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests