Don
Don

Reputation: 1570

Toggle, change html and reset form

I'm relatively new to JQuery, but I'm pretty sure this is possible...

<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>

If you click formLink1 or formLink3 above:

Clicking on either formLink2, or formLink1 when the form is open (and it shows "cancel" would:

I've been trying a combination of .toggle() to flip it, and then .html() to write the changed text but no luck.

Can't find a search that matches close enough to what I'm doing that makes sense.

Upvotes: 1

Views: 1092

Answers (2)

Brad Christie
Brad Christie

Reputation: 101614

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();

The 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>

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239300

First, change the <a name= bit to <a id=. The name attribute is a deprecated attribute originally used to do anchor links. It was replaced by the id attribute.

Then:

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

Upvotes: 0

Related Questions