Using data table I want to search with only first letter - javascript

I have a table with Owner names. The users wants to be able to sort the tables from first letter on wards.
Example:
1)Saurabh Gujarani
2)Testsa
By searching "Sa" should only list - Saurabh Gujarani
But in my current code it display both.
<script type="text/javascript">
$(document).ready(function () {
$('#custom_2').dataTable({
"aoColumnDefs": [
{ "bSearchable": false, "aTargets": [ 0,1,4,5,6,7,8 ] }
] } );
});
</script>

you can modify the default search functionality of DataTable as follows.
//Declare table
var table = $('Table Selector').DataTable();
//on search box keyup
$('input[type = search]').on( 'keyup', function () {
//start check from first character
table.search( '^' + this.value, true, false).draw();
});
Please see the working demo https://jsfiddle.net/Prakash_Thete/b577yxa3/1/

I have used this to make users able to search for elements in a periodic table.
var searchString = document.getElementById("search").value; //The user input field
if (searchString !== "") {
var cols = document.querySelectorAll('#yourTableID td'), colslen = cols.length, i = -1;
while(++i < colslen){
if(cols[i].id.indexOf(searchString)>-1){
//Do something to the tds that match the searchstring (acces with "cols[i]")
} else {
//Hide the tds that does not match the searchstring (eg. cols[i].style.display = "none";)
I matches the search string with the id of a <td>, but I think you might be able to replace the .id. in the if statement, with innerHTML or value if you want to search for the text inside the td.
Hope this helps!

Related

Javascript - adding comma automatically to input field

I will post the part of a function that is adding numbers that are clicked into selected input field.
So, I need to separate it with a comma (,). I tried some of the examples but it seems not to be working on the function that I wrote.
var rowRange = 'abcdefghijklmnopqrstuvwxyz'.split('');
var $cart = $('#seats'),
$counter = $('#counter'),
sc = $('#seat-map').seatCharts({
map: [
'aaaaa__aaaaa',
'aaaaa__aaaaa'
],
naming : {
top : false,
getLabel : function (character, row, column) {
return rowRange[row - 1].toUpperCase() + column;
},
},
click: function () {
if (this.status() === 'available') {
$('#seats').split(",")
.attr('id', 'cart-item-'+this.settings.id)
.val(this.settings.label)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
return 'selected';
});
});
Seat is a input field where comma needs to be added after every click on any number.
.split(",")
when I remove this part the code works like it should, but without adding comma.
.split() doesn't work on jquery objects. Instead use it on the values in your select.
Here is an example on how it could work.
$selected = $('#selected');
$(".seat").on("click", function() {
const cur = $selected.val();
const valToInsert = $(this).text();
$selected.val(cur.length === 0 ? valToInsert : cur.split(',').concat(valToInsert).join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="selected">
<button class="seat">a</button>

Filtering an exact of string in DataTable JQuery

How do I search for an exact match in the search bar of JQuery Datable I tried using fnFilter but it's still not returning an exact match.
$(document).ready(function() {
var oTable = $('#datacal_table').DataTable({"order": [[4, "asc"]]});
oTable.fnFilter("^"+$(this).val()+"$", 4, true);
});
For example I only watch to search 'active' but what happens is the 'inactive' words also returns in the result. What should I do I need to be able to search only the the exact string.
EDIT
I tried one of inuka's links How to search for an exact string in a jQuery DataTable?
and it seems like my text class is interfering with the search, how do I get around this? I want to keep using my class text so that it's colored.
<td id="status">
<span class = "label {{ getStatusColor($data->status) }}"
id = "status_{{ $data->id }}">
{{ getStatusText($data->status) }}
</span>
</td>
when I only retain {{getStatusText}} the search works but when I try to class it, it doesn't.
<script type="text/javascript">
$(document).ready(function() {
var table = $('#datacal_table').DataTable({
"order": [[4, "asc"]]
});
$('.dataTables_filter input', table.table().container())
.off('.DT')
.on('keyup.DT cut.DT paste.DT input.DT search.DT', function(e) {
var term = $.trim(this.value);
if (term !== ""){
var termRegExp = new RegExp('^' + $.fn.dataTable.util.escapeRegex(term) + '$', 'i');
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex){
var isFound = false;
$.each(data, function (index, value) {
if (termRegExp.test(value)){ isFound = true; }
return !isFound;
});
return isFound;
}
);
}
table.draw();
if (term !== "") {
$.fn.dataTable.ext.search.pop();
}
});
});
</script>
The following answer from this post will give you an answer for searching term inside your HTML table structure.
$('#datacal_table').DataTable({
"columnDefs": [{
"targets": [4],
"render": function ( data, type, full, meta ) {
if(type === 'filter'){
return $('#datacal_table').DataTable().cell(meta.row, meta.col).nodes().to$().find('span').text();
} else {
return data;
}
}
}]
});
According to Datatables documentation this columnDefs.targets will give you the option to match only specified column name values. "targets": [4] will only focus on values under your Status column.
try this code
var oTable = $('.datatable').DataTable();
$('.dataTables_filter input').keyup( function () {
oTable.fnFilter("^"+$(this).val(),0,true,false);
});
working link http://codepen.io/subbu1191/pen/GmrvNd
1.{string}: String to filter the table on
2.{int|null}: Column to limit filtering to
3.{bool} [default=false]: Treat as regular expression or not
4.{bool} [default=true]: Perform smart filtering or not
5.{bool} [default=true]: Show the input global filter in it's input box(es)
6.{bool} [default=true]: Do case-insensitive matching (true) or not (false)
you have to make the smart filtering false in order to get the regex working

Find ID in String using match

I'm building a widget that will generate a graph for an element when it is double clicked on the page. Without remaking all widgets this is the only way for me to tackle the problem.
I want find the ID of a widget from the html of an element.
All widgets I want to work are inside a div element panel_content_id_#
I want to find the number found on the line of code
var io_id=32715;
How can I search the string for this pattern and get the number (32715).
$('div[id^="panel_content_id_"]').dblclick(function(e){
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
var search = code.match("var io_id=");
if(search > -1){
}
console.log($(this).html());
});
The line of code im looking for will look like so
var io_id=xxxxx;
Where xxxxx = some random number I dont know
I want to find xxxxx
Split it in two parts - All the code before the var io_id= and the other part is after that.
And then you know that the line ends with ;, so from that second part you cut of the stuff that is before the semicolon.
CODE
$('div[id^="panel_content_id_"]').dblclick(function(e){
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
if (code.indexOf("var io_id")>-1) {
id = parseInt(code.split("var io_id=")[1].split(";")[0]);
}
if(search > -1){
console.log("The code betrayed me");
}
console.log("The id is: " +id);
});
Maybe you could try this regex pattern:
\d+(?! var io_id=)
Used like this:
$('div[id^="panel_content_id_"]').dblclick(function(e) {
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
var search = code.match("var io_id=");
if (search) { // Edited
// New code
alert(code.match(/\d+(?! var io_id=)/gim));
}
console.log($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="panel_content_id_32715">
Div content
<br><br>
var io_id=32715;
</div>

How to replace text based on counter value?

Call to the count function made by two group of checkboxes. First group represents categories, when clicked subjects for that category will be listed out.
html: id: counter displays count value. id: select replaces text acordingly
<div class="small-8 text-left columns" style="left:-30px;">
<span id="counter"><span id="count">0</span></span>
<span id="select">Select Subjects</span>
</div>
script:(categories group) To pass value for the subjects to be fetched by ajax. updateCount();is the count function call.
$("input[type=checkbox][id^=level]").change(function() {
var selectedval = $(this).val();
if($(this).is(":checked")) {
var selectedtext = $(this).next().text();
sendtobox(selectedval, $("#slider1").val(),"regis");
} else {
$("th."+selectedval).remove();
updateCount();
}
});
(subjects group)
$(document).on('change', '[id^=sub][type=checkbox]', updateCount);
count function:
function updateCount () {
$('#count').text($('[id^=sub][type=checkbox]:checked').length);
}
script to replace text:
$(".close-reveal-modal").on("click",function()
{
document.getElementById("select").innerHTML = "Select subject";
var str = document.getElementById("select").innerHTML;
var res = str.replace("Select subject", "Selected Subject");
document.getElementById("select").innerHTML = res;
});
Now I can replace text and the count works just fine! My problem is it doesn't obey the English grammar!
If 0 item/subjects returned, the text should be 0 Selected Subjects and if more than 1 is checked, it should say the same. See the (s) must be added in 'subject' word.
My problem is , I couldn't identify number of counts to replace this text.
I want someting like this:
if ($("#count") >1 || ($("#count")==0))
{
var res = str.replace("Select subject", "**Selected Subjects"**);
document.getElementById("select").innerHTML = res;
}
else
{
var res = str.replace("Select subject", "**Selected Subject"**);
document.getElementById("select").innerHTML = res;
}
I tried to alert $('#count').length , it red like this each time the checkbox checked:
1 1 1 1
What I'm expecting is
1 -when clicked once
2 - when clicked twice
This way would be easier for me to replace text indeed!
it sounds like you want the TEXT of the span with id 'count' for that comparison:
if ($("#count").text() == "1") {
// singular
}
else {
// plural
}

In Jquery take a different values from single text box id

I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}

Categories

Resources