views:

381

answers:

1
+1  Q: 

Jquery Traversing

Hi ,

I am using JQuery for showing a modal dialog box. The dialog box has a file upload control and upload button. Also it contains two buttons for save and cancel.

I need to make the file upload control a mandatory one. I can able to traverse the file control and get the path using $(this).parent().siblings().children().get(1).value; and display the error message on click of upload button. But I want to show the same error displayed for save button also.

Need help to traverse from save button as I created the button along with dialog box like

$("#dialog").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 500,
    width: 600,
    modal: true,      
    buttons: {
        Cancel: function() {        
        $(this).dialog('close');     
        },
        'Save': function() {}
    }
});
+1  A: 

From your code example it looks like this inside the cancel and save handlers is the #dialog element, so you can traverse to all it's children from there. It would be far more robust to use a selector instead of traversal however. Something like $(this).find(':file').val() should work.

Using selectors would make your code more robust as it'll continue to work even if you add additional elements to your dialog. As some commenters have pointed out, giving the file upload control a unique ID would make it easier to select it with a simple selector. If you need the code to work for multiple dialog boxes with different ids for the upload field you can use a class or other specific selectors, like the :file selector mentioned above, combined with the .find method on a specific context.

To help you further we may need a bit more context, like what are the contents of the #dialog element. Perhaps mentioning the jQuery plugin that defines the .dialog method would be helpful.

Martijn Pieters