简体   繁体   中英

Prefill field value and readonly

I have a form with several fields and I need to customize some fields using javascript for allow me to:

  1. prefill the value "New York" for the field "city"

  2. make the field "email" readonly

  3. prefill AND make readonly the field "country"

To get the result of point 1, I used this code which works well:

<script type="text/javascript">function on_form_loaded(event) {
if (event=='reserve')
document.getElementById('city').setAttribute("value", "New York");
}</script>

For get the result of point 2, I used this code which works well:

<script type="text/javascript">function on_form_loaded(event) {
if (event=='reserve')
document.getElementById('email').readOnly=true;
}</script>

But now I don't see how to "mix" prefill/readonly paramters for get the result of point 3.

Someone can help ?

In addition I would like shorten the code for avoid to include a single javascript for each field. I make some test but without success. if you can give me some example...

I'm not sure what you're missing but try this

var country = document.getElementById('country');
country.value = "USA";
country.readOnly = true;

As jimjimmy1985 mentioned in the comments above, you can also do this in markup

<input name="country" id="country" value="USA" readonly>

Assuming You're using 'on...="on_form_loaded"' as attribute in the form tag and having no problem to add jQuery, You may try:

<script type="text/javascript">
jQuery('#ID_OF_YOUR_FORM').ready( function(event) {
 if (event=='reserve') {
    var form_object = jQuery(this);
    form_object.find('#city').value('New York').end()
               .find('#country').value('USA').end()
               .find('#country, #email').attr('readonly', true);      
  }
});
</script>

Where ID_OF_YOUR_FORM has to be replaced by Your forms individual ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM