Improving my jQuery
Thu, 24 July, 2008 – 9:59 pm
Usually you blog about something, putting your opinion over about something. Well today it's my turn to ask the questions! I have a number of jQuery questions and figured I'd leave them up here for either me to then find the answer or for someone who may know the answer to give me a few hints
This isn't a 'how do I do this'. What I have already works, but I'm sure it could work a lot more efficiently and a couple of questions linger in my mind as to how or even whether it's possible.
Update: I've got the first issue working thanks to Marc Grabanski (who has an excellent site and is a must read for any jQuery user!)
1. I need to create a function that resets several select lists. However the id of each select list is dynamically generated. What I have is a select list with a list of parents in and each has an ID. Then each parent has a child select list, and the child select list uses the parent ID to make it unique (with me so far?!). At present I use PHP to generate the function by looping through the parent IDs (retrieved from a database), which gives me:
- JavaScript function
-
- function resetLists() {
- $('#child1')[0].selectedIndex = 0;
- $('#child2')[0].selectedIndex = 0;
- $('#child3')[0].selectedIndex = 0;
- }
However, I'm sure there must be a way that I can just use jQuery to read through all of the option values of the parent list and get the 1, 2 and 3 from that and do the same above i.e have a function that pretty much says 'get each value from the parent list and for each value set the selectedIndex to 0 for the child + value list. I'm sure it's possible, but how, I don't know (yet).
2. This is one I've not actually got working yet. I'm working on an admin area and I've got the parents listed in a table. Then at the end is the option to remove the parent. However as each parent has one or more children, the children need to be moved to another parent. So when you click 'Remove' it gives a select list of the available parents to move the children to. You can select the new parent and then click Go. However at this point I don't want the form to actually submit and reload the page (which it's currently doing), I want the form to trigger a function which runs the PHP file to move the children, delete the parent and just remove the table row of the parent off the screen.
So far I've got it to run the function, however once the function runs the page refreshes. The only way I've got this function to run is by using the onsubmit attribute in the form tag. Now I know I could change the submit button to a standard button, but surely there's a way to prevent the form form submitting? I've tried putting return false; at the end of the function that's run, but that doesn't seem to work. I've tried putting the function in the action with javascript: at the start of it, but that really didn't work!
Update: Some code may help. This is what I have at present.
- Remove Function
-
- function exremtrade(id) {
- var newtrade = $('#trade_' + id).val();
- $.get("/admin/includes/remTrade.inc.php", {id: id, nt: newtrade}, function(data) {
- if (data) {
- $('#message').text('Trade details removed.').fadeIn();
- $('#row' + id).fadeOut();
- } else {
- $('#message').text('Error removing Trade details.').fadeIn();
- }
- });
- return false;
- }
I've then got a form that has the attribute onsubmit which runs
onsubmit="exremtrade(2)"
Where '2' is the ID of the trade to remove. The new trade ID is in the select list, also in the form. Now if I remove the form and just use a button and the select list, it works. But of course that isn't valid, and ideally the form should be there just in case the user doesn't have JavaScript (plus I'd like to understand why it's not working!). However, with the form in place, and the button as either a button or submit input, the function runs, works as it should, but then the form gets submitted which effectively refreshes the page and loses my update message.
That's my two questions so far. I'm currently reading jQuery in Action thanks to Si's recommendation, which is a great book, I'm just a slow reader! 2 months ago I didn't have a first clue about AJAX, and now I'm quite confident with the basics. My first AJAX enabled site has been live for almost a week and it's not collapsed! I'd just love to be able to improve it further ![]()


14 Responses to “Improving my jQuery”
Are they the only selects on the page other than the parent select? If so, why not do this:
$("select").not("[id=parentlist]").selectedIndex = 0;
(I've spelt out the id=parentlist to make it obvious what I'm doing).
As for calling a PHP script behind the scenes, try this for size:
$.post("myscript.php", { var1: "value of variable 1", var2: "value of variable 2", var3: myVar});
where myVar is a variable you've got something sitting in. You can then remove the elements you want to by using:
$("whatever to select the right elements").remove();
Sam
By Sam on Jul 24, 2008
Hey Sam. Thanks for the reply. The first issue, no they're not the only selects, however you've given me food for thought as they all contain a common part of their name so I could use the * or ^ to match the name. So I'll give that a go.
For the second issue, I've got the PHP running fine. All I need to do is stop the form from actually submitting (but submits if javascript isn't enabled, although that's not a major issue).
However the remove() does actually answer another question that I was pondering over earlier today! So cheers for that too!
By Sarah on Jul 24, 2008
Sarah, for #1 this should do the trick…
$(document).ready(function(){$('#reset').click(function(){
$('#parent option').each(function(i,option){
child_id = $(option).val();
$('#'+child_id)[0].selectedIndex = 0;
});
});
});
First I created a button with id=reset. On click it grabs the parent select list options.. loops through them. Uses the value of the option (id) to select the child select list. Then sets each select list to the first option.
#2 - From what I gather, all you need to do is send the PHP script three things: the parent you are moving to, the parent you are deleting, and the children that are moving. Use the format Sam provided to submit this data.
To stop a form from submitting simply do the ajax post and then "return false".
The main issue left is the selectors you are using. I can't get into that unless I see a deeper explanation of the task at hand.
If you need any more help, please describe the areas where you are getting snagged.
By Marc Grabanski on Jul 25, 2008
Marc, thanks for your comment. I couldn't get your first code working which was along the lines of what I figured I'd need. It just keeps coming up saying the 5th line child_id is undefined.
However, thanks to Sam's first comment I've got the first bit working with a one liner
$("select[id^=child]")[0].selectedIndex = 0;Although I really want to understand the each() function.
In regards to the second issue. I've currently got
function exremtrade(id) {var newtrade = $('#trade_' + id).val();
$.get("/admin/includes/remTrade.inc.php", {id: id, nt: newtrade}, function(data) {
if (data) {
$('#message').text('Trade details removed.').fadeIn();
$('#row' + id).fadeOut();
} else {
$('#message').text('Error removing Trade details.').fadeIn();
}
});
return false;
}
So the Trades are the parents, each trade has several jobs tied to it. That's not the issue however. That all works fine. It's just the line line, where I already have return false; but it seems to be ignoring it. So when I click the submit button it runs the function and then submits the form which, at present just refreshes the page. My message and stuff is never seen.
As I mentioned, I can get round this by using a standard button as opposed to a submit button, so it's more a question of why not how.
By Sarah on Jul 25, 2008
Change that, the one liner fix for point 1 only does the first select list not all 6
Back to trying to get the each function to work.
By Sarah on Jul 25, 2008
take out the [0] which is limiting your results to the first one
hth
Sam
By Sam on Jul 25, 2008
Sam, I tried it without too. It didn't do anything at that point.
By Sarah on Jul 25, 2008
Have you tried:
$("select[id*=child]").selectedIndex = 0;
?
By Sam on Jul 25, 2008
The first code works, I tested it.. which is a solution based on exactly how you described what you wanted to do it. Here is the full paste: Reset Select Lists based on Select with Ids
If you want to get the prefix selector working then make a button with id="reset" then run this code:
$("#reset").click(function(){$('select[id^=child]').each(function(i,select){
$(select)[0].selectedIndex = 0;
});
});
On #2, if return false isn't working then an error occurred in your code. Watch firebug carefully as you submit the form.
By Marc Grabanski on Jul 25, 2008
Marc my apologies. I've just worked out what the problem was after comparing your code to mine. The first option in my parent list has
<option value="">Select a Parent</option>and that's what was coming up as undefined and subsequently killing the function.
Your code does indeed work perfectly. I can't believe I've just lost the entire morning to an empty value!
Thank you so much for the code. I'd have never worked it out otherwise!
By Sarah on Jul 25, 2008
Update - looks like onsubmit and return false don't play well together as it works fine if I use the click() function. Now I just have to work out how to do it all dynamically!
By Sarah on Jul 25, 2008
Finally got the form to work using submit() and a bit of trickery. I'll write up about it in the morning. I have an admin section to finish first!
Cheers to Sam and Marc for their input
By Sarah on Jul 25, 2008
Hi Sarah,
I have to admit I have finished the book either due to opensource project commitments, real life and normal work. Am glad you're enjoying the book though.
By Si Philp on Jul 25, 2008
Si I know the feeling. I have so many personal projects half finished, books half read, magazines not even looked at. Client work seems to be taking over my life right now, and when it isn't all I want to do is escape the house (where I reside 24 hours a day most of the time!).
But yes, the book, so far, has been great
By Sarah on Jul 25, 2008