简体   繁体   中英

Javascript / jQuery: How to prevent active input field from being changed?

how do I prevent the user to change the value in an input field (which contains a certain value to be copied into the clipboard) without using disabled="true"? The text should be selected once the user clicks in the field (that's working already) but entering anything should have no effect.

Thanks

jQuery('input.autoselect[value]').focus(function() { jQuery(this).select(); });

只需在输入的html中读取即可阻止用户编辑输入。

<input readonly="readonly" type="text" value="You can't edit me!"/>

I think this should work:

var val = jQuery('input.autoselect[value]').val();
jQuery('input.autoselect[value]').change( function(){
   jQuery(this).val(val);
});

Or possibly (not sure)

jQuery('input.autoselect[value]').keydown(function(){
   return false;
});

Based on Pim's answer , how about this?

jQuery(document).ready(function(){

    jQuery("input.readonly").each(function(){
           jQuery(this).attr("savedVal", jQuery(this).val());
    });

    jQuery("input.readonly").change(function(){
           jQuery(this).val(jQuery(this).attr("savedVal"));
    });

});

(completely untested, but it demonstrates the idea...)

<script>
document.getElementById("newval").readOnly = true;
</script>

Watch for the capital "O" in readonly...

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