I'm using the legacy jquery autocomplete plugin and would like to trigger an event if my search box is cleared. Here is my current code:
jQuery(function($){
$("#searchbox").Watermark("Search");
});
$("#searchbox").autocomplete("search_names.php", {
width: 250,
selectFirst: false
});
$("#searchbox").result(function(event, data, formatted) {
if (data) {
filterView( data );
}
});
I've tried using the result trigger but it's expecting a valid result. Any idea how I can trigger an event when the search box is empty? Basically I want to restore the search results prior to the filtered results.
Thanks
a possible solution might be to use the .focus to run a while loop that checks for an empty field when the user is clicked in the search box and close the while loop in using .blur when they leave the searchbox. I haven't tried this, so please let me know if it works. Sincerely,
Kevin
$("#searchbox").focus(function () {
var checkNull = true;
while (checkNull == true){
if (!data) {
if (previous results are not displayed) {
your code here to display prior results;
}
}
}
}
$("#searchbox").blur(function () {
checkNull = false;
}
Related
I have a form where small labels are displayed above each field, once the user adds a value to that field.
This for is sometimes loaded with some of the fields being pre-populated.
How would i check on page load if any of the form fields have a value and if so, have the label visible?
Here's my current code for displaying labels once a field has a value:
$('.form-control').blur(function() {
if( $(this).val() ) {
$(this).prev().show();
}
});
on page load try this:
$('.form-control').each(function() {
if( $(this).val() ) {
$(this).prev().show();
}
});
$(document).ready(function(){
$('.form-control').each(function(){
if($(this).val() != ''){
$(this).prev().show();
}
});
});
On document ready, for each .form-control, if the input's value is not blank, do whatever code you would to show the label.
Using focusout Event wouldn't be much of an overkill, would it?
<script type="text/javascript">
(function ($) {
$(document).ready(function (e) {
// ALTHOUGH BLUR IS OK, ONE COULD SIMPLY BIND THE .form-control CLASSES TO THE focusout EVENT
// THIS ENSURES THAT THERE IS A HIGHER LIKELIHOOD THAT THE FIELD IN QUESTION ONCE HAD FOCUS
// WHICH MAY IMPLY THAT THE USER ALSO INTERACTED WITH THE FIELD IN SOME WAY...
$('.form-control').each(function(elem){
var objElem = $(this);
objElem.focusout(function(evt) {
if ($(this).val()) {
// NOW, YOU SHOULD KNOW WHICH METHOD TO USE TO TRAVERSE THE DOM
// AND GET AT THE LABEL....
// IN YOUR CASE IT SEEMS TO BE THE PREVIOUS ELEMENT BEFORE THE FORM-FIELD.
$(this).prev().show();
}
});
});
});
})(jQuery);
</script>
I have been trying to figure this out for hours, switching it around every which way, but nothing seems to work. Each function works great individually, but I can't seem to get the .change function to fire when the check all button is clicked. What am I doing wrong?
The first function is from this: It selects all the checkboxes, but the change does not affect the second function.
The second function is from this: It changes the class of the divs (and therefore the css), but only if a single checkbox is checked/unchecked.
$(document).ready(function(){
(function() {
var checked = false;
$('button.check-all').click(function() {
checked = !checked;
$('input[class^="orgImgColl\["]').prop('checked', checked);
if (checked) $(this).text('Uncheck All');
else $(this).text('Check All');
});
})();
$('input[class^="orgImgColl\["]').change(function(){
if(this.checked){
$(this).children('table').removeClass('unchecked');
$(this).children('table').addClass('checked');
$(this).siblings('table').removeClass('unchecked');
$(this).siblings('table').addClass('checked');
$(this).parentsUntil('tr').removeClass('unchecked');
$(this).parentsUntil('tr').addClass('checked');
} else {
$(this).children('table').removeClass('checked');
$(this).children('table').addClass('unchecked');
$(this).siblings('table').removeClass('checked');
$(this).siblings('table').addClass('unchecked');
$(this).parentsUntil('tr').removeClass('checked');
$(this).parentsUntil('tr').addClass('unchecked');
}
});
});
here is the HTML/PHP
<div class=\"unchecked\">";
echo "<input class=\"orgImgColl[".$i."]\" style=\"float:right\" type=\"checkbox\" name=\"orgImgColl[]\" value=\"".$row['img_id']."\"/>
<table class="unchecked" id="imgList" cellspacing="0" cellpadding="3" width="90%">
etc.
Just so you know the $i in the input class is for debugging purposes, so you can ignore it.
It is because when you change the checked state using script the change event is not fired, the solution is to trigger the change event manually once the checked property is changed using .change() or .trigger('change')
(function () {
var checked = false;
$('button.check-all').click(function () {
checked = !checked;
$('input[class^="orgImgColl\["]').prop('checked', checked).change();
if (checked) {
$(this).text('Uncheck All');
} else {
$(this).text('Check All');
}
});
})();
Demo: Fiddle
You can improve the selector by changing only those checkboxes which are not in the desired state using something like (not tested)
$('input[class^="orgImgColl\["]')[checked?'not':'filter'](':checked').prop('checked', checked).change();
Demo: Fiddle
Just a quick question regarding this issue i am having. I am using jeditable to edit in place some fields on a page. This is working perfectly. Now I wish to implement some data checking. I have my php code to check the data entered and if its correct, it updates that database, and if it isn't it will return the error. The issue I am having is I want it to spit out the error to tell them but when they click the field again to edit it, it shows the error in the field until a page refresh. What i want it to do is have the same data in the field when they click on it after the error occurs instead of having to refresh the page then click the field again to edit it. Perhaps there is a way to return back the error and pass that into a tooltip of some sort above the field? Of course the way jeditable works is the div is surrounding the field then i have some js calling on my update.php file, this parses what jeditable passes to it and returns a $value to be error checked and by default if it is fine it simply at the bottom of the php "return $value;" to be put back int he field after its been saved in the DB.
Hopefully someone can understand what I am asking here and any assistance would be appreciated.
Easiest way is probably to do some client side validation. Right now you are doing server side validation by checking in PHP when the form is submitted. What are you checking for?Without code it is hard to give you a good example of client side validation.
Basic field checking:
var check_field = $("#field").val();
if (!check_field) { alert("Error message"); } else
{
// submit POST or whatever
}
Edit
Since the MAC address validation algorithm is already written server side, I recommend a separate ajax POST request that calls the checker function. Take the result of that request (true, false) and check it client side. If true, proceed with the update call.
Example:
$("#form").submit(function() {
var mac = $("#macfield").val();
if (!mac) { alert("MAC address can't be empty!"); } else
{
$.POST("checkmacaddress.php", {macval: mac}).success(function(a){
//assuming a comes back as a bool
if (!a) { alert("Invalid MAC!"); } else
{
// if the checker returned true, update the record
$.POST("update.php" ...);
}
});
} });
This doesn't include the checkmacaddress.php but you should be able to handle that if you already have the function on hand.
Hate when I do this, post here then figure out the answer myself...but at least if someone has the same issue they will see it. I found out about the jeditable onsubmit functions...i am using a tooltip to show on hover when editing the field so this will set the tooltip to the error and not submit the data unless its a valid mac.
function isMAC(value) {
teststr = value;
regex=/^([0-9a-f]{2}([:-]|$)){6}$|([0-9a-f]{4}([.]|$)){3}$/i;
if (regex.test(teststr)){
return true;
}
else {
return false;
}
}
$(".edit_mac").editable("edit_mac.php", {
onsubmit: function(settings, data) {
var input = $(data).find('input');
var value = input.val();
if (isMAC(value)) {
return true;
} else {
//display your message
$("#tooltip").html("Bad MAC Address...");
return false;
}
},
indicator : "Saving...",
submitdata: { _method: "put" },
submit : 'Save',
cssclass : "editable",
type : "text"
});
I have a PHP notification system, and the amount of notifications is put into a DIV using jQuery. The only problem is that when there are 0 notifications, the empty DIV still shows up. This is the jQuery I am currently using:
$(document).ready(function() {
$.get('/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
});
setInterval(function() {
$.get('http://localhost/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
}, 8000);
The only problem is that if at document load there is 0 notifications and a notification is added, the badge will not show up, so basically if the element is removed it won't come back unless the page is reloaded, but I made the notification system so that the page wouldn't have to be reloaded. How can I fix this?
.remove() takes the element out of the DOM as well as the content. This is why it doesn't come back unless you reload. Use .fadeOut() or .hide() instead
You should probably do something more like this:
var elm = $('#nfbadge'),
T = setInterval(getCodes, 8000);
function getCodes() {
$.get('/codes/php/nf.php', function(a) {
elm.html(a);
if (elm.is(':empty') && elm.is(':visible')) {
elm.hide();
}else{
elm.show();
}
});
}
Will need some more work on your part, but should get you on the right track!
If you have control over the PHP, you shouldn't be using jQuery to be removing DIVs, it's a waste of resources and load time, even if it's just a few lines of code.
In your PHP template you should include the #nfbadge div in a conditional statement, something like:
if($notifications) {
echo '<div id="nfbadge">';
//notification stuff
echo '</div>';
}
Then with your jQuery code you could do something like the following:
var $nfbadge = $('#nfbadge');
if($nfbadge) {$nfbadge.html(a)}
Why don't you just make the div hidden?
http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/
I'm trying to get the jquery ui autocomplete to work with a codeigniter project.
so far I have an input field <input type="text" id="text1"/>
and then in my script I have
source: function(request, response) {
$.post('autocompleteHandler', {mechanic: request.term}, function(data) {
console.log('data.phpResp = '+data.phpResp);
console.log('in post?');
console.log('data = '+data.toSource);
var realArray = $.makeArray(data); // this line was needed to use the $.map function
response($.map(realArray, function(item) {
console.log('in map');
return {
label: item.info,
value: item.info
}
}));
}, 'json');
},
In my codeigniter controller I have this function
function autocompleteHandler() {
$input = $this->input->post('mechanic');
$this->load->model('login_model');
$results = $this->login_model->search_mechanic_criteria($input);
$mechs= array();
foreach($results as $result) {
$mechs['info'] = $result['mechanic_name'];
}
}
I'm not getting this to work. anyone have any ideas of where I can begin to troubleshoot? I really have a hard time with the jquery ui documentation.
EDIT: I've changed my code a bit. Instead of returning json_encode, I needed to echo json_encode on the php side of things. I still don't have anything showing up in my console though.
2ND EDIT Now my question is, how can I return multiple values for the autocomplete function? If i have a query that returns, just one row, it works fine, but if I have multiple rows returned, doesn't work. It's gotta be something with the way i'm returning the data, but I can't figure it out.
I have been playing around with jsfiddle after you mentioned toSource(). See http://jsfiddle.net/XYMGT/. I find that the map function does not return jQuery, but the new array.
OLD STUFF:
I suspect that the $.map function does not return the array, but jQuery. Maybe it would to do this:
// also you could inspect the data if the server returns what you think it returns:
console.log(data);
// first map the array
$.map(data, function(item) {
console.log('in response?');
return {
label: 'testing',
value: 'test'
}
})
// ...then separately do the response part
response(data);
Lets us know if it makes a difference.
EDIT:
If this PHP code is still used:
function autocompleteHandler() {
echo json_encode(array('phpResp' => 'something'));
}
Then console.log(data) should show the following in the console tab in FireBug:
{'phpResp':'somehting'}
Meaning that console.log(data.phpResp) should print 'something'. I am unsure where you are getting data.toSource from.
I would launch fiddler and see what it says it's returning. You can also go straight to your server side page in the browser that is serving the JSON results. I think the autocomplete automatically adds ?term to the string. url.aspx?term=|valueofText1|
$("#text1").autocomplete({
source: url,
minLength: 2,
select: function (event, ui) {
sou = ui.item.label;
}
});