toggle edit buttons with save and cancel buttons

2019-05-04 07:17发布

I want to change the button when it's clicked. Initial there's only one "Edit" button. After I click it, it will become a "Save" button and I also want to show a "Cancel" button next to it. How can I do that? I have the code below.

    <!DOCTYPE html>
    <html>
    <head>
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <meta charset=utf-8 />
    <title>demo by roXon</title>
    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    </head>

    <body>
    <button data-text="Save">Edit</button>
    <p>Hello</p>
    <p style="display: none">Good Bye</p>

<script>
$("button").click(function(){
    $(this).nextUntil('button').toggle();


    var btnText = $(this).text();
    $(this).text( $(this).data('text') );
    $(this).data('text', btnText );
});
</script>

</body>
</html>

2条回答
唯我独甜
2楼-- · 2019-05-04 07:51

I suggest a layout and jQuery like this jsFiddle example.

jQuery

$('.edit').click(function() {
    $(this).hide();
    $(this).siblings('.save, .cancel').show();
});
$('.cancel').click(function() {
    $(this).siblings('.edit').show();
    $(this).siblings('.save').hide();
    $(this).hide();
});
$('.save').click(function() {
    $(this).siblings('.edit').show();
    $(this).siblings('.cancel').hide();
    $(this).hide();
});

HTML

<form>
    <div>
    <input class="edit" type="button" value="Edit" />
    <input class="save" type="button" value="Save" /> 
    <input class="cancel" type="button" value="Cancel" />
    </div>
    <div>
    <input class="edit" type="button" value="Edit" />
    <input class="save" type="button" value="Save" /> 
    <input class="cancel" type="button" value="Cancel" />
    </div>
    <div>
    <input class="edit" type="button" value="Edit" />
    <input class="save" type="button" value="Save" /> 
    <input class="cancel" type="button" value="Cancel" />
    </div>
</form>

CSS

.save, .cancel {
display:none;
}​
查看更多
你好瞎i
3楼-- · 2019-05-04 07:51

you can add a new button for the cancel and just hide it as you need. you can follow the demo here

here is the code in case you need it:

<button id='EditSave' data-text="Save">Edit</button>
<button id='Cancel' data-text="Cancel" style="display:none;">Cancel</button>
    <p>Hello</p>
    <p style="display: none">Good Bye</p>​

$("#EditSave").click(function(){
    var btnText = $(this).text();
    if(btnText == 'Edit')
    {
        $(this).text('Save');
        $('#Cancel').show();
    }
    else
    {
        $(this).text('Edit');
        $('#Cancel').hide();
    }
});

$('#Cancel').click(function(){
    $(this).hide();
    $('#EditSave').text('Edit');
});
​
查看更多
登录 后发表回答