I am trying to limit my textbox to include max 500 character, for example i want to receive a question from the user but it the max length is 500 and how can i show the number of how many character left while writing ?
this is my code in the view, but i don't know its not working, i have tried various ways!
<li>
#Html.LabelFor(m => m.TeacherQuestion, new { maxlength = 500 })
#Html.TextBoxFor(m => m.TeacherQuestion , new { maxlength = 500})
</li>
There is no built-in element or attribute for this - you need to use Javascript.
Assign an ID to your input and add a new element to hold the remaining character count
#Html.TextBoxFor(m =>
m.TeacherQuestion, new { id = "questionInput", maxlength = 500 })
<span id="charsLeft"></span>
Next add a reference to jQuery and add the following Javascript to your layout view:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(function () {
$("#questionInput").keyup(function () {
var charsLeft = $(this).attr("maxlength") - $(this).val().length;
$("#charsLeft").text(charsLeft + " characters left");
});
});
</script>
(If you need to include the script in a normal view, please refer to this answer for guidance.)
The result should look something like this:
Related
It is the first time that I use Kendo and I am quite lost, in this case I have a grid in the form of a table and there are fields that I do not show with ClientTemplate and depending on whether the ServiceStatusId field returns 5 I have to cross out the text and if not, leave it as it is. But I try to put a conditional for the case of the style and it doesn't work for me. I have tried several ways and I can't find a way to make a conditional to evaluate that. If I put it this way it will let me, but I need to indicate the conditional
style = "text-decoration:line-through;"
And this is how I have it right now:
<div>
#(Html.Kendo().Grid<Faculty.Web.Models.Ces.MyTasksProgramFilterViewModel>
()
.Name("program_session_services_grid")
.AutoBind(true)
.Columns(columns =>
{
columns.Select().Width(50)
.HeaderHtmlAttributes(new { #class = "grid_SelectColumn" })
.HtmlAttributes(new { #class = "grid_SelectColumn" });
columns.Bound(c => c.ProviderLiteral).HtmlAttributes(new { #class = "Assignment_Courses_Grid_Item_Center FontSize10 ", style = $"\\# if (ServiceStatusId==5) {{ \\# '" + "text-decoration:line-through;" + "' \\# }} \\#" })
.Title(Resources.Ces.MyTasksPrograms_Grid_Header_Provider)
.HeaderHtmlAttributes(new { #class = "Assignment_Courses_Grid_Header_Center " });
Any suggestion, help or advice is good for me, I already tell you that I have never touched Kendo until now and I need to apply this conditional and I don't know how to do it so that it detects it correctly and works.
No you can't use a template in the .HtmlAttributes. There's a few different ways you can solve this.
Probably the best way is to apply a template on the content.
columns.Bound(c => c.ProviderLiteral).ClientTemplate($"#=GetKendoTemplate(data,'ProviderLiteralTemplate')#");
Where GetKendoTemplate is a javascript method
function GetKendoTemplate(data, templateName) {
var templateObj = $('#' + templateName).html();
var template = kendo.template(templateObj);
return template(data);
}
And ProviderLiteralTemplate is a kendo template
<script id="ProviderLiteralTemplate" type="text/x-kendo-template">
<div style="# (ServiceStatusId==5) ? 'text-decoration:line-through;' : ''">
<span>#=ProviderLiteral#</span>
</div>
</script>
I am having a Controller Calculations where I have a property called Formula. The main idea behind the Calculation is to perform operations using objects from other tables in the Database , here for instance SetValues.
What I am trying to achieve
I have a textbox for entering the Formula. I want to make sure that the variables used in the Formula are existing in the database. I can display the names of all the available rows in the table SetValues. I would like to make the values being displayed from the Setvalues click-able so that the value being clicked would be displayed on the textbox. I will keep a table with the mathematical operators as well which would also work in the same way. How can I make the TextBox for Formula the way I want? And how can I make the Names to be entered into the TextBox when clicked.
When the formula has been saved I want to use the formula to perform calculations based on the values of the SetValues(Assume SetValue has properties Name and Values(int)). I understand that I need to parse the Formula to perform the calculation which I have not yet tried, but could find other examples where the same has been performed. I have done something similar but with a Calculation string with numbers alone. I have not done something that would parse a formula and then assign values to it. Is it possible to achieve the parsing?
Calculation View
#foreach(var item in ViewBag.SetValues
{
<p>#item.Name</p>
}
#Html.LabelFor(model => model.CalculationName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.CalculationName, new { htmlAttributes = new { #class = "form-control" } })
#Html.LabelFor(model => model.CalculationFormula, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.CalculationFormula, new { htmlAttributes = new { #class = "form-control" } })
<input type="submit" value="Create" class="btn btn-default" />
In a ViewBag I have passed the SetValue and the elements are displayed.
The Model classes and Controller are not relevant for the output I guess. But if it is required comment. Further details can be added.
Update : adding Wireframe sample
To solve your question regarding to adding the formula to the formula textbox when clicked. Here is some sample code. I use jQuery with a double click event.
HTML
<b>Formulas:</b><br/>
<i>Double click to append the formula.</i></br>
<select id="formulas" size="5">
<option>d_0</option>
<option>v_fix</option>
<option>f_Fc</option>
<option>a_sc</option>
</select>
<select id="operands" size="5">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<br/>
<span id="message" style="color: red"></span>
<hr/>
<b>Formula:</b><br/>
<textarea id="formula"></textarea>
JavaScript
$(document.ready( function() {
var formulas = $("#formulas");
var formula = $("#formula");
var operands = $("#operands");
var message = $("#message");
var expectFormula = true;
formulas.dblclick(function() {
if(expectFormula == true) {
var currentFormula = formula.val();
var appendFormula = formulas.val();
var newFormula = (currentFormula + " " + appendFormula).trim();
formula.val(newFormula);
expectFormula = false;
return;
}
message.html("Operand expected.");
});
operands.dblclick(function() {
if(expectFormula == false) {
var currentFormula = formula.val();
var appendFormula = operands.val();
var newFormula = (currentFormula + " " + appendFormula).trim();
formula.val(newFormula);
expectFormula = true;
return;
}
message.html("Formula expected.");
});
});
JSFiddle
https://jsfiddle.net/L1r3xdvq/1/
I am by no means a JavaScript expert, but this should demonstrate on how to do this.
Do note that you have to double check the user input on the server, even though it is created with JavaScript, it is possible to enter whatever you want and send this as formula.
I have a field called ReclaimTotalAmount that displays a value from a c# model.
<div class="container-left">
Reclaim Total: <span data-bind='text: model.ReclaimTotalAmount'></span>
</div>
And I also have a field that displays the value of the Sum of fields:
<div class="container-left">
Countered Total:<span data-bind='text: model.CounteredTotalAmount'></span>
</div>
To get the CounteredTotalAmount I use the following
self.model.CounteredTotalAmount = ko.computed(function () {
var SumCounterTotals = 0;
for (var i = 0; i < self.model.CounterReclaimViewModels().length; i++) {
SumCounterTotals += (
parseFloat(self.model.CounterReclaimViewModels()[i].CounteredTimeAmount())
+ parseFloat(self.model.CounterReclaimViewModels()[i].CounteredMileAmount())
+ parseFloat(self.model.CounterReclaimViewModels()[i].CounteredAppurtenanceAmount())
)
}
So I need to check weather the Countered total is greater than the ReclaimTotal. I tried this:
I created an extension
self.model.CounteredTotalAmount.extend({
greaterThan: { params: self.model.ReclaimTotalAmount, message: "Car number high must be greater than the low." }
});
then this is the function
ko.validation.rules['greaterThan'] = {
validator: function (val, other) {
if (val != null && val != "" && other != null) {
var first = parseInt(val);
var second = parseInt(ko.unwrap(other));
if (!isNaN(first) && !isNaN(second)) {
return first > second;
}
}
return true;
},
message: 'Must be greater than or equal to the other value'
};
everything works except the validation. I am not able to generate an error message if the Countered Total is greater than the Reclaim total...
Thanks
Multiple things could go wrong, but because you haven't' posted a complete example only code fragments you need to check the following things:
Because you are creating a custom validator you need to call ko.validation.registerExtenders(); before you want to use it for the first time.
the KO .extend({ }) returns the extended observable so you need to override the existing property with the result:
self.CounteredTotalAmount = self.CounteredTotalAmount.extend({
greaterThan: {
params: self.ReclaimTotalAmount,
message: "Car number high must be greater than the low."
}
});
Because KO validation only overrides the value and checked binding to automatically display the error message. So you need to use the validationMessage binding to display your error because you are using the text binding here:
<div class="container-left">
Countered Total:<span data-bind='text: CounteredTotalAmount'></span>
<span data-bind="validationMessage: CounteredTotalAmount"></span>
</div>
Here is a working JSFiddle with the simplified version of your code.
I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
I am using also Entity Framework and Code First Method.
In a view, I have a DropDownList and a button and a TextArea.
When I click on the button, the selected value in the DropDownList is added to the TextArea.
The values added are sperated by a space " " and that with using script.
This is the code of the view :
<fieldset><legend>Gestion</legend>
<div>
<%:Html.Label("Fonction :")%>
<%: Html.DropDownList("SelectedFonction",null, new{ id = "ff" })%></div>
<br />
<div><input type="button" value="Ajouter" id="aj" onclick="addtext()"/></div>
<br />
<div>
<textarea id="tt" cols="10" name="S1" rows="8" readonly="true"></textarea>
</div>
</fieldset>
<script language="javascript" type="text/javascript">
var storedValues = [];
function addtext() {
var ff = document.getElementById('ff');
var tt = document.getElementById('tt');
var selectedValue = ff.options[ff.selectedIndex].value + " ";
if (storedValues.indexOf(selectedValue) === -1) {
storedValues.push(selectedValue)
tt.value = storedValues.join('')
}
}
</script>
This is what i did in the controller :
Fonction_Poste FP = new Fonction_Poste();
var value1 = Request["S1"];
FP.ID_Fonction = value1;
This is code is only available when I entered one value in the TextArea.
When the user add many values, they are stored in the textarea sperated by a space between each others.
So I have to save them in a table, but i didn' t find how to elimnate the spaces.
You can use some other delimiter like the ~ when you are using in javascript. like the one shown below
<script language="javascript" type="text/javascript">
var storedValues = [];
function addtext() {
var ff = document.getElementById('ff');
var tt = document.getElementById('tt');
var selectedValue = ff.options[ff.selectedIndex].value + " ";
if (storedValues.indexOf(selectedValue) === -1) {
storedValues.push(selectedValue)
tt.value = storedValues.join('~')
}
}
In the model, you should then be having like this
public class Fonction_Poste {
public List<string> ID_Fonction {get;set;}
}
In the Action method, you can use like the following,
var value1 = Request["S1"];
FP.ID_Fonction = value1.contains('~')?value1.split('~').ToList():null;
Or else, you can create a javascript array and then push each item into the array and then post the data using JSON to the controller so that it will be automatically bound to the list by default model binding.
Choose the approach that suits your requirement. I would vote for the Javascript array based posting mechanism which will be easy to use and no need to join and split with special characters.
split it by spaces
var requireddata=listdata.split("");
it automatically store the data in a array
I have a WebGrid full of lots of products, and I want to be able to edit the quantity for each row in the web grid and update the Cart table in the database when the textChanged event is raised on the corresponding textbox.
But is this even possible with WebGrid? I have not found anything that would suggest it's possible. I would really appreciate any help at all.
It's possible to attach a change event to the textboxes.
I set my grid up like the following:
#grid.GetHtml(
htmlAttributes: new { cellspacing = "2px", cellpadding = "2px" },
columns: grid.Columns(
grid.Column("Id"),
grid.Column("Description"),
grid.Column("PacketQuantity"),
grid.Column("ThickCover", format: (item) => {
var p = item.Value as MvcApplication1.Models.Product;
return Html.TextBox("ThickCover", p.ThickCover, new { #class = "thickCoverInput", #data_value = p.Id });
}),
grid.Column("ThinCover", format: (item) => {
var p = item.Value as MvcApplication1.Models.Product;
return Html.TextBox("ThickCover", p.ThinCover);
})
)
)
Then I had the following script to wire up the changes:
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script>
$(document).ready(function () {
$('.thickCoverInput').change(function(event) {
alert(event.currentTarget.attributes["data-value"].value);
alert(event.currentTarget.value);
// Here you can post data to an action to update your table
});
});
</script>
When I changed the value in the textbox, I was able to get two alerts. One for the Id of the Product and the other is the new value.
Hope this is what you were looking for.