Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 );
    }
});

Solution 2:

This code will show/hide the relevant HTML code. If you want to eliminate HTML code with pure CSS, that's not possible. CSS only helps styling your content, not removing it from the DOM.

.tag-lg {
  display: none;   
}
.tag-sm {
  display: block;
}
@media (min-width: 100px) and (min-width: 768px) {
  .tag-lg {
     display: block;   
  }
  .tag-sm {
     display: none;
  }
}
<divclass="col-xs-12 hidden-xs tag-lg">
  BIG TEXT
</div><divclass="col-xs-12 visible-xs-block tag-sm">
  Small text
</div>

You can use JQuery to find out the screen size $( window ).width(); and remove the requested elements according to the value you get.

$(document).ready(function() {
    if (( window ).width() > 767){
        $('.tag-sm').remove();
    } 
    else{
        $('.tag-lg').remove();
    }
});

Post a Comment for "Switching Between Different Inputs In A Form Based On @media Width Size"