how to add filter to datatable - javascript

I have made a dataTable and populated it with many fields, but I would like to add my own search/filter function to it.
I have a textbox that I am using as the search/filter:
<div class="filterTable">
<form>
<input id="tableSearch" type="text" placeholder="filter">
</form>
</div>
And this is the JavaScript function that I have added for it:
$("tableSearch").keyup(function () {
var string = document.getElementById("tableSearch").value;
oTable.fnFilter(string);
});
oTable is the initialized dataTable.
The problem I am having is that the JavaScript function is never hit. Any Ideas?

You should use the # tag for reffering the ID of an element.
Try with the below mentioned code.
$("#tableSearch").keyup(function () {
var string = $(this).val();
oTable.fnFilter(string);
});

Related

Modify the value of each textfield based on original value using jQuery

Is it possible to modify the value of each textfield present in a webpage, based on the original value, using jQuery or JavaScript?
For example, suppose I have 50 textfields in a page. I want to remove whitespace from the beginning and end of each textfield’s value. I don’t find it to be a good idea to call the function for every textfield individually. How can I do it without calling a function for each textfield?
Can just use val() with a callback argument. It will loop over all elements for you:
$('input[type=text]').val(function( index, originalValue){
return $.trim(originalValue);
});
val() API docs
You can execute this code:
$('input[type=text]').each(function (i, e) {
var $this = $(e);
$this.val($this.val().trim());
});
Get all the inputs from the page using jquery then run a loop, and for each element trim the value
<body>
<input type="text" value=" abc " >
<input type="text" value=" def " >
<input type="button" id="remove" value="Remove">
<script type="text/javascript">
$(document).ready(function(){
$('#remove').click(function(){
var inputs = $('input[type=text]');
$.each(inputs, function(index,input){
$(input).val($(input).val().trim())
});
});
});
</script>
</body>

How can I filter data returned from jQuery?

jQuery code:
$(document).ready(function() {
$('#s-results').load('get_report1.php').show();
$('#search-btn').click(function(){ showValues(); });
$(function() {
$('form').bind('submit', function() { showValues(); return false; });
});
function showValues() {
$.post('get_report1.php', { name: form.name.value },
function(result) {
$('#s-results').html(result).show();
}
);
}
});
HTML:
<form name = "form">
<div>Enter name</div>
<input type="text" name="name" id="fn" />
<input type="submit" value="Search" id="search-btn" />
<div>
<input type="text" id="se2" name="search22">
</div>
</form>
<div id = "s-results" style="height:50px;">
</div>
Up to this the script is running perfectly. Now I just want to filter the returned HTML from the above function again.
For implementing this I have tried this line of code:
$(result).filter('#se2');
under the function with the result parameter, but it is not working.
So how can the returned HTML code be filtered?
You probably need find() instead of filter as you need to get the descendant whereas filter "Reduce the set of matched elements to those that match the selector or pass the function's test"
Live Demo
$(result).find('#se2');
If the #se is added in DOM then you can directly use the id selector
se = $('#se2');
I made another demo (as I am still waiting for your demo that is not working) to further elaborate how a string containing the html you have could be passed to jQuery function $() to search elements within it using find.
Live Demo
html = '<form name = "form"> \
<div>Enter name</div> \
<input type="text" name="name" id="fn" /> \
<input type="submit" value="Search" id="search-btn" /> \
<div> \
<input type="text" id="se2" name="search22" value="se2"/> \
</div> \
</form>\
<div id = "s-results" style="height:50px;"> \
</div> ';
alert($(html).find('#se2').val());
Note You can further check the code working in the example above by using find wont work by using filter over this jsfiddle example
The issue
You are successfully adding the result to #s-results:
$('#s-results').html(result).show();
And then tried to select #se2 from the added results like this, with no success:
$(result).filter('#se2');
It didn't work because you didn't get it from the dom added in the second step.
Actually, it is creating a new unattached dom with the same result variable.
The solution
To select #se2 from the added result content correctly, try the following:
$('#s-results').filter('#se2');
Or, as suggested by #zerkms, you could select it directly through:
$('#se2');
These possibilities will work, because now it is referencing something attached to dom, which will search into the same elements you added in the first step.
You can try to use ajax for this as below:
$(document).ready(function () {
$('#s-results').load('get_report1.php').show();
$('#search-btn').click(function () {
$.ajax({
type: "POST",
url: "get_report1.php",
data: {
name: $("#fn").val()
},
beforeSend: function () {
//do stuff like show loading image until you get response
},
success: function (result) {
$('#s-results').html(result).show();
},
error: function (e) {
alert("Error in ajax call " + e);
}
});
});
});
Note: When you click on search-btn each time it will call the get_report1.php file and retrieve the data base on the text-box value that you have passed. I assume that in ge_report1.php file you are using the tex-box value like: $_POST['name'] and you are fetching the data using MySQL search query.
You can use JQuery find instead of filter.
$(result).find('#se2');
Then add to your variable like this
var your_element = $('#se2');

How to pass JavaScript variable to g:remoteFunction "update" property?

I have a function in JavaScript that submits a message to a method in a Grails controller and at the same time updates div with myID id.
function messageKeyPress(field,event,messageBox) {
...
var message = $('#messageBox').val();
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="myID"/>
...
}
I use it like this:
<div id="chatMessages" class="chatMessages"></div>
<input type="text" id="messageBox" class="messageBox" name="message" onkeypress="messageKeyPress(this,event,'#messageBox');"/>
<div id="myID">
I would like that function to be reusable being able to update different divs.
I tried:
onkeypress="messageKeyPress(this,event,'#messageBox', '#myID');"
and in JavaScript:
function messageKeyPress(field,event,messageBox, myID) {
...
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="${myID}"/>
But that didn't work. My question is how to pass a JavaScript variable to Grails g:remoteFunction "update" property.
I suggest you to use jQuery instead. It is bundled by default to Grails projects. As a result, you'll get a neat separation between javascript code and gsp view logic. For instance, application.js might look like this:
(function($) {
$('.messageBox').on('keypress', function () {
...
var params = {message: $(this).val()};
var url = $(this).data('url');
var target = $(this).data('target');
$.post(url, params, function(response) {
$(target).html(response);
});
...
});
})(jQuery);
and your view file:
<input type="text" id="messageBox"
class="messageBox" name="message"
data-url="${createLink(action: 'submitMessage')}"
data-target="#myId"/>
<div id="myID"></div>
You should assign a messageBox css class to every input field you want to have this event listener. And in data-target attribute of every field you can specify a selector for all divs that should be updated.
jQuery is very easy to learn. http://api.jquery.com/
The update attribute should be set to the ID of the element to be updated, not a selector that matches this element. In other words, try this:
onkeypress="messageKeyPress(this,event,'#messageBox', 'myID');" // '#' removed from myID

Grails richui autocomplete passing object to function or updating object ID

I've got a table with a load of auto complete boxes in it which look like so...
<richui:autoComplete style="width:500px" name="objSelect[${newRow-1}].id" value= "" action="${createLinkTo('dir': 'object/searchAJAX')}" forceSelection = "true" maxResultsDisplayed="20" minQueryLength ="3" onItemSelect="updateHiddenInput(id,${newRow-1})" />
I've got it to call a function called updateHiddenInput when a user selects a value passing in the id selected as well as the row the autocomplete is on (this function then updates a hidden field in the same row, using the values passed in, with the ID). The function looks like so: -
function updateHiddenInput(id, num){
var objID = "objectID[" + num + "].id";
$(document.getElementById(objID)).val(id);
}
Everything works until I add a new row within my table, this pushes everything down one row and stops the autocomplete from updating the right rows hidden field (as its still referencing the old row).
Currently I have another piece of code that goes through and renames all the fields when a new row is inserted, but I have no idea how to update the autocomplete so that it passes through the right row number, anyone know how I can alter this?
The only other alternative I could think of would be to just pass through the object itself as well as the ID I can then locate the hidden based off the object, but I can't work out how to do this, any suggestions gratefully received! :S
I've tried changing
onItemSelect="updateHiddenInput(id,${newRow-1})"
to
onItemSelect="updateHiddenInput(id,this)"
Theoretically so I can just pass through the autocomplete object and from there just traverse the page to find the hidden field I want to update. However when I then attempt to use that object in my function, for example with something like: -
var mynumber = $(myobject).closest('td').find('input').val();
I always get an "undefined" returned when I try to alert back the value...
If I just put in an alert(myobject) in the function it returns AutoComplete instance0 autoLook[0].id but if I've inserted new lines the id value doesn't change (i.e the objects id is now autoLook[3].id but it still shows [0], which I think could be part of the problem but I've got now idea how I can update this value...
I notice when looking in firebug at the html there is a /script linked to the autocomplete which could be the problem as this doesn't get updated when new lines are added and I can see multiple references to the old/original id value (see below) so maybe the passing through of this isn't passing the current objects values through...?
<script type="text/javascript">
var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/Framework/object/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
;
autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','ad186a42e45d14d5cde8281514f877e42', autoCompleteDataSource);
autoComplete.queryDelay = 0;
autoComplete.prehighlightClassName = 'yui-ac-prehighlight';
autoComplete.useShadow = false;
autoComplete.minQueryLength = 3;
autoComplete.typeAhead = false;
autoComplete.forceSelection = true;
autoComplete.maxResultsDisplayed = 20;
autoComplete.shadow = false;
var itemSelectHandler = function(sType, args) {
var autoCompleteInstance = args[0];
var selectedItem = args[1];
var data = args[2];
var id = data[1];
updateHiddenInput(id,this) };
autoComplete.itemSelectEvent.subscribe(itemSelectHandler);
</script>
My thanks so far to user1690588 for all his help thus far! :)
On further digging I'm convinced that my issues is down to the line autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','a5b57b386a2d1c283068b796834050186', autoCompleteDataSource); specifically the part where its inputting autoLook[].id and if I could change this I'd then be ok, but this line is auto generated and I've got no idea how to update it, anyone have any similar experience?
I have not much idea about your gsp page but I tried it on my side:
My gsp:
<!DOCTYPE html>
<html>
<head>
<resource:autoComplete skin="default"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = ${list.size()};
function asd() {
jQuery.ajax({
url: " ${createLink(controller: 'oauthCallBack', action: 'testAuto')}",
data: "idx=" + counter++,
success: function (data) {
jQuery("#tableId").append("<tr><td>" + data + "</td></tr>");
}
});
}
function updateHiddenInput(id, tg) {
jQuery(tg).val(id);
}
</script>
</head>
<body>
<g:form>
<table id="tableId">
<g:each in="${list}" var="vr" status="idx">
<tr>
<td>
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
</td>
</tr>
</g:each>
</table>
</g:form>
<button onclick="asd()">Add</button>
</body>
</html>
My action:
def testAuto() {
render template: 'addNew', model: [idx: params.idx]
}
My template(addNew):
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}"
onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
Try this..,.
EDIT.....................................................................................
I supposed that you have successfully updated all the input field names. Then you can edit hidden field like:
View:
<tr class="dummyClass">
<td>
<richui:autoComplete name="name[${idx}]" id="uniqueId[${idx}]" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, this)"/>
<g:hiddenField name="someName[${idx}]" id="someId[${idx}]" value=""/>
</td>
</tr>
jQuery:
function updateHiddenInput(id, tg) {
jQuery(tg._elTextbox).closest("tr.dummyClass").find("input[type=hidden]").val(id);
}
EDIT.....................................................................................
Why you need to change the 'id'? Changing name is sufficient to send values in order. And you can update the hidden field without id as above edit.
If you still need to change the id then you can change it by cloning the tr and then use regex. See this answer for full working example.

JQuery - Append to text area that has been modified with Jquery

I am trying to append the value of a div or a input box to my text area. I have this working no problem but if i clear the contents of the text area first with a Jquery action it doesnt allow me to use my append features.
E.g.
<script type="text/javascript">
$(document).ready(function() {
$("#Column1").click(function () {
$("#sql").append($("#Column1").val())
})
$("#Column2").click(function () {
$("#sql").append($("#Column2").html())
})
$("#reset_sql").click(function () {
$("#sql").val('SELECT ')
})
</script>
<div> <input type="checkbox" name="column1" id="column1" value="`Column1`"> column1 </div>
<div id="Column2"> Column2 </div>
<textarea rows="10" cols="80" name="sql" id="sql"><? echo $sql ;?></textarea>
<input type="submit" value="submit" />
<input type="button" value="reset sql" id="reset_sql" />
The input and div lines above are just generic examples but relate exactly to what i'm trying to do.
I dont understand that when i clear the text area with javascript that my appends wont work. I get no JS errors in firefox error console.
thank you
You have several issues with your code: you haven't closed your document.ready callback, you are using the incorrect case when refering to your ID's, and you're using some of the jQuery methods incorrectly. For example, append() appends HTML to an element, whereas you want to update the value.
Your logic isn't quite correct either, since columns won't be removed when you uncheck a checkbox, and the columns won't be comma delimited (it looks like you are building a SQL string here).
I believe something like this is what you're looking for:
$(document).ready(function() {
var $sql = $('#sql');
var initialValue = $sql.val();
$("#column1, #column2").on('change', function () {
var cols = [];
var checked = $('input[type="checkbox"]').filter(':checked').each(function() {
cols.push($(this).val());
});
$sql.val(initialValue + ' ' + cols.join(', '));
})
$("#reset_sql").on('click', function () {
$sql.val(initialValue)
})
});
Working Demo
Your checkbox has an id of 'column1', but your event handler is $("#Column1").click(function () {.
Case matters! Either change the id to 'Column1' or the event handler to look for $('#column1').
Demo

Categories

Resources