views:

557

answers:

3

Hi,

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(); });
A: 

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;
});
Pim Jager
Thanks, the second version works but also prevents the user from copying the content (because CMD+C doesn't work either), with the first version I have the problem that it should work for more than 1 field on a page. Any ideas on how to solve this?
ole_berlin
A: 

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...)

Stobor
Example: http://jsbin.com/iqomu (source http://jsbin.com/iqomu/edit )
Stobor
thanks, but scunliffe solved it most elegantly...
ole_berlin
+5  A: 

Uhm,... am I missing something here?

<input readonly="readonly" value="You can't edit me!"/>
       ^^^^^^^^^^^^^^^^^^^
scunliffe
haha, that's so emberassing... You're right, I only tried disabled but not readonly, totaly forgot about it! Thanks!
ole_berlin
+1 I'm an idiot too. :-) I read "without using disabled" and thought "without using attributes".
Stobor
no problem! I just read the question (3 times) and was confused what the trick was. ;-)
scunliffe