0

I'm looking for a techniuqe similar to a switch function in PHP so I can use a single function for multiple named selectors. Additional code would be added based on which selector calls the function.

My example is a 'Save' button along a 'Save And Close' button where the latter has additional code to close an accordion.

If the 'Save' button is clicked it calls this:

    $('form[name=experienceForm]').submit(function(eve) {

            eve.preventDefault();
            tinyMCE.triggerSave();

            var FormData = $(this).serialize();
            var requestThis = $(this);
            var inputCom = $(this).find('input[name=inputCom]').val();
            var inputTitle = $(this).find('input[name=inputTitle]').val();

                $.ajax({
                        type : 'POST',
                        url : '<?php echo site_url('resume/update'); ?>',
                        data: FormData,
                        dataType: "html",
                        context : $(this),
                        success : function(msg){
                        requestThis.closest('.item').children('h3').children('a').text(inputCom+' : '+inputTitle);

                        if(msg != '') {

                        showNotice(msg);
                        }

                        },

                        error: function(msg){
                        alert('FAIL '+msg);
                        }
                    }); 


    });

I would like the 'Save and Close' button to do the same as above with this added:

    $('input[name=experienceClose]').click(function(eve) {

        eve.preventDefault();
        tinyMCE.triggerSave();          
        $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().accordion({active:"false"});
    }); 
3
  • 2
    You can use closest instead of a million parent() calls. Commented May 8, 2012 at 23:28
  • @PaoloBergantino -- Thanks! I was going to ask that too. I used closest elsewhere and it's so much cleaner. Commented May 8, 2012 at 23:31
  • Yeah the chance of that working for more than a few days is pretty small ;) Commented May 8, 2012 at 23:54

2 Answers 2

1

Not sure I get the question, but would a switch function do it, they do have them in Javascript aswell ?

$('input[name=experienceClose], form[name=experienceForm]').on('click submit', function(e) {
    e.preventDefault();
    tinyMCE.triggerSave();  

    switch ($(this).attr('name')) {   //based on the buttons name
        case 'experienceClose' : //would be the name of the save and close button
            //do something for save and close button
        break;
        case 'experienceForm' :  //would be the name of the save only button
            //do something for save button only
        break;
        default:
            //do something on neither of the above
    }
});

On the other hand, if it's only two buttons, an if/else statement is probably more appropriate.

Sign up to request clarification or add additional context in comments.

1 Comment

Makes perfect sense, but I'm having trouble implementing because my selectors use name= not id because there are multiple instances on one page.
0

Assuming the buttons will match a pattern like name="experience*" you could do something like this:

// just save the form
function save(e)  { 
    // all the stuff to do in either case
}

// just close it
function close() {
    // death by a thousand parents
}

// use "on" instead of older jQuery constructs
$('form').on('click', '[name^="experience"]', function(e) {
    switch(this.name) {
        case 'experienceSave':
            save.call(this,e);
            break;
        case 'experienceForm':
            save.call(this,e);
            close();
            break;
        default: 
           throw 'Why am i here?';
     }
});

What's going on:

1) The selector gets anything with attribute name that starts with ^= "experience".

2) this in an event handler is the element that got clicked.

3) switch is the same in Javascript as any C-like language.

4) It's good to throw errors in things like this. If you didn't have a default case and added some more markup that happened to match the selector, it would just fail silently if there were no default. Throw errors when things that shouldn't happen happen, makes debugging easier. If you worry about real users seeing an error, then when you get to production add a global window.onerror handler that sends you an email or something before failing silently :)

7 Comments

Thanks! Wondering if a ':' is needed after case 'experienceForm'?
Did you also notice that you are using a delegated event, have quoted the document, and that you only match the form element, not the input ?
@adeneo I use delegated events a lot with forms because forms frequently change themselves. Binding to document didn't make sense though. Especially to the string 'document'. Been a long day.
It will actually work with the string 'document', but it's generally a bad idea, done that one myself a couple of times !
Is that a special case with on to save idiots like me? I mean, does on just bind to document if called on an empty selector? $('document') doesn't select anything.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.