Reputation: 10981
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">
Upvotes: 2
Views: 5899
Reputation: 322502
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');
});
Upvotes: 2