Jquery Live Search Only Inputs First Result In List - php

Am using the following code to perform a livesearch via a SQL query. The Jquery code is shown below:
$(document).ready(function() {
$('#holdername').on('keydown', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('holdersearch.php', { keywords: searchKeyword }, function(data) {
$('ul#liveSearchList').empty()
$.each(data, function() {
$('ul#liveSearchList').append('<span class="searchResultItem">' + this.holder + '</span></br>');
});
}, "json").fail($('ul#liveSearchList').empty());
} else {
$('ul#liveSearchList').empty()
};
});
$('#liveSearchList').on('click', function() {
var holderName = $(this).find("a").html();
console.log("Holder: ",holderName);
$('#holdername').val(holderName);
$('ul#liveSearchList').empty()
});
});
This creates the list as it should however when any item in the list is selected (clicked) it will only ever populate the input box with the first item in the list. Am not sure why it is doing this, if I hover down the list the link shows the different values for hldr as it should so it appears it is working as it should. The console.log confirms the item selected is only ever the first on the list

You added click event on whole ul, so $(this).find("a").html(); select all <a> elements and return value of first
You should add click event to all <li> or <a> elements. Try this:
$('#liveSearchList').on('click', 'li', function() {
var holderName = $(this).find("a").html();
console.log("Holder: ",holderName);
$('#holdername').val(holderName);
$('ul#liveSearchList').empty()
});

Related

jQuery fast mouse move mouseleave event triggers before previous event completes

If a users mouse goes over a table cell then a dropdown box replaces the html with data loaded via a post call. This works fine if the users mouse move is not too quick, but if it is too fast the html doesn't update so that when the user moves the mouse back in the html is incorrect.
$(".edit_dropdown").bind('mouseenter', function () {
$(this).unbind('mouseenter');
var a = $.trim($(this).html());
var id = $(this).attr('id');
$(this).html("<span id='s-" + id + "'></span>");
$.post('save/dropdown.php', {
id: id,
a: a
}, function (data) {
$("#s-" + id).html(data);
$(".edit_dropdown").bind('mouseleave', function () {
var id = $(this).attr('id');
var a = $("#e-" + id).val();
var dir = $(this).attr('class');
$(this).html(a);
$(this).bind('mouseenter', function () {
$(this).unbind('mouseenter');
var a = $.trim($(this).html());
var id = $(this).attr('id');
$(this).html("<span id='s-" + id + "'></span>");
$.post('save/dropdown.php', {
id: id,
a: a
}, function (data) {
$("#s-" + id).html(data);
});
});
});
});
});
html
<tr>
<td>customer county</td>
<td class="edit_dropdown" id="customer-cust_s_county"><?php echo $row['cust_s_county']; ?></td>
</tr>
The $.post file returns a list of UK counties, if the county name matches the html then that county is returned as the selected option.
The problem occurs because the mouseleave handler is only put in place in response to an asynchronous response to the mouseenter handler.
You should be looking for a simpler overall code structure that doesn't involve detaching and reattaching handlers.
It should be possible to write two handlers that remain permanently attached, as follows :
$(".edit_dropdown").on('mouseenter', function () {
//Perform all mouseenter actions here.
//If necessary, test for different states and branch as required.
}).on('mouseleave', function () {
//Perform all mouseleave actions here.
//If necessary, test for different states and branch as required.
});
Another point: As the list of counties is static, you can serve it once as part of the page's original HTML. You then need to return only the name or id of the county to be selected rather than repeatedly returning the whole list.

Why won't this jquery get command save dynamic ui sortable list?

I am trying to save the order of my jquery ui sortable list to the server. I am loading my list from an external file when the user clicks a tab, then adding a checkbox to each list item. The code was working fine until I put in the line to add the checkbox - now it won't save the order on the server. I can't figure out why prepend checkbox line is breaking it. Any help would be greatly appreciated.
Jquery to load list and add checkbox:
window.onload = function() {
var a = document.getElementById("fvsortid"); // loads slides when user clicks tab and adds checkbox
a.onclick = function() {
$("#sortable").load("file.xml");
$("#sortable").load("file.xml", function(){
$('<input type="checkbox"/>').prependTo('#sortable li');
});
}
}
Jquery to update order:
$(document).ready(function(){
$('#sortable').sortable({
update: function(event, ui) {
var newOrder = $('#sortable').html();
$.get('reorder.php', {order:newOrder});
alert("New order saved to server");
}
});
});
Reorder.php:
<?php
$items = $_GET['order'];
$items = "<body>\n$items\n</body>";
file_put_contents('file.xml', $items);
?>
if you prepend an input element to a li element, the input will end up as a child element of ul, which is invalid. Perhaps you can prepend to another element, or wrap the input in a li element?

Remove drop down entries based on previous selection

I've looked through stackoverflow for an answer and am almost there but need some help.
I have multiple drop down lists with the same options in them. For example three identical lists with the following:
<label for='distlist_1'>Distribution List 1</label>
<select name='distlist_1'>
<option value=''>Please Select:</option>
<option value='1'>All</option>
<option value='2'>All Managers</option>
<option value='3'>Leavers</option>
</select>
The only difference being the name eg, distlist_1, 2, 3 etc. I can add ids if necessary.
When a user selects an option in the first drop down list I need it to be removed from all other drops downs. I found a script that did this.
$('option').click(function(){
$('option:contains(' + $(this).html() +')').not(this).remove();
});
But I need it so that if the user then decides, 'wait I don't need that option in drop down list 1 after all', she picks something else and the option reappears in the other drop downs. The code above removes the options then there is no way of retrieving them until if you click enough they all disappear.
This actually does what you want... This is based on jquery 1.7 and the on() event binder
$(document).ready(function (){
$('select').on('focus', function() {
// on focus save the current selected element so you
// can place it back with all the other dropdowns
var current_value = $(this).val();
// bind the change event, with removes and adds elements
// to the dropdown lists
$(this).one('change.tmp', { v : current_value }, function(e)
{
if ($(this).val() != '')
{ // do not remove the Please select options
$('option[value="' + $(this).val() + '"]')
.not($('option[value="' + $(this).val() + '"]', $(this)))
.remove();
}
if (e.data.v != '')
{ // do not add the Please select options
$('select').not($(this)).append($('option[value="' + e.data.v + '"]', $(this)).clone());
}
});
// on blur remove all the eventhandlers again, this is needed
// else you don't know what the previously selected item was.
$(this).on('blur.tmp', { v : current_value}, function (e)
{
$(this).off('blur.tmp');
$(this).off('change.tmp');
});
});
});
The only thing it doesn't do is ordering everything in the right order. You will have to think of your own way of doing that at the .append function.
I ended up using this as it was concise...
jQuery(document).ready(function() {
var selects = $('.mapping')
selects.change(function() {
var vals = {};
selects.each(function() {
vals[this.value] = true;
}).get();
selects.not(this).children().not(':selected').not(':first-child').each(function() {
this.disabled = vals[this.value];
});
});
});

Select changes not triggering if added by JQuery

I have a multi level select chain, where by the value of the first select generates the options for the next select list. And within the second list some of the values will cause a div to display with another input.
My codes (below) seem to work just fine when tested on static content (ie: the second select is hard coded in the html). But when I add it with JQuery, the second level no longer triggers the .change function.
<script type="text/javascript">
$(document).ready(function() {
$dts = $("select[name='tourdes']");
$dts.change(function() {
var dtsValue = $(this).val();
var dtsString = '?tourdes=' + dtsValue;
$('#dateSelect').show();
$('#dateSelect').load('include/avdates.php' + dtsString).append();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$tags = $("select[name='tourcode']");
$tags.change(function() {
if ($(this).val() == "private") {
$(".prvcal").css({"visibility":"visible"});
}
});
});
</script>
I am guessing something needs to be re-initialized, but I am getting no where with my experiments.
If you're using jQuery 1.7 you'll want to use on, as both live and delegate are deprecated.
$(document).on("change", "select[name='tourcode']", function() {
var dtsValue = $(this).val();
var dtsString = '?tourdes=' + dtsValue;
$('#dateSelect').show();
$('#dateSelect').load('include/avdates.php' + dtsString).append();
});
docs for on()
You are probably using dynamically-generated HTML elements. If that is the case, you need to use .delegate() to handle them:
$('select').delegate("[name='tourdes']", 'change', function() {

Jquery, add value to array in each loop

I have a jQuery app where the user can add items to a list from an input field.
I want to put all items in an array when you submit the form so I can manipulate them with php later. Is this the right way to do it?
jQuery:
$("#form").submit(function(){
var items = [];
$("#items li").each(function(n){
items[n] = $(this).html();
});
$.post(
"process.php",
{items: items},
function(data){
$("#result").html(data);
});
});
PHP:
$items = $_POST["items"];
foreach($items as $item){
//Something here
}
The idea is sound. What it not very clear is that your example populates items now, but the submit handler will of course be called at some point in the future. Is it possible that the list items may have changed by that time?
If so, you need to move the "pack the items" code inside the submit handler, e.g.:
$("#form").submit(function(){
var items = [];
$("#items li").each(function(n){
items[n] = $(this).html();
});
$.post(
"process.php",
{items: items},
function(data){
$("#result").html(data);
});
});

Categories