Reputation: 61
What would be the easiest way to have the color of a text field in an ASP .NET MVC form changed according to a value just entered BEFORE form submission.
The color to be used is returned by a DB query.
For example:
The query returns Red if the number enter in the field is lower then the Quantity registered for the item in the DB.
Thanks
Upvotes: 0
Views: 216
Reputation: 11977
If it doesn't impose any security risk, it would be best to cache the available quantity for the products, instead to go to the server for validation. This way, the UI will be more responsive - and the user experience will be better. So, basically,
// JS
var availableQuantities = [10, 15, 30];
$(".the-imput-control").blur(function () {
var value = $(this).val();
var productIndex = $(this).parent().children().index(this); // sort of
$(this).toggleClass('invalid', (availableQuantities[productIndex] < value));
});
// CSS
.invalid { color: red; }
Upvotes: 0
Reputation: 650
You would like to have an event onclick for the submit button or on changing the quantity to retrieve the quantity of the product.
You can also load a color in the beginning but the stock may change during the user's input.
For example
As I understood you would not have a postback if the amount in db is lower than the amount ordered.... but consider that users may not have javascript turned on, you should also implement in server side.
Personally I would just do it on server side, because on client side is just an extra functionality which you cannot rely on.
Upvotes: 0
Reputation: 16651
You can do it like in the example below, using jQuery :
//bind a function to the blur even of the text field
$("#the-imput-control").blur(function () {
var value = this.val();
//send the value to the server and then process the result.
$.getJSON("yourUrl", { key: value }, function(data) {
//return a json object with a property "color"
//and use its value to set the text field's color
$("#the-imput-control").css("color", data.color);
});
//you can of course use another ajax function depending on your needs.
});
Upvotes: 1