Reputation: 2143
I have the following:
for (int i = 0; i < Model.Questions.Count; i++)
{
@Html.TextAreaFor(modelItem => Model.Questions[i].AnswerText, new { @class = "form-control multi", rows = "6" })
<div class="remaining-counter">
<p><span id="Counter_@i"></span> characters remaining</p>
</div>
}
I am trying to implement a remaining counter for each text area using jquery simply countable
$('.multi').simplyCountable({
counter: 'How to get the id here',
countType: 'characters',
maxCount: 4000,
strictMax: false,
countDirection: 'down',
thousandSeparator: ',',
});
What I cant figure out is how to get the appropriate id for the counter span that shows the remaining count <span id="Counter_@i"></span>
Upvotes: 1
Views: 185
Reputation: 10683
i don't know if its correct way but you can replace this line in jquery.simplyCountable.js file:-
var counter = $(options.counter);
with
var counter = $(this).next().find('span');
or you can simply do this:-
$(function () {
$('.multi').each(function () {
var id = $(this).next().find('span').attr('id');
$(this).simplyCountable({
counter: '#' + id,
countType: 'characters',
maxCount: 4000,
strictMax: false,
countDirection: 'down',
thousandSeparator: ',',
});
});
});
Upvotes: 1
Reputation: 93561
Sorry, but I feel hacking the plugin to hard-wire a selector is a terrible solution.
Option 1 - no plugin change required
JSFiddle: http://jsfiddle.net/TrueBlueAussie/e82kf82r/7/
You can iterate the .multi
elements and wire them up individually with the matching span IDs like this:
$(function () {
$('.multi').each(function () {
var counter = $(this);
counter.simplyCountable({
counter: '#' + counter.next().find("span").attr('id'),
countType: 'characters',
maxCount: 4000,
strictMax: false,
countDirection: 'down',
thousandSeparator: ',',
});
});
});
Option 2 - improve the plugin
A nicer solution would be to improve the plugin so that the counter
option is used to find elements relative to the element plugged in. This will require a common ancestor element so that the textarea
and counter can be located.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/e82kf82r/9/
$(function () {
$('.container').simplyCountable({
counter: 'span',
countType: 'characters',
maxCount: 4000,
strictMax: false,
countDirection: 'down',
thousandSeparator: ',',
});
});
HTML change (added parent divs):
<div class="container">
<textarea class="multi"></textarea>
<div class="remaining-counter">
<p><span class="safe">3,979</span> characters remaining</p>
</div>
</div>
Extract of changes to plugin:
The default options add a text
selector:
$.fn.simplyCountable = function (options) {
options = $.extend({
text: 'textarea',
counter: '.counter',
The new plugin initialising code looks like:
return $(this).each(function () {
var $element = $(this);
var countable = $element.find(options.text);
var counter = $element.find(options.counter);
Upvotes: 1