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.
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;
}
}
I have build a jQuery PHP based instant search, I have used some fading effect along with onblur event, everything is working fine except when clicking anywhere in body for first time results disappear, but again if hover over to input field to bring result and then clicking in body results do not disappers,
i.e onblur does not work second time.
Please see my code for better understanding and suggest any possible way to do this.
JQuery:
$(document).ready(function () {
$('#search-input').keyup(function(){
var keyword=$(this).val();
$.get('../search/instant-search.php', {keyword: keyword}, function(data){
$('#search-result').html(data);
});
});
$('#search-input').keyup(function(){ $('#search-result').fadeIn(400);});
$('#search-input').blur(function(){$('#search-result').fadeOut(400);});
$('#search-input').click(function(){$('#search-result').fadeIn(400);});
$('#search-input').mouseenter(function(){ $('#search-result').fadeIn(400);});
$('#search-input').mouseleave(function(){ $('#search-result').fadeOut(400)});
$('#search-result').mouseenter(function(){ $('#search-result').stop();});
$('#search-result').mouseleave(function(){ $('#search-result').stop();});
});
HTML:
<input name="keyword" type="text" size="50" id="search-input" value = '';" />
<div id="search-result"></div><!--end of search-result-->
Why have you bind so many events to #search-result??
Check below code if it helps you.
<script language="javascript" >
$(document).ready(function () {
$('#search-input').keyup(function(){
var keyword=$(this).val();
$('#search-result').fadeIn(400);
//$('#search-result').html('ajax result data');
$.get('../search/instant-search.php', {keyword: keyword}, function(data){
$('#search-result').html(data);
});
});
$('#search-input').bind('blur', function() {
$('#search-result').fadeOut(400);
});
$('#search-input').bind('focus', function() {
$('#search-result').fadeIn(400);
});
});
</script>
You can try this:
$('#search-input').on('blur', function() {
$('#search-result').fadeOut(400);
});
$('#search-input').on('mouseleave', function() {
// on mouse leave check that input
// is focused or not
// if not focused the fadeOut
if( !$(this).is(':focus')) {
$('#search-result').fadeOut(400);
}
});
$('#search-input').on('focus mouseenter', function() {
$('#search-result').fadeIn(400);
});
DEMO
According to comment
$('#search-input').on('focus mouseenter', function() {
$('#search-result').fadeIn(400);
});
$(document).on('click', function(e) {
if(e.target.id != 'search-input' && e.target.id != 'search-result') {
$('#search-result').fadeOut(400);
}
})
DEMO
how do I change the jquery hint text colour. Currently it is the same colour as the textfield however I would like it to be different!
$(document).ready(function () {
//Shows the title in the text box, and removes it when modifying it
$('input[title]').each(function (i) {
$(this).val($(this).attr('title')).addClass('hint');
$(this).focus(function () {
if ($(this).val() == $(this).attr('title')) {
$(this).val('').removeClass('hint');
}
});
$(this).blur(function () {
if ($(this).val() == '') {
$(this).val($(this).attr('title')).addClass('hint');
}
});
});
//Clear input hints on form submit
$('form').submit(function () {
$('input.hint').val('');
return true;
});
});
you change it in the css the same way as in the last thread I just gave you jQuery code replacement for your hints 10 minutes ago
http://jsfiddle.net/jzCeq/2/
I am trying to check some checkboxes based on it value.
In my code, I can update the database using this ckbxs, but when I try load the updated date, the status is showed as uncheck.
So, I am trying to read the html, after create the form, to check the values and then check the ckbx.
What can I do here to fix it?
Thanks in advance
$(document).ready(function(){
$('input[type=checkbox]').each(function () {
if (this.value == 1) {
(function(){this.attr('checked', true);})
}
} )
})
You need to enclose the thiss in a $( ) and change value to val().
$(document).ready(function(){
$('input[type=checkbox]').each(function () {
if ($(this).val() == 1) {
$(this).attr('checked', true);
}
});
});
$(document).ready(function () {
$('input[type="checkbox"][value="1"]').each(function () {
$(this).attr('checked', true);
});
});
Thanks Willian, now I am using a onChange and I got what I need...
function changerCB(idCheck){
$(document).ready(function() {
$.post('ajaxUpdate.php', {
id: document.getElementById(idCheck).id,
value: document.getElementById(idCheck).checked?1:0
}, function(data){
$('#display').html(data.returnValue)
if(data.success) {
} else {
}
}, 'json');
return false;
});
}
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 + '.');
});