Show/hide by post id - javascript

I use some script to hide full content , but i have problem this only hide my first div in while.
script:
$('#blah').css({height:'20px', overflow:'hidden'});
$('#blah').on('click', function() {
var $this = $(this);
if ($this.data('open')) {
$this.animate({height:'20px'});
$this.data('open', 0);
}
else {
$this.animate({height:'100%'});
$this.data('open', 1);
}
});
And while php code , just wanna to show all rows from database and all result from db must to be hidden not just the first one..
PHP code:
$fq = mysqli_query("SELECT * FROM `table` ORDER BY time DESC LIMIT");
while($f = mysqli_fetch_array($fq)){
echo "
<div id='blah'>$link</div>
";
}
I just wanna to all results from db be hidden and can be ellapsed by postid , anyhelp?
Best regards

Selecting elements via jQuery using ID only selects the first occurence.
If you want to select many elements, dont use ID, use Class
while($f = mysqli_fetch_array($fq)){
echo "
<div class='blah'>$link</div>
";
}
On you script :
$('.blah').css({height:'20px', overflow:'hidden'});
$('.blah').on('click', function() {
var $this = $(this);
if ($this.data('open')) {
$this.animate({height:'20px'});
$this.data('open', 0);
}
else {
$this.animate({height:'100%'});
$this.data('open', 1);
}
});

Related

Set custom attribute for autodividers

I am trying to divide a ListView that is dynamically populated in jQuery-mobile. I am setting some listitems with attribute status="true" and some to status="false", and wonder if it's possible to automatically divide these into two groups (Downloaded/Not downloaded)?
This is my HTML:
<div role="main" class="ui-content jqm-content">
<div>
<ul id="linkList" data-role="listview" data-autodividers="true">
</ul>
</div>
</div>
My JS:
var $li;
var $status = 'false';
window.resolveLocalFileSystemURL(fileSource + val.title + ".pdf", success, fail);
// if file exists
function success() {
$li.find("a").on("click", function(){ openPdf(val.title); });
$status = 'true';
}
// if file doesnt exists
function fail() {
$li.find("a").on("click", function(){ downloadPdf(val.title,val.url); });
$status = 'false';
}
$li = $("<li><a href='#' status=''+status+''>"+val.title+"</a></li>");
$("#linkList").append($li).listview('refresh');
$("#linkList").listview({
autodividers: true,
autodividersSelector: function (li) {
var out = li.attr('status');
return out;
}
}).listview('refresh');
So, is it possible to do this automatically, or do I have to do the sorting by code, and add the dividers. The code as it is doesn't add any dividers at all.
First, autodividers really only works if your list is already sorted by status. So you will want to sort it before adding it to the UL.
Next, for status you can use a data-attribute on the LI or the anchor within the li:
'<li >' + item.val + '</li>'
Then when adding the items, set the autodividersSelector to retrieve the data-attribute on the anchor:
$('#linkList')
.empty()
.append(allfiles)
.listview({
autodividers:true,
autodividersSelector: function ( li ) {
var out = li.find('a').data("status");
return out;
}
})
.listview("refresh");
Working DEMO

jQuery move table row's with inputs and change id/name

I need to have buttons for moving up and down table rows with input's inside.
On move I need to guarantee that the input's name's and id's are changed
regarding to their new position
I've tried around on JSFiddle but couldn't get it to work: http://jsfiddle.net/vaDkF/1194/
For example I've the first row is moved down there are four changes:
<input type="text" id="id_1" name="id_1"/>
<input type="text" id="test_1" name="test_1"/>
needs to become
<input type="text" id="id_2" name="id_2"/>
<input type="text" id="test_2" name="test_2"/>
but the values need's to stay the same just need the id/name to change.
This is just a test example, in production environment I have like 20 inputs
per row.
Hope someone can help.
Try this : after rearranging the rows, call a function which will reassigne id and name to the input fields
$(document).ready(function(){
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
reAssignIdAndName();
});
reAssignIdAndName = function(){
$('table tr').each(function(index){
$(this).find('td:eq(2) input').each(function(){
//id of input element
var id = $(this).attr('id');
//get index of underscrore
var underScoreIndex = id.indexOf('_');
//take id till underscore and append your index+1 value
id = id.substring(0,underScoreIndex+1)+(parseInt(index)+1);
//assigne new id and name
$(this).attr('id',id);
$(this).attr('name',id);
});
});
};
});
Demo
This works and reAssign the position only for the 2 rows that moved :
jQuery(document).ready(function($){
$(".up,.down").click(function(){
var $this = $(this),
row = $this.parents("tr:first");
if ($this.is(".up")) {
if (row.parent().find("tr:first").get(0) !== row.get(0)) {
reAssignPosition(row.prev().find('input'));
row.insertBefore(row.prev());
reAssignPosition(row.find('input'), true);
}
} else {
if (row.parent().find("tr:last").get(0) !== row.get(0)) {
reAssignPosition(row.next().find('input'), true);
row.insertAfter(row.next());
reAssignPosition(row.find('input'));
}
}
});
function reAssignPosition($elt, up) {
var $row = $elt.parents("tr:first"),
oldPosition = parseInt($row.find('input').attr('id').replace(/(id|test)_/, '')),
newPosition, newId, newName, input = $row.find('input');
if (up) newPosition = oldPosition - 1;
else newPosition = oldPosition + 1;
$elt.each(function() {
this.id = this.id.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
this.name = this.name.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
});
}
});
Some refactoring can be done, I am sure, though.

Javascript - Conditionally add checkbox to php page if cookie exists

I have some Javascript that adds some disclaimer text and a confirmation CheckBox, just before a submit button on a PHP/WordPress page. What I'd like to happen is the script checks for the existence of a cookie. If cookie doesn't exist (or has expired), then to add the disclaimer text, the checkbox and force the user to click the Checkbox before proceeding. But once done, a cookie is written so that the next time the script runs, if bypasses the disclaimer text, checkbox and just allows the user to hit 'submit'.
So, something like:
if cookie-exists {
// straight to submit part of the code
} else {
// show disclaimer and checkbox
// Only allow user to hit submit if checkbox is ticked
// Set the cookie with an expire of a day
}
I can see an answer on setting / reading a cookie here > How do I create and read a value from cookie?
But I'm just struggling to get it into the code snippet below.
Any pointers or help would be greatly appreciated. Thanks.
Code snippet follows:
function add_listing_select_cb()
{
?>
<script type="text/javascript">
jQuery(document).ready(function ($){
var checkbox_cont = '<br><input type="checkbox" name="I_Agree" id="I_Agree" value="I_Agree" /> <b>Disclaimer text here....</b>';
jQuery(".property-search input[type='submit']").before(checkbox_cont);
jQuery("#searchform").submit(function () {
if (!jQuery("#I_Agree").is(":checked")) {
alert("Please first agree with the terms.");
return false;
};
});
var $sel = $('#showresultsbasedonourratings'),
$opts = $sel.children();
$optsSorted = [];
$optsSorted.push($opts.eq(0));
for (var i = $opts.length - 1; i > 0; i--) {
$optsSorted.push($opts.eq(i));
};
console.log($optsSorted);
$sel.empty();
$sel.append($optsSorted);
});
</script>
<?php
}
Have you tried something similar to this?
function add_listing_select_cb()
{
?>
<script type="text/javascript">
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
jQuery(document).ready(function ($){
if (getCookie("anything")!==true){
var checkbox_cont = '<br><input type="checkbox" **required** name="I_Agree" id="I_Agree" value="I_Agree" /> <b>Disclaimer text here....</b>';
jQuery(".property-search input[type='submit']").before(checkbox_cont);
jQuery("#searchform").submit(function () {
if (!jQuery("#I_Agree").is(":checked")) {
alert("Please first agree with the terms.");
return false;
};
});
}
var $sel = $('#showresultsbasedonourratings'),
$opts = $sel.children();
$optsSorted = [];
$optsSorted.push($opts.eq(0));
for (var i = $opts.length - 1; i > 0; i--) {
$optsSorted.push($opts.eq(i));
};
console.log($optsSorted);
$sel.empty();
$sel.append($optsSorted);
});
</script>
<?php
}

How can I delete the selected messages (with checkboxes) in jQuery?

I'm making a messaging system and it has a lot of AJAX. I'm trying to add a bulk actions feature with check boxes. I've added the checkboxes, but my problem is that I don't know how to make something happen to the selected messages.
Here's my function that happens whenever a checkbox is clicked:
function checkIt(id) {
if ($('#checkbox_' + id).is(':checked')) {
$('#' + id).addClass("selected");
}
else {
$('#' + id).removeClass("selected");
}
}
But, I don't know where to go from there.
Here is some example markup for one of the lines [generated by PHP] of the list of messages:
<div class="line" id="33" >
<span class="inbox_check_holder">
<input type="checkbox" name="checkbox_33" onclick="checkIt(33)" id="checkbox_33" class="inbox_check" />
<span class="star_clicker" id="star_33" onclick="addStar(33)" title="Not starred">
<img id="starimg_33" class="not_starred" src="images/blank.gif">
</span>
</span>
<div class="line_inner" style="display: inline-block;" onclick="readMessage(33, 'Test')">
<span class="inbox_from">Nathan</span>
<span class="inbox_subject" id="subject_33">Test</span>
<span class="inbox_time" id="time_33" title="">[Time sent]</span>
</div>
</div>
As you can see, each line has the id attribute set to the actual message ID.
In my function above you can see how I check it. But, now what I need to do is when the "Delete" button is clicked, send an AJAX request to delete all of the selected messages.
Here is what I currently have for the delete button:
$('#delete').click(function() {
if($('.inbox_check').is(':checked')) {
}
else {
alertBox('No messages selected.'); //this is a custom function
}
});
I will also be making bulk Mark as Read, Mark as Unread, Remove Star, and Add Star buttons so once I know how to make this bulk Delete work, I can use that same method to do these other things.
And for the PHP part, how would I delete all them that get sent in the AJAX request with a mysql_query? I know it would have to have something to do with an array, but I just don't know the code to do this.
Thanks in advance!
How about this
$('#delete').click(function() {
var checked = $('.inbox_check:checked');
var ids = checked.map(function() {
return this.value; // why not store the message id in the value?
}).get().join(",");
if (ids) {
$.post(deleteUrl, {idsToDelete:ids}, function() {
checked.closest(".line").remove();
});
}
else {
alertBox('No messages selected.'); // this is a custom function
}
});
Edit: Just as a side comment, you don't need to be generating those incremental ids. You can eliminate a lot of that string parsing and leverage jQuery instead. First, store the message id in the value of the checkbox. Then, in any click handler for a given line:
var line = $(this).closest(".line"); // the current line
var isSelected = line.has(":checked"); // true if the checkbox is checked
var msgId = line.find(":checkbox").val(); // the message id
var starImg = line.find(".star_clicker img"); // the star image
Assuming each checkbox has a parent div or td:
function removeDatabaseEntry(reference_id)
{
var result = null;
var scriptUrl = './databaseDelete.php';
$.ajax({
url: scriptUrl,
type: 'post',
async: false,
data: {id: reference_id},
success: function(response)
{
result = response;
}
)};
return result;
}
$('.inbox_check').each(function(){
if ($(this).is(':checked')){
var row = $(this).parent().parent();
var id = row.attr('id');
if (id == null)
{
alert('My selector needs updating');
return false;
}
var debug = 'Deleting ' + id + ' now...';
if (console) console.log(debug);
else alert(debug);
row.remove();
var response = removeDatabaseEntry(id);
// Tell the user something happened
$('#response_div').html(response);
}
});

jquery removing string parts from two areas

I'm looking to expand on a recent script i've coded using jquery.
I have this following code
<script type='text/javascript'>
added_departments = new Array();
$("#departments_submit").click(function(){
var depo = $("#depo_list").val();
if(jQuery.inArray(depo, added_departments) != -1)
{
return false;
}
else
{
added_departments.push(depo);
$("#depo_added_list").append("<li>" + depo + "<a href='#' title='"+ depo +"' class='remove_depo'> [X] </a></li>");
var current_value = $("#departments").val();
if(current_value)
{
$("#departments").val(current_value + "," + depo);
}
else
{
$("#departments").val(depo);
}
return false;
}
});
</script>
The above code takes information selected in a select drop down box, adds it to a div to display publicly and also into a hidden form field that processes the data.
i've tried to create now something that will reverse this effect and remove certain selections from the div and the field. which is where i have this code
<script type='text/javascript'>
$(".remove_depo").click(function(){
var removing = $(this).title();
var current_val = $("#deparments").val();
if(current_val == removing) {
$("departments").replace(removing, "");
}
else {
$("departments").replace("," + removing, "");
}
});
</script>
It doesn't cause any errors, but it doesn't do anything either? So I'm really stuck. Any ideas?
EDIT: Updated code
$(".remove_depo").click(function(){
var removing = $(this).attr('title');
var current_val = $("#deparments").val();
if(current_val == removing) {
$("#departments").replace(removing, "");
}
else {
$("#departments").replace("," + removing, "");
}
});
Here is the html
<form method="post" action="javascript:void(0);">Select Departments To Be Added:
<div class="depo_adder">
<select id="depo_list"><option value="">--- INDIVIDUAL TAGS ---</option><option value="blah">blah</option></select>
<button id="departments_submit">Go!</button>
</div></form><form method="post" action="briefings/addbriefing.php">
<div class="form">
<strong>Departments: </strong>
<ul id="depo_added_list"><li>blah [X] </li></ul>
<input name="departments" id="departments" value="blah" type="hidden">
</div>
you're referring to $('departments') - this won't work. You need to specify either an identifierm eg $('#departments') or a class, eg $('.departments)
ah - other answer is also correct, .title() is not a function. You want
$('#foo').attr('title') to get the title.

Categories

Resources