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
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.
});
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
User loads an order form, quantity in stock: 4, maybe you set the color to orange because it's low...
user fills out the form, some other users order 3 in total, 1 is left in stock
user would like to order 2 items.
user clicks on submit, you have your event checking the quantity and display a message/change the color of textbox
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.
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; }
Related
I've a razor view that shows some jobs data on the basis of some filter like date, description, city, country etc. etc. Data loads in grid and then user can open that specific job.
when user clicks to view some job, it redirects on another page. what I want is that when user comes back on this page again, it should have preserved selected filter and searched data accordingly. I tried tempdata but is of no use. Then i tried cookies but it does not allow me to keep object as it always wants a string as a value.
Any guesses please?
Just use the browser local storage and some javascript code before sending the query to your server.
In the event that trigger the query, just collect the data and store it like this with javascript:
function myFunctionToBeCallBeforeSendingTheQuery() {
var query = {
jobTitle: 'user typed text goes here',
countryId: 'the id goes here'
}
localStorage.setItem('query', query);
}
When the user come back to the page you need to execute the following javascript code after the page get loaded:
$(function() {
var query = localStorage.getItem('query');
if(query != null) {
// here you set the fields of your form with the preview stored data.
}
});
I am working on a feature where in the user could customize the grid (adding, grouping, sorting,aggregation etc) and then can save this as a template.
I am able to retrive the grid options on a button click as below.
JSON.stringify($scope.gridOptions)
however when I am using that as the grid option the grid loads but the grouping, sorting and aggregate is missing. if I analyze the grid option, I still have them.
You can use ui-grids Save and restore functionalities.
Save and Restore
Inject 'ui.grid.saveState' module.
Add 'ui-grid-save-state' to your grid html.
<div id="gridSaveState" ui-grid="gridOptions" ui-grid-save-state class="grid"></div>
Then you can use store the ui-grid states by saving the formatted JSON and also restore from that data.
I think for your case you can use the built-in save and restore state feature of angular-ui-grid. This will mean the grid will bring back the settings you want and display them correctly. You can also control which of these settings (e.g. sorting, filtering etc) are restored, and which not.
http://ui-grid.info/docs/#/tutorial/208_save_state
Some example code
$scope.gridOptions.onRegisterApi = function(gridApi) {
$scope.gridApi = gridApi;
// I store when the user changes a filter, but you could
// instead store on the user clicking a button or any other event
$scope.gridApi.core.on.filterChanged($scope, function() {
var state = gridApi.saveState.save();
SomeServiceOfMineForStoringStuff.storeState(state);
});
}
Later...
var savedState = SomeServiceOfMineForStoringStuff.getState();
if (savedState) {
$scope.gridApi.saveState.restore($scope, savedState);
}
I had a question that was marked as a duplicate but it really didn't answer my question, but it did answer another question that I had so that was great :) I think perhaps I did not explain myself correctly so going to try again. Please keep in mind that I am still relatively new to RoR. My previous question can be found here:
Rails: Select on 1 field returns value to another field
So, let me explain what I am trying to achieve again. I have a table called plans and a table called plan_prices. A plan has many plan prices. I have another table called contracts. A contract can have a plan and a plan price, so the contract table has plan_id and plan_price_id. So here is what I am trying to achieve. When I create a contract I have a select for the plan which returns the plan_id. I also have a select on the plan_price that returns the plan_price_id. This first select has some JS on it to determine when it changes so that the plan_price is filtered accordingly. All this is working just fine. The final piece that I want to do is when I select the plan_price there is a column on that table called price. I want to take this price and default it into the contract.price field which can then be changed if the user deems necessary. I am just having a hard time working out how I would default the plan_price.price value into the contract.price field once the plan_price has been selected. The contract.price field is a simple free entry field and not a select field, since the user can change the price to something else.
Hope the above is clear and I hope that there is someone that can help me out on this.
TIA.
Send an Ajax request on the onchange state of the plan_price field:
:onchange=>"selectPrize(this)"
You will be passing the selected value as a param on your AJAX request
JS Function
function selectPrize(prizeID) {
var dataString ='prize='+prizeID.value;
$.ajax({
type: "GET",
url: "/your_controller/your_controller_method",
data: dataString
});
return false;
};
On your controller, in the selected method, look for the plan prize with the id you got through your ajax request.
#plan_prize = Planprize.where("id = #{params[:prize]}").first
Then create a js.erb file in your folder, depending on the method you've chosen in your controller and do some simple javascript to change the value of the contract_prize:
your_method.js.erb file
$(document.getElementById('contract_prize').value = '<%= #plan_prize.prize %>');
This should work.
I've seen so many posts and examples of people using a DDL placeholder like this...
#Html.DropDownList("lstUsers",(SelectList)ViewBag.UsersList, "--Select User--")
or
#Html.DropDownListFor(u => u.RoleID, Model.RoleList, "Select", new { #id="hi"})
I mean yea these work, but I want the placeholder to disappear after the ddl index changed, and all these do is place dummy text for the 1st index which can then be selected again.
I haven't been able to find an answer for the life of me. I've tried jquery
$("#tb2").attr("placeholder", "--Please Select--"
which works for a textbox, but not a DropDown. I'm using dynamically generated ddl's
Thanks!
That's not how the select element works. That "placeholder" is actually a full-fledged option in the select list. It's value is usually set to an empty string so that if it's still selected on POST, an empty string is posted and will caused an error if the field is expected to have a value. It doesn't just disappear automatically on it's own.
A textbox is entirely different. When placeholder text is placed inside a textbox, it is literally overwritten by user input, hence why it goes away. In HTML5 textboxes now have an actual placeholder attribute, which will show and hide a bit of text based on the focus of the input. The select element has no equivalent, though.
You could potentially do what you want with some additional JavaScript. You would just watch for a change event on the select and if it has a value (not the "placeholder"), then you could remove the first item from the select (which should be the placeholder):
$('#mySelect').on('change', function () {
if ($(this).val() != '') {
var firstChild = $(this).children().eq(0);
if (firstChild.prop('value') == '') firstChild.remove();
}
});
(I'm using jQuery here because doing the same in straight JavaScript would be much more arduous and since you're using ASP.NET MVC, it's a safe bet you're also using jQuery)
I'm using simple_form. How can I have a select menu and a text input and have something like Select or add another.
The app will only take one value, either from the select menu or the text input.
It would also be good to validate to have either one or the other but not both, to avoid user confusion.
Implement what is called a 'combobox' to your simple_form
Jquery UI has a combobox:
http://jqueryui.com/autocomplete/#combobox
something fancier:
http://demos.kendoui.com/web/combobox/index.html
This will get you as far as your combo boxes displaying. I don't think there is a plugin for validating, so you'll have to write the code yourself.
You can try to use a combination of JavaScript and Ruby to solve this. If a user wants to enter a different value then what's available in the dropdown, you should have JS listen to a keydown event in that input and clear the dropdown, i.e.:
$(".input_field").bind('keydown', function() {
$(".select_field").val('0') // this should be a default blank value
});
That will clear the select when a user types. Likewise, you want to clear the input when the user selects from the dropdown, right?
$(".select_field").change(function() {
// Let's only clear the input field if the value is not the default null value
if ( $(this).val() != 0 ) {
$(".input_field").val('');
}
});
This will handle the front-end interactions. In the controller, you'll want to do some additional logic:
def create
object.new(...)
if params[:select] and params[:input]
# Overwrite the select with the input value
object.attribute = params[:input]
end
object.save
end
I assume that you want the input value to supersede the select, therefore if they are most submitted, we can just overwrite the select value with the input value and then continue to save the object.
Is this what you're looking for? Not sure if the inputted value was suppose to create a new object with a relationship or not. Hope this helps.