I have parent directories in <select id="cat1">
I'm trying to get it to populate <select id="cat2"> with children directories
My JQuery looks as follows:
$(function(){
$("#cat1").change(function () {
var thisID = this.value;
$.getJSON("find-child-dirs.php?parent=" + thisID, function(data) {
$("#cat2 option").remove();
$.each(data, function(i, val){
$("#cat2").append('<option value="' + val.id + '">' + val.name + ' </option>');
});
});
});
});
Upon sending the parent ID to my php it returns:
([{"name":"Child Name","id":"8"}])
But nothing is populating the #cat2 select. I've been trying many variations but believe this is closest to clean and simple as I can get. Any suggestions?
I copied and ran most of what you have there and it all works just fine - any chance you're missing the end select tags? ('</select>') (You 'change' a dropdown value of select #cat1 and it does add the options to select #cat2.) I can't test the php request but everything else there works fine. I'm guessing that maybe you're missing '</select>' in two places?
Related
For certain reasons (towards a larger picture), I have a select element that is populated by a php page. The data is populated properly within the element. However, when I make a selection the element always forces the first item in the list. If I "append" the returned data, I can select different items but if clicked again it will just keep appending on top of the existing items. If I "empty" before the "append" it shows the correct list but still forces the first item in the list and this happens whether I use onclick or onchange. Whatever code works will also need to be applied the same to this element being dynamically created on the same page later. As I understand it the $(document).on('click'... as opposed to $(document).click(... works better for dynamic elements. Any help is appreciated. Thanks, I am still new to this exchange and I hope I described my problem correctly. I have searched for hours about this problem, but I mostly get results about multiple select elements or populating a second select, and even potential answers I have tried do not work.
My data is pulled from _get_staffnames.php, and lets say it shows Frank, George, Todd.
$stmt = $myPDO->prepare( "SELECT userID, CONCAT(firstname,' ', lastname) AS Fullname FROM tbl_user ORDER BY Fullname ASC" );
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $row):
echo '<option value="' . $row['userID'] . '">' . $row['Fullname'] . '</option>';
endforeach
My HTML is:
<select name="userID1" id="userID1" class="namesClass" required>
<option selected value="">Select Staff</option>
</select>
One JQuery way I tried, specifically for the one element id "userID1", populates Frank, George, Todd...but when I pull down and click Todd, it still shows Frank (first in list) after the click.
$("#userID1").click(function() {
$("#userID1").load("_get_staffnames.php");
});
More towards the dynamic way I am going. This code allows me to choose Frank, George, or Todd and keeps the selection, but if I click on that given dynamic element again, the list keeps repeating the group +1 every time I click on it.
$(document).on('click', '.namesClass', function(e) {
var select_id = $(this).attr("name");
$.ajax({
type: "POST",
url: '_get_staffnames.php',
})
.done(function (returndata) {
$('#' + select_id).append(returndata);
})
});
When I try the .empty parameter before append as below, I get the correctly populated list (without multiple appended groups) but when I choose any item it always defaults to the first item in the list (Frank) again.
$(document).on('click', '.namesClass', function(e) {
var select_id = $(this).attr("name");
$.ajax({
type: "POST",
url: '_get_staffnames.php',
})
.done(function (returndata) {
$('#' + select_id).empty().append(returndata);
})
});
Is clicking on the Select element the only way you can load data from a remote source?
It's totally unconventional and by doing so, you are triggering the onclick event and performing the ajax method every time you click on any item of it which will eventually recreate its child elements on every callback and thus the first item being selected as default.
As kolunar pointed out, even when I clicked on my selection I was running ajax again. So, I just check if there is anything in the element before running ajax and it works. Feels silly now, but thanks for the time and input.
$(document).on('click', '.namesClass', function(e) {
var select_id = $(this).attr("name");
if ( $('#' + select_id).val() == '' ) {
$.ajax({
type: "POST",
url: '_get_staffnames.php',
})
.done(function (returndata) {
$('#' + select_id).empty().append(returndata);
})
}
});
I am building a facility on a website (using Symfony2) that allows the user to create reports and display them on a screen using AJAX. The reports are effectively SQL statements that are created on the fly and are then ran on the Database.
The problem I have is that I can't fathom a way to display these results to the screen without first knowing what fields are used in the report. The queries could contain just 2 fields from a table, or 15 fields, and I'd like the code to be robust enough to handle this.
So far, this is the code I'm using:
$.ajax({
type: 'POST',
url: urlLink,
success: function (data) {
var Type = (data.recordType);
var Results = (data.results);
var Name = (data.name);
var Description = (data.description);
var Titles = (data.titles);
$('#reportName').text(Name);
$('#reportDescription').text(Description);
$('#listTable > tbody:last').empty();
$('#listTable > thead:last').empty();
$('#listTable > thead:last').append('<tr>'+Titles+'</tr>');
$.each(Results, function(i, item) {
$('#listTable > tbody:last').append('<tr><td>' + Results[i] + '</td><td>' + Results[i] + '</td><td>' + Results[i] + '</td><td>' + Results[i] + '</td><td>' + Results[i] + '</td><td>' + Results[i] + '</td></tr>');
});
}
});
The variable Titles comes from the query, as when the user is adding fields to the database these are then added to a string which I then explode using PHP in the controller.
Inside the foreach, every column comes back with [object Object]. When I remove the [i] from the code and replace it with .column-name it will then work. But this is what I'm trying to avoid. I'd like to have something similar to what I do with the Table Titles.
Maybe try this, and show output of console.log(data);
console.log(data);
var data = $.parseJSON(data);
$.each(data, function() {
$.each(this, function(k, v) {
/// do stuff
});
});
I am using the following ajax / jquery / php to pull data into select boxes. After this, I use the code below it to reset the select dropdown menus if the user makes any changed to previous select boxes. The odd thing that is happening is if the user changes the #customer dropdown it resets all of the qty boxes and all of the linetotal calculations as well as the stock dropdowns, but copy and paste the same function onto the #vehicle dropdown for some odd reason it clears the qty text box, clears the linetotal calculation, but leaves the stock dropdown select menu's how they are instead of resetting them to default, this is with the exact same code that WORKS on the #customer dropdown to reset everything on change.
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#customer').on('change', function () {
$('#vehicle').html("<option value=''>Select</option>"); // add this on each call then add the options when data receives from the request
$.getJSON('select.php', {
customerId: $(this).val()
}, function (data) {
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['reg'] + ' - ' + data[x]['make'] + ' - ' + data[x]['model'] + '</option>';
}
$('#vehicle').html(options);
$("select").select2();
});
});
$('#customer').on('change', function () {
$('#qty1').val('');
$('#linetotal1').text('');
$("#stock1").val($("#stock1 option:first").val());
$('#qty2').val('');
$('#linetotal2').text('');
$("#stock2").val($("#stock2 option:first").val());
$('#qty3').val('');
$('#linetotal3').text('');
$("#stock3").val($("#stock3 option:first").val());
$('#qty4').val('');
$('#linetotal4').text('');
$("#stock4").val($("#stock4 option:first").val());
$('#qty5').val('');
$('#linetotal5').text('');
$("#stock5").val($("#stock5 option:first").val());
$('#qty6').val('');
$('#linetotal6').text('');
$("#stock6").val($("#stock6 option:first").val());
});
$('#vehicle').on('change', function () {
$('#qty1').val('');
$('#linetotal1').text('');
$("#stock1").val($("#stock1 option:first").val());
$('#qty2').val('');
$('#linetotal2').text('');
$("#stock2").val($("#stock2 option:first").val());
$('#qty3').val('');
$('#linetotal3').text('');
$("#stock3").val($("#stock3 option:first").val());
$('#qty4').val('');
$('#linetotal4').text('');
$("#stock4").val($("#stock4 option:first").val());
$('#qty5').val('');
$('#linetotal5').text('');
$("#stock5").val($("#stock5 option:first").val());
$('#qty6').val('');
$('#linetotal6').text('');
$("#stock6").val($("#stock6 option:first").val());
});
});
</script>
so if I change the #vehicle select it clears the qty and line total but leaves the stock how it was, if I change the top select for #customer it clears the select just fine, using the same function......
ALL OF THE SELECTS ARE USING THE JQUERY PLUGIN CALLED SELECT2 BY THE WAY.
I am assuming #vechicle is a select tag.
$('#vehicle').html(options);
on this line you're turning it into option tag , double check the HTML using firebug.
You may do something like this, if you want to add value on your select tag
$('#vehicle').append(options);
I have a search box. I'm using jQuery and keyup to filter repeating divs.
Each div looks like this:
<div class="searchCell" id="searchCell' . $id . '">';
<div class="friendName">
// someNameOutputWithPHP.
</div>
</div>
Now, I want to filter based on the name text. If someNameOutputWithPHP contains the search query, the entire searchCell should show(). If it doesn't, the entire searchCell should hide().
This doesn't work, though:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
$(".searchCell > .friendName:contains(" + searchValue + ")").show();
});
});
</script>
EDIT
New problem: I got the divs show() to show how I want. But the :contains isn't working exactly right.
For instance: say one of the name's is Ryan. When I search for 'Ryan', I get nothing. But when I search for 'yan' I get the Ryan div.
What's wrong?
Here's the :contains code:
$(".friendName:contains(" + searchValue + ")").parent().show();
That is because you are hiding the .searchCell and then showing its children .friendName divs, which though get display property will not show up because parent is hidden.
Try this:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
//$(".searchCell:has(.friendName:contains(" + searchValue + "))").show();
// OR
//$(".friendName:contains(" + searchValue + ")").parents(".searchCell").show();
// OR
$(".friendName:contains(" + searchValue + ")").parent().show(); // If .searchCell is always a direct parent
});
});
</script>
Your selector
$(".searchCell > .friendName:contains(" + searchValue + ")")
will select all .friendName divs that contain the text from searchValue. That works just fine, but you need to .show() the parent element. Just invoke the .parent() method for that:
$(".searchCell > .friendName:contains(" + searchValue + ")").parent().show();
Demo: http://jsfiddle.net/d3ays/3/
And by the way, you HTML markup looks messed up too. There is a ; behind your div.searchCell for instance.
For some reason the script below is unable to get the id of the draggable divs using attr('id'), but it works on the other static elements on the page. I am totally confused as to why this wont work and if anyone has a solution for me it would me much appreciated.
$(document).ready(function(){
//$(".draggable").draggable();
$(".draggable").draggable({ containment: '#container', scroll: false });
$(".draggable").draggable({ stack: { group: '#container', min: 1 } });
$("*", document.body).click(function (e) {
var offset = $(this).offset();// get the offsets of the selected div
e.stopPropagation();
var theId = $(this).attr('id');// get the id of the selceted div
$("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
$.post("http://localhost/index.php", "id=" + theId + "&x=" + offset.left + "&y=" + offset.top); //post x,y to php (and the id of the elemnt)
});
var req = function () {
$.ajax({
url: "out.php",
cache: false,
success: function(html){
$("#stuff").empty().append(html);
var css_attr = html.split(",");
$('#1').css('left', css_attr[0] + 'px').css('top', css_attr[1] + 'px');
},
complete: function(){
req();
}
});
};
req();
});
Note: This script is dependent on the following JavaScript sources.
jquery.js
http://jqueryui.com/latest/ui/ui.core.js
http://jqueryui.com/latest/ui/ui.draggable.js
http://jqueryui.com/latest/ui/ui.droppable.js
Currently you're attaching the click handler to all elements in the DOM with * (very very bad, don't do this!), including any children in those draggables.
You are correctly stopping the event from bubbling up using .stopPropagation(), but it's likely a child of a .draggable you've clicked, not the draggable itself. What you want is actually listening on the .draggable element themselves, like this:
$(".draggable").click(function (e) {
var offset = $(this).offset(),
theId = this.id;
e.stopPropagation();
$("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
$.post("http://localhost/index.php", { id: theId, x: offset.left, y: offset.top });
});
The other changes here are id can be accessed directly, via this.id, and passing an object to $.post() is safer for serialization, like I have above.
Even the above isn't quite there though, you likely want to send the position when you stop dragging, by changing this:
$(".draggable").click(function (e) {
To this:
$(".draggable").bind("dragstop", function (e) {
...or in newer versions of jQuery (1.4.2+):
$(document.body).delegate(".draggable", "dragstop", function (e) {
Your click function works for me on a test page. Out of curiosity, if you move the 'e.stopPropogation()' line to the bottom of your click function, does it behave differently?
Be careful with *, you know, all means all, if you have <div><p><span><a></a></span></p></div> it means that the action is set to every single element. I'd specify classes or tags that should be affected by your function, to be always sure that you get what you want to be clicked.
Try your code replacing * with the object you think it's ID isn't get, and see if it works..
This may seem pretty obvious but are you sure that all the elements that your selecting actually have IDs. If your including everything (with the *) then it is likely that some elements don't have IDs.