HTML form read only SELECT tag/input



Problems:

  • form html - According to HTML specs, the select tag in HTML doesn't have a readonly attribute, only a disabled attribute. So if you want to keep the user from changing the dropdown, you have to use disabled.
  • The only problem is that disabled HTML form inputs don't get included in the POST / GET data.
  • What's the best way to emulate the read only attribute for a select tag, and still get the POST data?

Solution 1:

  • html form action - You should keep the select element disabled but also add another hidden input with the same name and value.
  • If you reenable your SELECT, you should copy its value to the hidden input in an onchange event and disable (or remove) the hidden input.

Here is a html form example :

$('#mainform').submit(function() {
    $('#formdata_container').show();
    $('#formdata').html($(this).serialize());
    return false;
});

$('#enableselect').click(function() {
    $('#mainform input[name=animal]')
        .attr("disabled", true);
    
    $('#animal-select')
        .attr('disabled', false)
    	.attr('name', 'animal');
    
    $('#enableselect').hide();
    return false;
});
#formdata_container {
    padding: 10px;
}

html form input :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <form id="mainform">
        <select id="animal-select" disabled="true">
            <option value="cat" selected>Cat</option>
            <option value="dog">Dog</option>
            <option value="hamster">Hamster</option>
        </select>
        <input type="hidden" name="animal" value="cat"/>
        <button id="enableselect">Enable</button>
<select name="color">
            <option value="blue" selected>Blue</option>
            <option value="green">Green</option>
            <option value="red">Red</option>
        </select>

        <input type="submit"/>
    </form>
</div>

<div id="formdata_container" style="display:none">
    <div>Submitted data:</div>
    <div id="formdata">
    </div>
</div>

Solution 2:

  • We could also use this demo
  • Disable all except the selected option

html code :

<select>
<option disabled="disabled">1</option>
<option selected="selected">2</option>
<option disabled="disabled">3</option>
</select>
  • This way the dropdown still works (and submits its value) but the user can not select another value.

Solutions 3:

This is one way for using Simple jQuery code

jQuery('select.readonly option:not(:selected)').attr('disabled',true);

Solution 4:

The another way of doing a readOnly attribute to a select element is by using css you can do the following:

Jquery code :

$('#selection').css('pointer-events','none');


Related Searches to HTML form read only SELECT tag/input