I'v got a question about LiveFilter. Or how to make it in another way without LiveFilter it is not so important. So iv got the page and got divs which are making from JSON file. And my filter is not working. So i got my page like this Before And when im start searching by the name or number it should be like this AfterShouldBe
So im using jquery.livefilter.js
<script> // Reading DATA from JSON
$(document).ready(function(){
$.getJSON("accounts.json", function(data){
$.each(data, function(key, value){
$("#main_list").append(
buildRow(value.name
,value.number
,value.city,value.amount,value.currency,value.rate)
);
});
});
});
</script>
<script>
$(function(){
$('#livefilter-list').liveFilter('#livefilter-input', 'li', {
filterChildSelector: 'a'
});
});
</script>
<script> // Making divs from JSON
function buildRow(a,b,c,d,e,f){
return '<ul id="livefilter-list"><div class="deposit-small-block first-block size-small-block tt" onclick="view(\'t1\'); return false">\
<div class="button_block">\
<div class="div-for-button">\
<input type="radio" name="on">\
</div>\
</div>\
<div class="deposit-form-block-name">\
<div class="deposit-form-block-name-first white-text"><name><li>'+a+'</li></name></div>\
<div class="deposit-form-block-name-second white-text"><number><li>'+b+'</li></number></div>\
<div class="deposit-form-block-name-third white-text"><city>'+c+'</city></div>\
</div>\
<div class="deposit-form-block-sum">\
<div class="deposit-form-block-sum-text white-text">\
<amount>'+d+'</amount><br><currency>'+e+'</currency>\
</div>\
</div>\
<div class="deposit-form-block-perc">\
<div class="deposit-form-block-sum-text white-text"><rate>'+f+'</rate></div>\
</div>\
</div>\
</ul>'
}
</script>
So could someone tell me where is the problem
And here is my rar with files (html, css, js, json)
Forget about liveFilter.js...
Your HTML is too complex for it.
I made a pretty small script for you.... Customized for your web page.
How it works:
On the input event, hide all rows.
Then search the inputted value within <name>, <number> and <city> content... For each rows, using the JavaScript method .indexOf().
If the search term is found, this row must be displayed.
// Custom search
$("#livefilter-input").on("input",function(){
//console.log("Searching...");
// Set ALL rows to display none.
$(".deposit-small-block").css("display","none");
// Loop to check the content of all custom tags: <name> <number> and <city>
$(".tt").find(".deposit-form-block-name .white-text").children().each(function(){
// If a matching text is found within name, account # or city
if( $(this).html().indexOf( $("#livefilter-input").val() ) != -1 ){
//console.log("FOUND a match!");
// Set this row to display block.
$(this).closest(".deposit-small-block").css("display","block");
}
});
});
Place it inside the document ready wrapper, just below the $.getJSON function.
Live link!
EDIT:
For case insensitive search:
Only one line to change:
if( $(this).html().toLowerCase().indexOf( $("#livefilter-input").val().toLowerCase() ) != -1 ){
Related
I am making a project of a chat app, I made a code that if the user is not your user it will be in the left side, and if the user is your user it will be on the right side, the code I do works, but there is a single error. The problem is that I do this:
html
<div class="msg right-msg" id="side">
<div class="msg-img" style="background-image: url(https://image.flaticon.com/icons/svg/145/145867.svg)"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">{{ chat.user }}</div>
<div class="msg-info-time"></div>
</div>
<div class="msg-text">{{ chat.message }}</div>
</div>
</div>
javascript
$( "#side" ).each(function() {
//console.log( index + ": " + $( this ));
var users = $(".msg-info-name").text()
if (users != me) {
$("#side").removeClass("msg right-msg");
$("#side").addClass("msg left-msg");
};
});
The problem is that there are many of the same html code(That has the same id, class, etc..), So I realized that I can use id in only one, I use id and this was the product Image of the product, it only change the place in the first one, So that doesn´t work.
So I try using class but instead of changing the first one side it change nothing, so class doesn´t works. What can I do?, is another way to loop into all of this, ALSO, the javascript example is using id's. thank for the help
use class not id for multiple elements.
$( ".msg" ).each(function() {
var users = $(this).find(".msg-info-name").text();
if (users != me) {
$(this).removeClass("msg right-msg");
$(this).addClass("msg left-msg");
};
});
I don't know if it's possible, but I need to send some information across a form ou inside url come from checkbox value.
This code below is inside a products loop and create a checkbox on every products (product comparison approach).
In my case, it's impossible to make this code below across a form.
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
To resolve this point, I started to use an ajax approach and put the result inside a $_SESSION
My script to for the checbox value
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty create the list via ajax
if (chkArray.length !== 0) {
$.ajax({
method: 'POST',
url: 'http://localhost/ext/ajax/products_compare/compare.php',
data: { product_id: chkArray }
});
}
});
});
And at the end to send information on another page by this code. Like you can see there is no form in this case.
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
No problem, everything works fine except in my compare.php file, I have not the value of my ajax. I inserted a session_start in ajax file
But not value is inserted inside compare.php.
I tried different way, include session_start() inside compare.php not work.
My only solution is to include in my products file a hidden_field and include the value of ajax across an array dynamically, if it's possible.
In this case, values of hidden_fields must be under array and sent by a form.
This script must be rewritten to include under an array the chechbox value
without to use the ajax. How to insert the good code?
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty show the <div> and create the list
if (chkArray.length !== 0) {
// Remove ajax
// some code here I suppose to create an array with the checkbox value when it is on true
}
});
});
and this code with a form
<?php
echo HTML::form('product_compare', $this->link(null, 'Compare&ProductsCompare'), 'post');
// Add all the js values inside an array dynamically
echo HTML::hidddenField('product_compare', $value_of_javascript);
?>
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
</form>
Note : this code below is not included inside the form (no change on that).
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
My question is :
How to populate $value_of_javascript in function of the checkbox is set on true to send the information correctly inside compare.php
If my question has not enought information, I will edit this post and update in consequence.
Thank you.
You cannot pass JavaScript Objects to a server process. You need to pass your AJAX data as a String. You can use the JavaScript JSON.stringify() method for this...
$.ajax({
method: 'POST',
url : 'http://localhost/ext/ajax/products_compare/compare.php',
data : JSON.stringify({product_id: chkArray})
});
Once that has arrived at your PHP process you can turn it back into PHP-friendly data with PHP JSON methods...
<?
$myArray = json_decode($dataString, true);
// ... etc ... //
?>
See:
JSON # MDN
JSON # PHP Manual
Example: Form Submission Using Ajax, PHP and Javascript
This question has been asked on a few occasions, for example:
Store Cloned Element in Variable
Copy DOM Element
However, I'm having issues selecting say <div id="XYZ"></div> and cloning it to a variable for the jQuery DataTable fnStateSaveParams to save. When the page refreshes it is then meant to reload the cloned object back into the HTML via fnStateLoadParams. I am trying to use .clone() over .html() because I also need the values stored within the dynamically generated textboxes.
If I'm not saving and loading via the Datatables plugin, then it works perfectly. As soon as I try calling code similar to the below then it ceases to work (please bare in mind I've tried a number of variations to the below code). Has anyone got any ideas or suggestions?
"fnStateSaveParams": function (oSettings, oData) {
var clonedHtml= $("#XYZ").clone(true);
oData.storedHtml = clonedHtml;
},
"fnStateLoadParams": function (oSettings, oData) {
//$("#displayHtml").append(oData.storedHtml);
//$("#displayHtml").html(oData.storedHtml);
//$(oData.storedHtml).prependTo("#displayHtml")
}
<div id="XYZ">
<div data-template="">
<label class="bolder"></label>
<div class="input-append">
<div class="inline-block advancedSearchItem">
<input type="text" id="test1" value="Test Scenario" />
</div>
<a href="#" data-id="" class="btn btn-small btn-danger removeField">
<div class="hidden-phone">Remove</div>
<i class="icon-trash icon-only hidden-tablet hidden-desktop"></i>
</a>
</div>
</div>
</div>
The end scenario will be more complex, however the above is the simplest form of what I am trying to create. If you need more information, feel free to ask and I'll update the question accordingly.
I didn't find a way of utilising .clone() to grab all HTML and Text Box values. However, I did come up with a solution and the code below is for anyone who needs a reference point.
Using .html() (as most will know) will only copy the available HTML and ignore what is essentially 'placeholder' text within text fields. My solution though is to force the value into the HTML rather than being treated as 'placeholder' text, this allows it to be used again when the page is loaded.
$(document).on("click", "#advancedSearchButton", function(event) {
event.preventDefault();
// DO SOME STUFF HERE
$("[data-value]").each(function(index) {
if (index > 0) {
fieldCount++;
$(this).attr("value", $(this).val());
}
});
oTable.fnFilter("");
});
function loadData() {
// ... ... ...
"fnStateSaveParams": function(oSettings, oData) {
oData.advancedSearchHtml = $("#addedSearchFields").html();
oData.fieldCount = fieldCount;
oData.isAdvancedSearch = isAdvancedSearch;
},
"fnStateLoadParams": function(oSettings, oData) {
$("#addedSearchFields").html(oData.advancedSearchHtml);
if (oData.isAdvancedSearch == true) {
$("#collapseElement").removeClass("collapsed");
$("#collapseIcon").removeClass().addClass("icon-chevron-up");
$("#filter").hide();
}
isAdvancedSearch = oData.isAdvancedSearch;
advancedSearchFields = oData.fieldCount;
}
// ... ... ...
}
There are multiple paragraphs in the page. Each paragraph must be followed by a div with two buttons Add and Edit. Clicking the Add button should create a textarea dynamically above it.
Related references that didn't work:
How to use jQuery to add form elements dynamically
How to add (clone) form fields using jQuery and increment ids and names
DEMO
HTML code:
<div id="notes"></div>
In my JavaScipt:
<script>
// get notes in json format from php array
var notes = <?php echo json_encode($notes); ?>;
// call the scan function to iterate through the notes
scan(notes);
function scan(obj)
{
jQuery.each(obj, function(key, val) {
if (val instanceof Object) {
for ( var v in val ) {
if (val[v]['type'] == 'Topic') {
$("#notes").append('<h2 class="topic">'+val[v]['content']+'</h2>');
}
if (val[v]['type'] == 'Subtopic') {
$("#notes").append('<h4 class="subtopic">'+val[v]['content']+'</h4>');
}
if (val[v]['type'] == 'Concept') {
$("#notes").append('<h5 class="concept">'+val[v]['content']+'</h5>');
}
if (val[v]['type'] == 'Paragraph') {
$("#notes").append('<p>'+val[v]['content']+'</p>');
// append input for all paragraphs
$('#notes').append('<div class="paragraphs">');
$('#notes').append('<div id="block">');
$('#notes').append('<p class="edit"></p>');
$('#notes').append('<p>');
$('#notes').append('<div id="para">');
$('#notes').append('<p><textarea cols="40" rows="2" id="textarea"></textarea></p>');
$('#notes').append('<button id="add" class="add success tiny">Add</button>');
$('#notes').append(' ');
$('#notes').append('<button id="startEdit" class="canEdit tiny">Edit</button>');
$('#notes').append('</div>');
$('#notes').append('</p>');
$('#notes').append('</div>');
$('#notes').append('</div>');
}
scan(val[v]);
}
}
});
};
// Add paragraph button
i = 1;
$('#textarea'+i).hide();
text = $('#textarea'+i).text();
var data = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';
$('.paragraphs').on('click', '#add'+i, function() {
if ( $('#add'+i).text() == "Add" ) {
ajaxRequest(data, 'editNotes', 'POST'); // POST request on editNotes
$('#textarea'+i).show();
$('#add'+i).text('Save');
$('#textarea'+i).focus(function() {
this.select();
});
}
else if ( $('#add'+i).text() == "Save" ) {
ajaxRequest(data, 'saveNotes', 'POST'); // POST request on saveNotes
if ($('#textarea'+i).val() == ''){
alert('Enter something...');
} else {
$('#add'+i).text("Add");
$('#textarea'+i).hide();
var overview = $('#textarea'+i).val();
i++;
console.log('after: i='+i);
$('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
}
}
});
</script>
How do I add the form elements dynamically with incremental id and class names?
Any help is appreciated
unfortunately append does not work like it may seem, when you submit something like:
$('#element').append('<div>start here'):
$('#element').append('end here</div>'):
The very first call sent will close the div, it will actually create 2 separate elements. One way to help with this rather than having a large append as it can get kinda messy, is to create a variable and place all the elements into that variable and append it.
Example:
http://jsfiddle.net/h8V93/
var appends='<div class="paragraphs">'
+'<div id="block">'
+'<p class="edit"></p>'
+'<p>'
+'<div id="para">'
+'<p><textarea cols="40" rows="2" id="textarea"></textarea></p>'
+'<button id="add" class="add success tiny">Add</button>'
+' '
+'<button id="startEdit" class="canEdit tiny">Edit</button>'
+'</div>'
+'</p>'
+'</div>'
+'</div>';
$('#notes').append(appends);
I hope this helps.
Update
Edit for further reading, the best way to actually do this is to create an html page as a separate file and include it like so:::
$.get("<urlhere>", function (data) {
//Append, After, Before, Prepend data or whatever you want to do with it.
});
This is very convenient in GM or TM scripts where you keep the html file on your own server.
Hope this update helps future readers.
in recent versions of TM (tampermonkey), because of added cross domain origin policies, use GM_xmlhttpRequest -> http://wiki.greasespot.net/GM_xmlhttpRequest
I have an application (drag and drop using JqueryUI.GridSort) that allows the user to upload photos, and then sort the photos in the order that they would like using drag and drop.
On page load, the user is prompted to upload photos which are posted to the next page. When they arrive on the next page my php script creates a <ul id="sortable"> containing <li> for each of the files they uploaded. For each picture that they have uploaded to the site, a new <li> is created. Inside of that <li> is a <img> that sets the picture for <li> with the image they have uploaded.
My goal is to be able to "save" the order of the pictures after they have arranged them in the drag and drop interface. For example, once they have finished arranging and sorting the pictures in the order they want them in, I would like to be able to send them another page that creates an xml file ( I don't need help with the XML, only saving the order) with using the list that they created in the correct order.
After hours of tinkering with PHP, I have come to realization that because PHP is a serverside language, it cannot see what is sorted post render. So my question is, is there a way to have JavaScript or Ajax read the current order of the list, and post it to the next page? If you do know how, could you please provide an example of both the POST from one page, and the post receiving on the other? I am not very familiar with Ajax.
Thank you greatly for any assistance you could provide.
Sample Code (The contents of the foreach statement that creates a LI for each file uploaded)
$imgID++;
echo '<li class="ui-state-default"><img id="'.$imgID.'"'.' src="user_files/'.$file_name.'" draggable="true" height="90" width="95"></li>';
EDIT
main page :
<script>
$('#my_form').on('submit', function() {
var ordered_list = [];
$("#sortable li img").each(function() {
ordered_list.push($(this).attr('id'));
});
$("#ordered_list_data").val(JSON.stringify(ordered_list));
});
</script>
<div id="tesT">
<form id="my_form" action="update_data.php">
<!-- other fields -->
<input type="hidden" id="ordered_list_data"></input>
<input type="submit" value="Proceed to Step 2"></input>
</form>
</div>
update_data.php:
<?php
// process other fields as normal
if(isset($_POST['ordered_list_data'])) {
$img_ordering = json_decode($_POST['ordered_list_data']);
echo "1";
} else {
echo "nodata";
}
// do things with the data
?>
I built a JSFiddle doing basically the same thing that David posted.
I added a piece to write out the result to a div on the page, so you can see what's going on:
<input type="button" id="savebutton" value="save"/>
<div id="output"></div>
<form id="listsaveform" method="POST" action="script.php">
<input type="hidden" name="list" id="hiddenListInput" />
</form>
Javascript:
$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
$( "#savebutton" ).click(function() { LISTOBJ.saveList(); });
});
var LISTOBJ = {
saveList: function() {
var listCSV = "";
$( "#sortable li" ).each(function() {
if (listCSV === "") {
listCSV = $(this).text();
} else {
listCSV += "," + $(this).text();
}
});
$("#output").text(listCSV);
$("#hiddenListInput").val(listCSV);
//$("#listsaveform").submit();
}
}
If you're using a <form> you can do something like this (assuming jQuery is being used):
$('#my_form').on('submit', function() {
var ordered_list = [];
$("#sortable li img").each(function() {
ordered_list.push($(this).attr('id'));
});
$("#ordered_list_data").val(JSON.stringify(ordered_list));
});
In essence, what you're doing is looping over the <ul>, fetching each <img> and appending the ids (in order of appearance) to an array. Arrays preserve ordering in JavaScript and JSON, so one can turn it into a JSON string using the JSON.stringify function, set it as the value of a <input type="hidden"> field and then submit the form.
If you want to use AJAX, the functionality is very similar. However, instead of using an onsubmit (or onclick) you'd use $.post.
Let's go with the <form> option since it's simpler. All told you'll have something similar to the above JS along with HTML like this:
<form id="my_form" method="post" action="./update_data.php">
<!-- other fields -->
<input type="hidden" name="ordered_list_data" id="ordered_list_data"></input>
<input type="submit" value="Submit"></input>
</form>
Then, in update_data.php (or whatever your script is named):
<?php
// process other fields as normal
if(isset($_POST['ordered_list_data'])) {
$img_ordering = json_decode($_POST['ordered_list_data']);
} else {
// handle case where there is no data
}
// do things with the data
?>