切换,更改html并重置表单

时间:2011-06-24 18:53:45

标签: jquery toggle

我对JQuery比较陌生,但我很确定这是可能的......

<a name="formLink1">Add Item</a>

<form id="theForm" class="hidden">
(form inputs)
<a name="formLink2">Cancel</a>
<input type="submit">

<a name="formLink3">Add an Item</a>

如果点击上面的formLink1formLink3

  • 表格应该显示
  • formLink1应将文本更改为“取消”,并将链接设置为执行“取消”操作

在表单打开时点击formLink2formLink1(并显示“取消”):

  • 将表单字段重置为空白 (他们都是文字)
  • 隐藏表单
  • 将formLink1切换回原始文本。

我一直在尝试.toggle()组合来翻转它,然后.html()来编写已更改的文字,但没有运气。

无法找到与我正在做的事情相近的搜索,这是有道理的。

2 个答案:

答案 0 :(得分:1)

http://jsfiddle.net/ftDL8/ - DEMO

// switch your anchors to use classes. A href isn't a good idea, and a class
// allows us to select the multiple elements easier
$('.addItem').click(function(e){
    // if it's not already visible, show the form
    $('#theForm:not(:visible)').show();

    // prevent the anchor from firing
    e.preventDefault();
});

// again, anchor with the class
$('.cancelItem').click(function(e){
    // locate the form
    var $form = $('#theForm');

    // fire the native reset (bring all elements back to default values
    $form[0].reset();

    // now hide it
    $form.hide();

    // prevent the anchor from firing
    e.preventDefault();
});

// start off with the form hidden (using code)
$('#theForm').hide();

HTML:

<a href="#" class="addItem">Add an Item</a>

<form id="theForm">
    <input type="text" value="Original Content" /><br />
    <input type="text" value="Default Value" /><br />
    <a href="#" class="cancelItem">Cancel</a>
</form>

<a href="#" class="addItem">Add an Item</a>

答案 1 :(得分:0)

首先,将<a name=位更改为<a id=name属性是最初用于执行锚链接的不推荐使用的属性。它被id属性替换。

然后:

$('#formLink1').click(function(){
    $a = $(this);
    if ($a.text() == 'Add Item') {
        $('#theForm').show();
        $a.text('Cancel');
    } else {
        $('#theForm').hide();
        $a.text('Add Item');
    }
    return false;
});
相关问题