as a follow up to this question, while the checkbox value is stored on pageload, the text is displayed on pageload, even if the checkbox is unchecked. the text should hide/display only if the user has unchecked/checked the checkbox, throughout the session or till he closes the browser.
js code which stores the checkbox state:
function getStorage(key_prefix) {
// this function will return us an object with a "set" and "get" method
// using either localStorage if available, or defaulting to document.cookie
if (window.localStorage) {
// use localStorage:
return {
set: function(id, data) {
localStorage.setItem(key_prefix+id, data);
},
get: function(id) {
return localStorage.getItem(key_prefix+id);
}
};
} else {
// use document.cookie:
return {
set: function(id, data) {
document.cookie = key_prefix+id+'='+encodeURIComponent(data);
},
get: function(id, data) {
var cookies = document.cookie, parsed = {};
cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
parsed[key] = decodeURIComponent(value);
});
return parsed[key_prefix+id];
}
};
}
}
jQuery(function($) {
// a key prefix is used for the cookie/storage
var storedData = getStorage('com_mysite_checkboxes_');
$('div.check input:checkbox').bind('change',function(){
$('#ab_'+this.id).toggle($(this).is(':checked'));
// save the data on change
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
}).each(function() {
// on load, set the value to what we read from storage:
var val = storedData.get(this.id);
if (val == 'checked') $(this).attr('checked', 'checked');
if (val == 'not') $(this).removeAttr('checked');
if (val) $(this).trigger('change');
});
});
this ^code should work, but it while it retains the state of the checkbox, it doesn't for the text. is it because the text is being called from a php page?
html:
$(document).ready(function() {
$("#bquote").load("quotes_in.php");
});
.. ...
<div class="check">
<p><input type="checkbox" value="Name" id="name" checked /> <label for="name">Name</label></p>
<p><input type="checkbox" value="Reference " id="reference" checked /> <label for="reference">Reference</label></p>
</div>
.. ...
<blockquote id="bquote">
</blockquote>
php:
public function formatQuotes($row)
{
return "<p id=\"ab_name\">" . $this->h($row['cName']) . "</p><br />"
. "<p id=\"ab_reference\">" . $this->h($row['vReference']) . "</p>";
}
You need to trigger the change() event on document ready after the p elements are generated.
Edit:
If placing the change trigger after the .load() call does not work, then that is probably due to the ajax request not being completed yet at the point of triggering. This can be solved by using callback parameter of .load(). Therefore, the code should look something like:
$(document).ready(function() {
$("#bquote").load("quotes_in.php", function() {
// create the P elements
// trigger the change() event
});
});
Related
I have a function that on click add/removes stuff from a SQL database.
I do a condition to check if it is refering to an add or remove and execute the code.
the add function works perfectly, but the remove not and its the same code, am i missing something obvious? And is this the best way to do this?
jquery:
//add card from list
$("#listcards a").click(function() {
if($(this).attr('add').length > 1) {
var value = $(this).attr('add');
$.post('searchc.php',{add:value}, function(data){
$("#add_result").html(data);
});
return false;
}
});
//remove card from list
$("#listcards a").click(function() {
if($(this).attr('rem').length > 1) {
var value = $(this).attr('rem');
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
}
});
html code:
<form id="listcards" method="post">
<input type='hidden' id='lcard' name='lcard' value=''>
<div>
bla bla -> imagem no + ? ou por algum efeito css+ | -<br>
coiso coiso + | -<br>
</div>
</form>
Do i also need to be in a form for the POST or a div would work too?
You've got two click handlers for the same elements, which could be causing a problem. You don't need to run both sets of code for each <a> element. Instead give the elements a class to show exactly what they do, and then limit your selectors to those elements
HTML:
+ | <a href="" class="remove" rem="bla bla">
Script:
$("#listcards a.add").click(function() {
var value = $(this).attr('add');
$.post('searchc.php',{add:value}, function(data){
$("#add_result").html(data);
});
return false;
});
//remove card from list
$("#listcards a.remove").click(function() {
var value = $(this).attr('rem');
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
});
You can use it like thisi will give only remove functionality. And oif possible add ajax.
$("#listcards .rem").click(function() {
var value = $(this).text();
if($(this).length()>1) {
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
}});
Suppose you don't have any card when you're loading this page 1st time. Then you click add new & a new card get's added to your html.
Now for this newly added card, the "remove" method doesn't get bind as that was loaded on page load (when this new card element was not present). Hence your remove method is not working for newly added cards.
So to make it work, you need to bing the remove method on new cards too. You can do that by keeping you remove part in a js function which you would call in "add" part after putting new card into html.
function removeCard(){
// first unbind the click event for all cards if any & then bind it
$("#listcards a").off('click');
//remove card from list
$("#listcards a").click(function() {
if($(this).attr('rem').length > 1) {
var value = $(this).attr('rem');
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
}
});
}
And you add part should be like this:
//add card from list
$("#listcards a").click(function() {
if($(this).attr('add').length > 1) {
var value = $(this).attr('add');
$.post('searchc.php',{add:value}, function(data){
$("#add_result").html(data);
removeCard(); // adding remove method here
});
return false;
}
});
Follow up your code,
$("#listcards a").click(function() {
var action = $(this).attr("add") ? "add" : "rem";
var value;
if(action == "add")
value = $(this).attr('add');
if(action == "rem")
value = $(this).attr('rem');
var param = {};
param[action] = value;
$.post('searchc.php',param, function(data){
$("#add_result").html(data);
});
});
Use onclick function to do this
It can help you out
+
-<br>
function addthis(addthis) {
if(addthis.length > 1) {
alert(addthis);
// $.post('searchc.php',{add:addthis}, function(data){
// $("#add_result").html(data);
// });
return false;
}
}
function removethis(remthis) {
if(remthis.length > 1) {
alert(remthis);
// $.post('searchc.php',{reb:remthis}, function(data){
// $("#add_result").html(data);
// });
return false;
}
}
My checkboxes are empty when page refreshes after submit. I would like to keep them checked. How can I do that in jquery?
Here is my jquery code.
$(document).ready(function () {
$(':checkbox.selectall').on('click', function () {
$(':checkbox[id="' + $(this).data('checkbox-name') + '"]').prop("checked", $(this).prop("checked"));
$( "#frm1" ).submit();
});
$(':checkbox.checkme').on('click', function () {
var _selectall = $(this).prop("checked");
if (_selectall) {
$(':checkbox[name="' + $(this).attr('name') + '"]').each(function (i) {
_selectall = $(this).prop("checked");
return _selectall;
});
}
$(':checkbox[name="' + $(this).data('select-all') + '"]').prop("checked", _selectall);
$( "#frm1" ).submit();
});
});
My html is as follows...
<input type='checkbox' id='selectall' name='sa_subcatinput[]' value='$row[id]'
data-checkbox-name='$row[id]' class='selectall'/></label></a></li>
<input type='checkbox' name='subcatinput[]' value='$test[id]' id='$test[category]'
class='checkme' data-select-all='sa_subcatinput[]'/>
You cannot do this unless you send a value back to your page which indicates the checkbox to be checked.Since you said the page refreshes, a server communication is happened. So you may use ajax to keep the check box checked
Pass a querystring parameter of the id or number or value or whatever of the checked checkbox.
request the parameter using server side code or a client-side javascript using a get parameter function (there on many on this site).
rechecked the box using your custom function and the value returned.
$('#ckeckbox1').val(unescape(getParam(document.URL,'checkbox1')));
function getParam(url,name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if( results == null )
return "";
else
return results[1];
}
function removeParameter(url, parameter) {
var urlparts= url.split('?');
if (urlparts.length>=2) {
var urlBase=urlparts.shift(); //get first part, and remove from array
var queryString=urlparts.join("?"); //join it back up
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;) //reverse iteration as may be destructive
if (pars[i].lastIndexOf(prefix, 0)!==-1) //idiom for string.startsWith
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
}
return url;
}
I was able to get the code working with php. Here is the code I inserted in the input to make it work.
echo"<input type='checkbox' id='selectall' name='sa_subcatinput[]' value='$row[id]'
data-checkbox-name='$row[id]' class='selectall'";
if (isset($_POST['sa_subcatinput'])) {
if (in_array($row['id'], $_POST['sa_subcatinput'])) {
echo"checked='checked'";
}
}
echo"/>
echo"<input type='checkbox' name='subcatinput[]' value='$test[id]'
id='$test[category]' class='checkme' data-select-all='sa_subcatinput[]'";
if (isset($_POST['subcatinput'])) {
if (in_array($test['id'], $_POST['subcatinput'])) {
echo"checked='checked'";
}
}
echo"/>
So. I have a Form with a lot of checkboxes. Along with that I have a piece of javascript code that is supposed to save the state of every checkbox when the user presses submit. My short and irritating problem is two things.
Question: I want to save Checkbox state to cookie ONLY when I submit the form, right now it saves if I mark a checkbox and reload the page, without submitting. Im working with Javascript and Cookies, two things that Im quite new to. So Im very greatful for all help. Here is my code that I got from here:
function getStorage(key_prefix) {
if (window.localStorage) {
return {
set: function(id, data) {
localStorage.setItem(key_prefix+id, data);
},
get: function(id) {
return localStorage.getItem(key_prefix+id);
}
};
} else {
return {
set: function(id, data) {
document.cookie = key_prefix+id+'='+encodeURIComponent(data);
},
get: function(id, data) {
var cookies = document.cookie, parsed = {};
cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
parsed[key] = unescape(value);
});
return parsed[key_prefix+id];
}
};
}
}
jQuery(function($) {
var storedData = getStorage('com_mysite_checkboxes_');
$('div.check input:checkbox').bind('change',function(){
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
}).each(function() {
var val = storedData.get(this.id);
if (val == 'checked') $(this).attr('checked', 'checked');
if (val == 'not') $(this).removeAttr('checked');
if (val == 'checked') $(this).attr('disabled','true');
if (val) $(this).trigger('change');
});
});
So I want to save to cookie only on submit basically.
Bind to the submit event of the form instead of the change event of all the checkboxes.
Try this in place of your second function:
jQuery(function($) {
// bind to the submit event of the form
$('#id-of-your-form').submit(function() {
// get storage
var storedData = getStorage('com_mysite_checkboxes_');
// save checkbox states to cookie
$('div.check input:checkbox').each(function() {
// for each checkbox, save the state in storage with this.id as the key
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
});
});
});
jQuery(document).ready(function() {
// on load, restore the checked checkboxes
$('div.check input:checkbox').each(function() {
// get storage
var storedData = getStorage('com_mysite_checkboxes_');
// for each checkbox, load the state and check it if state is "checked"
var state = storedData.get(this.id);
if (state == 'checked') {
$(this).attr('checked', 'checked');
}
});
});
What I want to do
When writing in the text field, I want the <div class="result"> to be filled with what PHP is echoing.
But it doesn't work!
Jquery
$(document).ready(function() {
var search = $("#search");
if (search.val() !== '') {
search.keyup(function() {
$.post("index.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
});
}
});
php
if (isset($_POST['search'])) {
echo 'hello';
}
html
<input type="text" name="search" id="search"/>
<br />
<div class="result"></div>
Problem
When filling the input, nothing happens, and it meant to POST the entered data on keyup (When entering a new character/or deleting.
What is stopping it from working? I am new to jQuery .
Thanks.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
This is wrong.
if (search.val() !== '') {
The above line should be,
if (search.val() != '') {
EDIT:
Then wrap the if condition inside the keyup function.
$(document).ready(function() {
var search = $("#search");
search.keyup(function() {
if (search.val() != '') {
$.post("getInputs.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
}
});
});
When I run into situations like this, I just start breaking the problem in half to see where its failing. Here are a couple things I would try.
First, in your jQuery, add some output to the console:
if (search.val() !== '') {
console.log("I am not empty so I should go to index.php");
search.keyup(function() {
$.post("index.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
});
}
else
{
console.log("search val was empty");
}
Of course you could always check the browsers network profiler to see if it made a POST to that resource. This will tell you if the problem is in your search.val test.
Then, if you want to debug the PHP side, you could remove the isset test and just always return "hello". That will tell you if its an issue with your POST variables or checks.
Finally, you could output the data result to be sure something is coming back at all. This will remove any issues with $(".result").html() being the problem:
$.post("index.php", { search : search.val()}, function(data) {
console.log(data);
$(".result").html(data);
});
If none of these work, maybe you could just switch around the way you bind to keyup in the first place:
$(document).ready(function() {
$("#search").keyup(function() {
if ($(this).val() !== '') {
$.post("index.php", { search : $(this).val()}, function(data) {
$(".result").html(data);
});
});
}
});
$(document).ready(function() {
var search = $("#search");
});
This fire only at document ready but not on keyup, means in var $("#search").val() will be blank.
Change your code to capture inpute value on every key-up stroke.
$(document).ready(function() {
search.keyup(function() {
var value = $("#search").val();
if(value!="")
{
$.post("index.php", { search : value}, function(data) {
$(".result").html(data);
});
}
});
});
Your logic is incorrect. You are only setting the keyup event handler if your #search has text in it. Unfortunately when that script runs on document ready, there is NO value in #search so your keyup handler never gets set, which is why it never fires.
I rewrote some of your logic and was able to get it to work. One being the way your checking to ensure you have a value. Instead of string comparing I am checking the length. Also, instead of binding the event to the field, I bind the event on the document and target the field. Try it:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<input type="text" name="search" id="search"/>
<br />
<div class="result"></div>
<script>
$(document).ready(function() {
$(document).on('keyup', 'input#search', function() {
if($(this).val().length > 0) {
$.post('index.php', {"search":$(this).val()}, function(data) {
$('div.result').html(data);
});
}
});
});
</script>
// when the html is loaded
$(document).ready(function() {
// find an element with the id 'search'
var search = $("#search");
// if this element's value is NOT an empty string -- oh look, it is!
if (search.val() !== '') {
// well, going to skip all this here then
search.keyup(function() { // don't care
$.post("index.php", { search : search.val()}, function(data) { // don't care
$(".result").html(data); // don't care
});
});
}
// YAAAAY! All done!
});
Actually nothing is wrong in your code. I have tried your code itself. Only issue was that you have called keyup function conditionally. Your Javascript code should be like below:
$(document).ready(function() {
var search = $("#search");
search.keyup(function() {
if (search.val() != '') {
$.post("index.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
}
});
});
Here, condition should be inside the keyup function.
I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});