2

I have the following text box input code. I do not have access to it to add the default value to it so i used this Jquery code to add the value and then disable the input but it doesn't send the added value. How would I add the value but not allow them to change it. I was going to use "hidden" but I want them to see it just not able to change it.

$("input[type='text'][name='ShipCity']").val('Madison').attr('disabled', 'disabled');



<input type="text" style="background-color: rgb(255, 255, 0);" value="" name="ShipCity" maxlength="45" size="25">
user357034
  • 10,731
  • 19
  • 58
  • 72

1 Answers1

2

EDIT: Another option would be to disable the fields, and enable them when you submit the form:

$("input[type='text'][name='ShipCity']").val('Madison').attr('disabled', 'disabled');

$("form").submit(function() {
    $(':input', this).removeAttr('disabled');
});

I think this should work anyway.


Original answer:

This will return false; on keypress events.

Also, it stores the default value using jQuery's .data(), and checks that value in a blur event handler.

The reason for this is that it is possible to enter a new value without a keypress event (via the GUI menus).

$("input[type='text'][name='ShipCity']")
    .val('Madison')                  // give default value
    .data('defaultVal', 'Madison')   // remember default value
    .keypress(function() {
        return false;                // prevent keypress events
    })
    .blur(function() {
        if(this.value !== $.data(this, 'defaultVal')) // set back to the default
            this.value = $.data(this, 'defaultVal');  //   if it was changed via
    });                                               //   the GUI menu

EDIT:

Here's a version that will let you do it so that you only need to type the default value once. (It is otherwise identical.)

Example: http://jsfiddle.net/cdzuR/

$("input[type='text'][name='ShipCity']")
    .data('defaultVal', 'Madison')  // You only need to give the default once
    .val(function() { return $.data(this, 'defaultVal'); })
    .keypress(function() {
        return false;
    })
    .blur(function() {
        if(this.value !== $.data(this, 'defaultVal'))
            this.value = $.data(this, 'defaultVal');
    });
user113716
  • 318,772
  • 63
  • 451
  • 440
  • Worked just like your last answer!!! :) It does work but will allow them to paste text into the box but will revert back to the default text on blur so I guess its fine. – user357034 Sep 09 '10 at 01:48
  • @user - Yeah, with regard to pasting the text, there really isn't any way of preventing that without disabling the input. One other option would be do disable it, then enable it just before you submit the form. I'll add that to my answer. – user113716 Sep 09 '10 at 02:11
  • While the 1st and second answer worked great the 3rd was really the greatest and the simplest answer and this way they cannot even mess with the text box in any way. THX again!!! – user357034 Sep 09 '10 at 04:17