Timmy Von Heiss Timmy Von Heiss - 3 months ago 9
CSS Question

switching between different inputs in a form based on @media width size

I have a form. I want to use input A in the form if @media (min-width: 768px), otherwise I want to use input B.

The reason I need to switch inputs is because select.js is buggy in mobile views, however it is awesome on desktop views.

Using

xs-hidden and xs-visible
with bootstrap or using
display: block/none
does not work. The inputs are still in the source code and will still be submitted.

example:

<div class="col-xs-12 hidden-xs tag-lg">
<%= f.input :tag_list, input_html: { class: 'tags', multiple: "multiple" }, collection: ActsAsTaggableOn::Tag.all, value_method: :name, placeholder: '', label: "Tags (seperated by commas):" %>
</div>

<div class="col-xs-12 visible-xs-block tag-sm">
<%= f.label :tag_list, 'Tags (seperated by commas):', class: 'label-tags'%>
<%= f.autocomplete_field :tag_list, autocomplete_tag_name_photos_path, :"data-delimiter" => ', ', 'data-auto-focus' => true, :id_element => '#tag_element' %>
</div>

@media (min-width: 768px) {
.tag-lg {
display: block;
}
.tag-sm {
display: none;
}
}

@media (min-width: 100px) and (max-width: 767px) {
.tag-lg {
display: none;
}
.tag-sm {
display: block;
}
}

Answer

Depending on the browsers you're trying to use, you could use javascript's matchMedia() method to detect the viewport's width (IE11+) or you can use whatever javascript library you're using (jQuery) to disable the controls at certain page widths. Disabled controls don't get posted to the server when a form is submitted.

As you've already discovered, this can't easily be done purely with CSS because the controls will still exist in the DOM even after hiding them.

Note: You probably don't want to outright remove the controls from the DOM because you may need to re-add them based on window resize, device rotation, etc.

Untested example:

$(document).ready(function() {
    if (( window ).width() > 767){
        $('.tag-sm select').prop( "disabled", true );
    } 
    else{
        $('.tag-lg select').prop( "disabled", true );
    }
});
Comments