How to ensure a <select> form field is submi

2019-01-04 17:26发布

I have a select form field that I want to mark as "readonly", as in the user cannot modify the value, but the value is still submitted with the form. Using the disabled attribute prevents the user from changing the value, but does not submit the value with the form.

The readonly attribute is only available for input and textarea fields, but that's basically what I want. Is there any way to get that working?

Two possibilities I'm considering include:

  • Instead of disabling the select, disable all of the options and use CSS to gray out the select so it looks like its disabled.
  • Add a click event handler to the submit button so that it enables all of the disabled dropdown menus before submitting the form.

15条回答
做个烂人
2楼-- · 2019-01-04 17:50

I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled. This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)

Shameless plug: https://github.com/Jezternz/jq-disabled-inputs

查看更多
女痞
3楼-- · 2019-01-04 17:51

Just add a line before submit.

$("#XYZ").removeAttr("disabled");

查看更多
戒情不戒烟
4楼-- · 2019-01-04 17:53

I found a workable solution: remove all the elements except the selected one. You can then change the style to something that looks disabled as well. Using jQuery:

jQuery(function($) {
    $('form').submit(function(){
        $('select option:not(:selected)', this).remove();
    });
});
查看更多
登录 后发表回答