Textarea increase ++ one row on enter and keypress using .attr() update - javascript

I have a textarea on which I want to increase his height with one row on every enter and on each time when text it goes into another row wile typing. So I have 3 conditions, when is displayed I want to number all used rows and set rows height based on this:
one: var countRows = $("textarea").val().split(/\r|\r\n|\n/).length;
two: when keypress == 13 is used
and three: when text it goes into another row wile typing
Till now I have achived this but is not really working :|
var countRows = $("textarea").val().split(/\r|\r\n|\n/).length;
var keynum = 13; //enter keynum
//for default state
//not calculating
$("textarea").attr("rows", countRows + 1);
//for enter key
//not really working
$("textarea").on('keypress', keynum, function() {
$(this).attr("rows", countRows + 1);
// alert("jjj");
});
//for case whentext it goes into another row wile typing
I just want to do that using .attr() and updating that attribute "rows" when one more row is added or removed.

From https://stackoverflow.com/a/10080841/4801673
$("textarea").keyup(function(e) {
while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height()+1);
};
});

$('textarea').keyup(function(e) {
var $lineHeight = $(this).height() / $(this).get(0).rows;
var $lines = $(this).val().split(/\r|\r\n|\n/).length;
$(this).get(0).rows = $lines;
});
Increase size if add new lines to textarea.
Decrease size if remove lines from textarea.
Nothing to do if lines not added/removed in textarea.

Related

Jquery Data table Search Option is not enable sorting icon

I am stuck in jquery Data table. if we use jquery data table then it provide by default search option. But problem is that if i search particular record and if content is not match or i found single record. then i need to remove sorting icon. it will work but as i press back space and remove searching content then as usual it display all records. But now sortable icon is disable it needs to enabled once again then what is the solution for that.
This is function call:-
$('#datatable-information').on('draw.dt', function () {
disableSortingSearchOption(oTable, 'datatable-information_filter input');
This is Function Defination:-
function disableSortingSearchOption(oTables, tableClass) {
if (oTables != null) {
var rowCount = oTables.fnSettings().fnRecordsDisplay();
{
if (rowCount == 0 || rowCount == 1) {
var oSettings = oTables.fnSettings();
//Remove sort icon
$('.DataTables_sort_icon').remove();
//Remove hand cursor
$('.datatable th').css('cursor', 'default');
//Iterate through each column and disable sorting
$('.' + tableClass + ' th').each(function (index) {
if ((oSettings.aoColumns[index]) != undefined) {
oSettings.aoColumns[index].bSortable = false;
}
});
}
}
}
}
Here is a simple way to remove the sorting arrows on the table headers and change the pointer to default when the drawed table has 1 line or less.
On more than one line, the table sorting and the pointer comes back to "normal".
My solution is quite different than the code you provided.
function disableSortingSearchOption(oTables) {
if (oTables != null) {
var colCount = 0;
$(oTables).find('th').each(function(){
colCount++;
});
//console.log(colCount+" colunms");
var rowCount = 0;
$(oTables).find('td').each(function(){
rowCount++;
});
rowCount = rowCount/colCount;
//console.log(rowCount+" rows");
if (rowCount <= 1) {
//Remove hand cursor
$(oTables).find('th').css('cursor', 'default');
//Remove sort arrows
$(oTables).find('th').removeClass('sorting');
}else{
//Add hand cursor
$(oTables).find('th').css('cursor', 'pointer');
//Add sort arrows
$(oTables).find('th').addClass('sorting');
}
}
}
We need to know the row amount...
To achieve this, we first count the column amount and the whole table's td amount.
The row amount is the td amount divided by the column amount.
Based on this number, we can add or remove the sorting class on all th and set the cursor.
Note that when there is no result, there is still one line to show "No matching records found". But since there is only 1 td in this case... divided by the colunm count, we have to think about "one or less line".
;)
Have a look at this CodePen.

Preventing X numbers from select

I have a script running to show a number in the select list options when the user check one specific value it will display a number refering to how much times he can pay his bill.
Note this code:
var tabelaParcelas = [2,3,4,6,8,10,12];
$(document).ready(function(){
update();
});
$('input[type=checkbox]').click(function(){
update();
})
function update(){
var list = $('#instNum2'); // use selector only once whenever possible for better performance
// clear any existing options from the dropdown list
list.html("")
// count checked boxes
var checked_boxes = 0
$(".check_list").each(function(){
if(this.checked){
checked_boxes++;
}
});
// append options to the select list
for(var i=0;i<checked_boxes;i++){
var option = $("<option>", {value: tabelaParcelas[i], "text": tabelaParcelas[i]});
list.append(option);
}
}
That's correct! But the thing is, I need to display 1x as well, and that's what's not showing at all, 1x should be visible always no matter how much boxes you select, and other thing, when I select more than 7 boxes, the option keep producing empty options, while it should only keep displaying 12x without appending any new...
var tabelaParcelas = [2,3,4,6,8,10,12];
$(document).ready(function(){
update();
});
$('input[type=checkbox]').click(function(){
update();
})
function update(){
var list = $('#instNum2'); // use selector only once whenever possible for better performance
// clear any existing options from the dropdown list
list.html("")
// count checked boxes
var checked_boxes = 0
$(".check_list").each(function(){
if(this.checked){
checked_boxes++;
}
});
//add limit to check_boxes
//This section was not in original code
// Could also do if(checked_boxes > tabelaParcelas.length) {checked_boxes = tabelaParcelas.length;}
//Would make it more dynamic.
//This is added to limit the number of options added to the length of the array at the top.
//This will prevent blank options from being added as requested in the question.
if(checked_boxes > 6) {
checked_boxes = 6;
}
//add 1x option to empty list
//This was not in original code
//This was added as the list was cleared when this function is run and they always wanted 1x to appear as an option.
list.append("<option value='1' selected>1</option>");
// append options to the select list
for(var i=0;i<checked_boxes;i++){
var option = $("<option>", {value: tabelaParcelas[i], "text": tabelaParcelas[i]});
list.append(option);
}
}

Count Textarea Character and increase or Decrease size of the TextArea

I want to allow user to enter upto 300 character and simultaneously. I want to increase textarea based on user text if he deletes text, decrease textarea
https://jsfiddle.net/yhqdhr3x/
<div id="divChar">300</div>
<textarea id="txtpostSearch" class="form-control" rows="3" ></textarea>
JQuery Code
$('#txtpostSearch').keyup(function () {
var txtCharCountLength = $(this).val().length;
if (txtCharCountLength <= 300) {
var remainingChar = 300 - txtCharCountLength;
$("#divChar").html(remainingChar);
}
});
In your initialisation, put the following to prevent errors (this is for what keeps it less than 300 chars):
oldVal = "";
If you use a monospace font, and know the number of chars that fit in a row, each time the letter is typed, you could do the following on each character typed.... this assumes you can fit 22 chars on each row...
// save the element as variable, just to access without typing as much
elem = document.getElementById('txtpostSearch');
//if the length is above 300, set it back to what the value was before
if(elem.length > 300){
elem.value = elem.value.substring(0, 300);
}
// the length of the contents of the textarea
len = elem.value.length;
// the new number of rows in the textarea
// it is the number of rows completely filled by text, plus two
// plus two makes room for the row currently typing in, and one more empty row
rows = Math.floor(len / 22) + 2;
// sets the height as the number of rows in units of font size
elem.style.height = rows + 'em';
//store the value in case the next length is too large
oldVal = elem.value;
I made a little fiddle: https://jsfiddle.net/5w7gogqt/
This fiddle uses a font called ProFont (if you dont have it, the fiddle defaults to plain monospace), which always has a set size no matter what OS or browser you use. You can always use a webfont for your field, then people use that font even if they don't have it.
You can change the number of rows and columns of the text area using JQuery.
To limit the number of input characters there's maxlength but it doesn't work consistently on all browsers, as an alternative you can just truncate the content of the textbox with substring and change the value of the textbox.
Demo:
$('#txtpostSearch').keyup(function() {
var str = $(this).val();
var txtCharCountLength = str.length;
if (txtCharCountLength <= 300) {
var remainingChar = 300 - txtCharCountLength;
$("#divChar").html(remainingChar);
var rows = str.split("\n");
var cols = rows.sort(function(a, b) {
return b.length - a.length
})[0].length;
$(this).attr('rows', rows.length + 1);
$(this).attr('cols', cols);
}
else {
$(this).val($(this).val().substring(0, 300));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divChar">300</div>
<textarea runat="server" class="form-control" cows="3" id="txtpostSearch"></textarea>

Reduce textarea height based on its content

I'm able to increase textarea height as textrows add up (based on this question/answer: Adjust TD height depending on textarea rows).
Now, how do I reduce rows as I remove text? The answer above only adds rows.
If you want it more stable, you can count the linebreaks. So you can be sure that it set exactly the right number of rows:
$('.expand').on('keydown', function(e) {
if(13==(e.keyCode ? e.keyCode : e.which)) {
var rows = $(this).attr('rows');
var rowsNew = parseInt(rows) + 1;
$(this).attr('rows', rowsNew);
}
});
$('.expand').on('keyup', function (e) {
var lines = $('.expand').val().match(/\n/g);
var need = lines ? lines.length + 1 : 1;
var itis = $('.expand').attr("rows");
if(itis!=need) {
$('.expand').attr("rows", need);
}
});
Demo here: http://jsfiddle.net/efhYe/
But if you have jQuery already, you can also use this plugin: http://www.jacklmoore.com/autosize/

textbox keyup event not working properly

I am using following code to update one textbox value txtUnitPrice based on other textbox txtQuantity ,both can be generated dynamically which is done.
//update unitprice based on quantity of product and tax applied
$('input').live('keyup', function () {
var inputId = $(this).attr('id'); //get textbox txtQuantity id
var rowNum = parseInt(/txtQuantity(\d+)/.exec(inputId)[1], 10); //get row id
var productValue = $("#ddlProduct" + rowNum).val();
var taxValue = $("#ddlTax" + rowNum).val();
var unitPriceValue = $("#txtUnitPrice" + rowNum).val();
var quantityValue = $("#txtQuantity" + rowNum).val();
if ((quantityValue != " ") && (quantityValue > 0)) {
$("#txtUnitPrice" + rowNum).val(unitPriceValue * quantityValue);
}
else {
$("#txtUnitPrice" + rowNum).val(unitPriceValue);
}
});
Now problem arising in the code above is that when I even moving cursor forward or backward in the textbox txtQuantity then the value for txtUnitPrice is changing becuase which this event 'keyup' is firing and hence whole code is executed with the existing txtunitprice value and multiplies this again with the existing txtquantity which I dont' want Please can anyone help me regarding this . Thanks
Just add a check to ignore the cursor movements like shown below
$('input').live('keyup', function (e) {
if([37, 38, 39, 40].indexOf(e.which)){
return false;//do nothing because the cursor keys have been pressed
}
//the rest of your code
});

Categories

Resources