0

I have a Save/Edit button. I would like it to do different things depending on whether it's currently a Save button or an Edit button. For clarity, I want to save the jQuery selector and function to a variable name, then call it:

    $('div#' + id + ' .edit').click(function(){

        var i = this;
        var state = function(st){
            if( typeof st !== 'undefined')
                $(i).html(st);
            else
                return $(i).html();
        };

        if( state() == 'Edit' ) {
            controller.edit(id);
            state('Save');
        } else {
            controller.save();
            state('Edit');
        }

    });

My question: is there a faster way to do this? Something like the following:

    $('div#' + id + ' .edit').click(function(){

        var state = $(this).html;

        if( state() == 'Edit' ) {
            controller.edit(id);
            state('Save');
        } else {
            controller.save();
            state('Edit');
        }

    });

...but this does not work.

This example is just an example; I know there are many ways to do what it's trying to do without saving the selector and the function to a variable. Nonetheless, the question still stands: is it possible to do this faster?

2 Answers 2

3

Why not just

$('#' + id + ' .edit').on('click', function(){
    $(this).text(function(_, txt) {
        if (txt == 'Edit') {
            controller.edit(id);
            return 'Save';
        } else if (txt == 'Save') {
            controller.save();
            return 'Edit';
        }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Your particular example doesn't change the text of the button after it's been clicked. And as I'd mentioned, I know there are different ways of doing it without saving the selector and function. I want to know whether saving selector and function is at all possible.
@sg.cc - It's not really clear what you're trying to do, as the code you've posted doesn't really make any sense, but I edited the answer to change the button text as well ?
$(this).text(_, txt) { doesn't make sense. I assume you meant to write $(this).text(function (_, txt) {
0

jQuery elements are objects so why not store directly into your Object element the desired state:

DEMO

$('div#' + id + ' .edit').click(function(){
  var es = this.es ^= 1;           // Toggle/Store state
  $(this).text(es?'Save':'Edit');
  return controller[es?'edit':'save'](id);
});

Comments

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.