0

Currently working with Javascript and JQuery (both which I'm new to so go easy on me) and the goal is to, when the form is filled out incorrectly. To add add a message that says the form is incorrect. When the form is inputed correctly, then the "incorrect" message should be removed. However, after inputed a bad input to prompt the additional HTML, when I correct the form to get rid of it, the javascript terminates after the remove function.

Also, is there anyway to remove on condition? In other words, is there a pre-existing method that says, "if the html exists to remove, then remove, else do nothing." or do I have to write my own flag.

    $(document).ready(function ()
    {
        $('#basic').on('submit', function(e)
        {
            if(!isBasicInfoValid())
            {
                if(!error)
                {
                    $('#basic').append($("<div class='basicError'>Input is not valid! </div>"));
                }
                error=true;
            }
            else if(error)
            {
                error=false;
                $('#basic').remove($(".basicError"));
                //program is stopping after remove for some reason
            }
            e.preventDefault();
        });
    };
   <body>
        <div class='form'>
            <h3> Basic Information </h3>
            <form id='basic'>
                <div>Year of Birth: <input type='number' name='YOB'> </div> 
                <div>Current Savings: <input type='number' name='CurrSav'> 
                </div>  
                <div>Expected Retirement Age: <input type='number' name='RetAge'></div>     
                <div>Life expectancy: <input type='number' name='LifeExp'>
                </div>  
                <div><input type='submit' value='Submit'></div> 
            </form>
        </div>
        <div class='form'>
            <h3> Scenario </h3>
            <form id='scenario'>
                <div>Name: <input type='text' name='ScenarioName'> </div>
                <div>Rate of Investment Return (While Working): <input type='number' name='Working'></div>
                <div>Rate of Investment Return (Retired): <input type='number' name='Retired'></div>
                <div>Desired Retirement Yearly Income: <input type='number' name='desiredInc'></div>
                <div><input type='submit' value='Submit'></div>
            </form>
            <div><button id='add' type='submit'>Add Scenario </button></div>
        </div>
</body>
4

3 回答 3

3

尝试改变:

$('#basic').remove($(".basicError")); 

只是:

$('#basic').remove(".basicError");
于 2013-10-02T08:30:05.850 回答
2

remove接受一个选择器,你给它一个 jQuery 对象。它正在停止,因为 jQuery 将抛出一个 JS 错误,因为它需要一个选择器。

尝试这个:

$('#basic').remove(".basicError");

或者,因为只有一个.basicError,你可以这样做:

$(".basicError").remove();
于 2013-10-02T08:29:17.910 回答
0

尝试

$('#basic').children('.basicError').remove();

或者

$("#basic .basicError").remove();
于 2013-10-02T08:32:25.733 回答