How to filter rows in database - javascript

I have a small line of code here...
if(todaysDate!==date_encoded_time){
str +='<div id='div_label'>'+recipe_arr[x].recipe_name+''+'</div>';
}else {
str +='<div id='div_label'>'+recipe_arr[x].recipe_name+'NEW ITEM'+'</div>';
}
for todaysDate, I'm getting the value of current date or the date today and for the date_encoded_time, it's the date that was stored in a database. What I'm trying to do here is when todaysDate matched date_encoded_time, it will show on the app 'NEW ITEM'; but every item says 'NEW ITEM', so how can I select a specific row or display a specific item that will tell the user that it's new, using JS and not PHP..? By the way it's already connected to the database wherein I used AJAX, but I just need to get the latest record that was added on the database.
Any thoughts? Anyone?
Thanks!

Try embeding a specific class on each elements and catch up them using jQuery.
I assume the code below is PHP code.
if (todaysDate!==date_encoded_time){
str +='<div id='div_label'>'+recipe_arr[x].recipe_name+''+'</div>';
}else {
str +='<div id='div_label' class="theClass">'+recipe_arr[x].recipe_name'</div>';
}
Then pick up and manipulate them by jQuery like this.
<script type="javascript">
$(".theClass").ready(function(){
// Manipulation as you would like.
$(this).html("NEW ITEM");
});
</script>
I didn't check that code but hope this will help you.

Related

Using JS or AJAX to live search filter through JSON object on page (laravel)

I'm new to AJAX and a lot of JS, but I need to replace some old angular functionality on our Laravel site.
We simply have a page with a static/sticky header search bar, but no submit button. It needs to do a live filter upon search input. i.e. if I type sofa, it should hide anything from the page without the word sofa.
The Laravel blade/HTML is built with foreach loops from controller data, but more importantly, the data is stored in a JSON object called orderFormData, shown below.
I need a simple and effective live search filter to hide anything that doesn't match between the JSON and the search bar. The page is built with multiple HTML tables so I don't want to filter by the table and I think that's too complicated and convoluted. It should suffice to do it by JSON, possibly with AJAX. However, I'm a total novice here and I'm desperate for a solution.
Here's the search html:
<div class="md-input-wrapper search-form">
<form class="uk-search" id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
</div>
Here's the JSON object and some JS that I was playing with, but it doesn't work:
<script type = "text/javascript">
var orderFormData = <?php echo json_encode ($tempdata);?>;
$(document).ready(function(){
$('#srch-term').on('keyup',function(){
var searchTerm = $(this).val().toLowerCase();
$('.uk-table tbody tr').each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
});
});
});
</script>
This is just a pure JS idea, but I'm interested in AJAX as well if it will work better for this scenario. How can I properly filter items on the page by tying the search bar and JSON object?
You don't need of Ajax to do a search function with hide and show, this is simply manipulating DOM, instead ajax can calls the json from the php and with jquery you can simple loop your td on keypress and use :contains of jquery, onkeypress you call a function and in this function you do show and hide if contains "search" show otherwise hide.
Here a simple example in one of my old project #tabellaWebLog was the id of the table ricercaUser was the id of the input search and trTabellaWebLog was the id of the row where i wanted the search instead .ricUser was the class of the table column to loop the search inside the table...Bye
user = $('#ricercaUser').val();
$('#tabellaWebLog').find("#TrTabellaWebLogRiga:not(:contains('"+ user +"'))").hide();
$(".ricUser:contains('" + user + "')").parent().show();
$(".ricUser:not(:contains('" + user + "'))").parent().hide();

Select multiple items with javascript / asp.net

This is what I have so far I have a view that displays date that I have not reported a time for.
My idea is to tick the dates I want to report a time, so I can report time for multiple dates, and if I did check a date I do not want to report for I just uncheck that box.
I have that working, (kinda) The problem is if i want to select a date, i'll always have to select the first in the list before I can check any other date.
Like this:
That works great as long as I always choose the first date in the list.
But that is not what I am looking for, I want the option so I can report any data without having to check the first date first.
This would not work because I did not check the first date:
This is my script:
var dateArr=new Array();
function SetDate(dt) {
if(document.getElementById("isoDate").checked) {
if(dateArr.indexOf(dt)<0){ //Check if date is already added. if not add it to array.
dateArr.push(dt);
}
else{
var index=dateArr.indexOf(dt);
if (index > -1) {
dateArr.splice(index, 1);//Remove from array if checkbox uncheck
}
}
$('#date').val(dateArr.join(" ")); //Add space separated string to the #date element.
}
}
And this is my view where I get the dates:
#foreach (var date in ViewBag.MissingDays)
{
var isoDate = date.ToString("yyMMdd");
<div class="col-md-1">
<input type="checkbox" id="isoDate" name="isoDate" value="#isoDate"onclick="javascript:SetDate('#isoDate');" />
#isoDate
</div>
}
There are some observations regarding your code, like is not a good practice to have multiple items with the same id(i could actualy say that is a bad practice, i am talking about the checkboxes, the same name should be enough) or lines like:
if(document.getElementById("isoDate").checked)
that ruins everything(this i think it is the real source of your problem since the result is the first element and not being checked will step to else)
Seeing that you use jquery, here you have a small sample of how this should look like.

Fetch values dynamically to a text field like a slider using php,mysql and javascript

Their are two tables : Table x( holds 'Areaname','datacount' coloumns) and Table Y (holds 'Areaname')
User enters Areaname and datacount from a php page later it gets inserted to table x
my requirement:
If Areaname is new entry for Table Y then it gets inserted to 'table y' too
IF Areaname is matching with table y values while the user types the area name on the textfield
then a slider/dropdown which should show the Areanames which are matching for the word he is typing
if he still continues then its treated as new area and gets inserted to table y
Ex:
Areaname |datacount
New york | 1000
California | 500
user 2 enters california again then while typing 'cali' then it should check with 'table y' if matches then it shold show in the slider if not matches then it should be inserted to 'table y'
Thanks in advance mates . Few code snippets i have got here but didn't match for my requirements.
Well I think you can use Jquery to check this, for example using the function .change() you can catch the event when the user change the data in the input, so you can send a post every that the input change to a php file where receive what the user are typing and check the database for results, then you return the results, and with jquery you recive that data and you can put it in a table below the input with the results, so if the user are looking for something that you already have, the results in the table can help him to find it and with a button he can select the result. if he don't want select the result he simplify submit the result and everithing it's saved.
$(document).ready(function(){
$("#yourSelectId").change(function(){
$.post("yourPHPfile.php",{str:$("#yourSelectId").value()},function(dataReturn){
//process the data and put it in a table. if you use json_encode in php
//it's gonna be easire you can use a .each() of jquery to process every
//row in the json and then create an string with the html of the table
//with results and put it in your <table> with .html(stringHtml);
});
});
});
I think this is the easiest way to make it, there can be other option for example the autocomplete (jquery plugin) in a < select>. But I put you an option, let me know if you need more help. Regards. Have a nice day.

PHP multiple records insert

I am attempting to reword my issue.
I have a datatable that can return thousands of records, each with multiple columns. There is a checkbox in the first column that, once the user checks it, they then click a button, and the CONTAINER_NUMBER that is associated with the row is sent to a modal window to be used in a form.
Here is the code for the checkbox:
echo "<tr><td><input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\" name=\"checkMr[]\" /></td>";
This is the javascript that retrieves the CONTAINER_NUMBER and sends it to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
});
$(".modal-body .containerNumber").val( selectedID );
});
});
</script>
This is the section of the modal window that displays the CONTAINER_NUMBER:
<div class="modal-body">
<form action="" method="POST" id="serviceModalForm" name="serviceModalForm">
<input type="text" name="containerNumber" id="containerNumber" class="containerNumber">
Here is the section of PHP that takes the id="containerNumber" and converts it to a PHP variable. After that, there is an INSERT statement that inserts the containerNumber into a database table:
<?php
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$container = mysql_real_escapse_string(stripslashes($container));
$sql = "INSERT INTO myTable (container_num) VALUES ('$container')";
if(mysql_query($sql)){
echo "Insert complete";
}
else {
echo "Insert was not completed";
}
?>
This code is fine. It works good. It does what it's supposed to do...for when the user checks ONE checkbox. It DOES NOT work when the user checks multiple checkboxes.
Basically, from what I've been researching is that I need to separate the records from the variable $container, as there can be multiple containers in that variable, which is why the query does not work when there are more than one container numbers selected.
I need to be able to separate the container numbers and store them in an array or something. The query will read each record separately and generate multiple INSERT statements for each record.
I've tried several times to create an array and get the sql statement to recognize it, but have been unsuccessful. I'm not sure if I'm placing the array in the right place. I'm not sure if this has to be done in the javascript before the container gets sent to the modal window.
I know I need to utilize a FOREACH loop to go through the array, but like I said, I'm not sure where the array needs to go in my code.
Please help. I know I need to learn PDO or MYSQLI. I will be sure to utilize PDO or MYSQLI on my next application. Until then, please help me with this issue.
Thank you, and sorry for so much wording.
Your containerNumber will be posted as a converted string from a js array. Something like id1, id2, id3[...]
In your php code, convert the $container back to an array ($containerArray = explode(",", $container)) and construct the sql dynamically to add all the rows in a single query so that the statment becomes something like
INSERT INTO myTable (container_num) VALUES ('$containerArray[0]'), ('$containerArray[1]')[...]

Dynamically generate the content of Drop Down list via jQuery

I am new to Javascript, JSON and jQuery. So please be easy on me. I have a JSP page that contain a drop down list. The contents of the drop down list are populated when the page is loaded. I wrote a Servlet that return the contain of the drop down list in the form of Map, and convert it to JSON string and sent back to the jsp via response.getWriter().write(json); However I am having trouble to getting the result back from the jsp side, and populate the contain of the drop down list from the result. Here are my codes
customer.jsp
$(document).ready(function() {
getCustomerOption('customer'); //try to pre-populate the customer drop down list
});
function getCustomerOption(ddId) {
var dd = $('#' + ddId);
$.getJSON("http://localhost:8080/WebApps/DDListJASON", function(opts) {
$('>option', dd).remove(); // Remove all the previous option of the drop down
if (opts) {
$.each(opts, function(key, value) {
dd.append($('<option/>').val(key).text(value));
}
}
});
}
down where the drop down list is generated
<select id="customer" name="customer">
<option></option>
</select>
The result is nothing get populated into the list. So sad
I think you are invoking the wrong function in document ready
Shouldn't it be
getInitialOption('customer');
instead of
getCustomerOption('customer');
You may add additional <option> elements to a <select> with the code:
$("#selectID").append("<option>" + text + "</option>");
see: JQuery Docs
I don't understand $(''), but I'm not sure that's the problem either, hard to tell exactly.
I do know it will be quicker if you do create the list of options in-memory and then do one append with .html(options) rather than append them one at a time. That may make it easier to understand also, to build the html up one line at a time and then append it.

Categories

Resources