I'm setting up an autosuggest where a person can enter a state and get referred to a page on my website. I am linking this to a database because once I get this simple example working I will have 50,000 places in a database to look up. Right now I just have states.
Everything works good except that when a user selects a state from the list, the name filled out in the box is the url link that I am sending them too rather than the correct label. (But I am still going to send them to a url.) Its a small point but it just doesn't look right. Any ideas?
jQuery(document).ready(function($){
$('#searchbox').autocomplete({
source:'suggest.php',
minLength:1,
select: function(event, ui) {
$( "#searchbox" ).val( ui.item.label );
var url = ui.item.value;
if(url != '#') {
window.location.href = url;
}
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
});
The php returns both the web link and the label being searched:
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['Label'],
'value' => $row['Link']
);
}
Here is the example running 1
It looks like the select method's default behaviour is to set the textbox to use value instead of label. So using $( "#searchbox" ).val( ui.item.label ); won't work, regardless of the string you put in there. In that case, we should stop the default behaviour.
Putting event.preventDefault() in the select function seems to fix the problem.
select: function(event, ui) {
event.preventDefault();
$( "#searchbox" ).val( ui.item.label );
var url = ui.item.value;
if(url != '#') {
window.location.href = url;
}
}
Related
Ok guys here's the fiddle
http://jsfiddle.net/wKbXx/24/
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
} else {
$('option[value=' + this.value + ']').remove();
}
});
});
What I need to do is to select two colors with the check boxes. Let say red, and blue. Then using the select, Mark one red and one blue. Then check green. I want it to keep the selected data. Right now once you select green it wipes that data. How can I do that?
UPDATED TO REFLECT WORKING ANSWER.. UPDATED FIDDLE TOO
I would go for a slightly different approach; instead of always resetting the select boxes, I would check whether the text in the changed checkbox is already contained in the select boxes. If it is, I would assume it's been unchecked and remove the option from the select boxes. Otherwise I would append just that new option to the select boxes.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if (sel.find('option').text().indexOf(this.id) > 0) {
$('option[value=' + this.value + ']').remove();
} else {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
});
});
The downside with this version is that the order of the colors in the select boxes is determined by the order in which the checkboxes are clicked; with your version, the order of the colors in the select boxes is always the same as in the checkboxes.
(Hope that made sense.)
Here's a fiddle: http://jsfiddle.net/Niffler/0hLxzvh8/
This may be the answer to your question...
You should have your rewrite on top as well.
$(function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]' ).on( 'change', function() {
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
else {
//Remove where ID matches up
sel.children().remove();
}
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
});
});
Cheers!
You need to get the value of the select box before you replace the options, then reset the value at the end.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.each(function(){
sel.data('previous', sel.val());
});
// overwrite the existing options
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]:checked' ).each( function() {
sel.append( $("<option />").val(this.value).text( this.id ) );
});
// if it had a value, set it back to that.
if ( currentValue != '' ){
sel.each(function(){
sel.val(sel.data('previous'));
});
} else {
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
}
});
});
What i intend to do is change view(grid or list) with cakephp.
So what i've done was this:
$( document ).ready(function() {
$(".lista_options #gridview").click(function(){
$( "#content" ).addClass( 'cubos' );
});
$(".lista_options #listview").click(function(){
$( "#content" ).removeClass( 'cubos' );
});
});
The problem here is that i have a paginator, and for that reason when i change page to get more results the view that i choose doesn't stays. My question how can i change my view mode and be constant during all pagination?
Any suggestion is good. Thanks in advance.
Share your changes using cookies and (or) sessions. When you click to switch between list and grid, save changes to the cookie, on page load read the cookie and uses its value.
EDIT: update code
use this jquery plugin
in your javascript add:
$( document ).ready(function() {
$(".lista_options #gridview").click(function(){
$( "#content" ).addClass( 'cubos' );
$.cookie.raw = true;
$.cookie('CakeCookie[switch]', 'grid', { expires: 7, path: '/' });
});
$(".lista_options #listview").click(function(){
$( "#content" ).removeClass( 'cubos' );
$.cookie.raw = true;
$.cookie('CakeCookie[switch]', 'list', { expires: 7, path: '/' });
});
});
AppController::beforeFilter();
if($this->Cookie->check('switch')){
$this->set('style', $this->Cookie->read('switch'));
}
index.ctp
<div class="<?php if($style == 'grid'){ ?> cubos <?php } ?>" > ...
I'd like have a button on my page that display a form (in a div) which includes text box and two buttons.
I'm not too familiar yet with jquery but I did do some reading and have tried to base my code on an example found here at: http://jqueryui.com/demos/dialog/#modal-form
I have a button that looks like:
<input type='button' class='btn btn-info' value='Change VLAN' id='changevlan'/>
and a div that contains the details of the pop form that I want:
<div id="dialog-form" title="Change Vlan">
<p>You must supply a new vlan number</p>
<form>
<fieldset>
<label for="vlan">Vlan Number:</label>
<input type="text" name="vlan" id="vlan" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
And then at the bottom of my page, i have included the jquery and jquery ui libraries (I loaded at bottom for faster page loading) and I have the following javascript: (I based it off the example i mentioned at the beginning of this post.)
<script type="text/javascript">
$(function() {
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
$( "#dialog:ui-dialog" ).dialog( "destroy" );
var vlan = $( "#vlan" ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Change Vlan": function() {
var bValid = true;
allFields.removeClass( "ui-state-error" );
bValid = bValid && checkLength( vlan, "vlan", 1, 1 );
bValid = bValid && checkRegexp( vlan, /^([0-9])+$/i, "vlan must be numeric." );
if ( bValid ) {
//this is where I need to redirect to another URL passing the vlan number.
$( this ).dialog( "close" );
}
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
$( "#changevlan" )
.button()
.click(function() {
alert('in here');
$( "#dialog-form" ).dialog( "open" );
});
});
</script>
As you can see I inserted an alert statement to ensure that i was getting into the javascript. But I don't get the alert message. And the contents of the div form just show up on the main page when it's initially rendered.
What I've checked so far:
I've tried to double check that the name of my button that should trigger the div form display matches the name of the variable i'm looking for in the javascript function:
$( "#changevlan" )
.button()
.click(function() {
alert('in here');
$( "#dialog-form" ).dialog( "open" );
});
I've also made sure that my div form is called #dialog-form
But I'm not too sure what else to try. If you ahve any suggestions, I'd appreciate it. I also need to know how to access the contents of the text box and then redirect the user to a new controller and method, passing the vlan number as a parameter.
Maybe I can just do a window.location type of thing...
Thanks.
u dont need more libraries, just make a simple jQueryUI .dialog, inside the "div" element for the dialog place some inline php from CI, something like <div id="dlgPopUpForm"><?= $this->load->view('dialogView.php'); ?></div>, then build your form in the dialogView.php of course.
At run time, the php wil be read into the div and the jquery options u use to create the dialog will handle the rest. something like $("#dlgPopUpForm").dialog({ autoOpen: false, modal: true }); $("#someButton").click(function(e){ $("#dlgPopUpForm").dialog("open"); });
dont forget to include your javascript for the form on the form view page (dialogView.php in my example)
maybe when i'm not so lazy, i'll make ya an example later today, though, its pretty straight forward
I want to make a search box, where you can search between records in the database.
search.php looks like this:
<?php
// connect to mysql
require_once('includes/connect.php');
// include config
include('includes/config.php');
$nameser = $_GET['term'];
$names = array();
$result = mysql_query("SELECT name,customerid FROM customers WHERE name LIKE '%".$nameser."%' ORDER BY name ASC");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['customerid'];
$row_array['value'] = htmlentities($row['name']);
array_push($names,$row_array);
}
echo json_encode($names);
?>
Javascript part looks like this:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};
However, this gives the error:
ReferenceError: item is not defined
What I want to happen is, that when I click something in the result list, I get redirected to the url
customers.php?action=view&cid={CustomerID}
Anyone got an idea?
EDIT:
Correct Javascript code that works:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + ui.item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};
i have a demo with a working example in jsfiddle. you can see it here:
the key is to get a valid url value in the autoselect select method. be sure to console.log the ui value so you can see what is available for you to use. i was able to use the standard ui.item.value value to send the user to another page.
to test my demo:
1.) go into the input box and enter "a".
2.) select "http://www.utexas.edu"
3.) the new page will load.
I want to create jquery autocomplete and php, the problem is the data shown in each record of the autocomplete has two values, I managed to do this like this (without PHP),
$(function() {
var authors = [
{
label: "jQuery",
desc: "the write less, do more, JavaScript library"
},
{
label: "jQuery UI",
desc: "the official user interface library for jQuery"
},
{
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine"
}
];
$( "#authorname" ).autocomplete({
minLength: 0,
source: authors,
focus: function( event, ui ) {
$( "#authorname" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#authorname" ).val( ui.item.label );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
now I want to change the source to php page (change authors to "getauthors.php")
I don't know what to put inside "getauthors.php" in order to pass two things for label and desc.
I managed to pass one thing like this using json,
<?php
$json = array();
$json[]="test";
$json[]="test2";
$json[]="test3";
echo json_encode($json);
?>
which outputs like this,
you can see that the second thing is always undefined, how I can pass value to this in php using json (or any other way).
Thanks.
<?php
$json = array();
$json[] = array ("label"=>"test", "desc"=>"description");
...
echo json_encode($json);
?>