Devesh Chauhan
Devesh Chauhan

Reputation: 411

How to remove appended element usng jquery?

I am creating a form. On submit of form for each input field there is an errorbox that is appended when that input field is not filled. I want to remove or display off that errorbox onFocus of that input field.While in my code that will remain at that position. I tried and I went through all of similar posts but not able to find solution. Thank you!

html code is like

<div class="rowform">
        <label for="name">Name<span>*</span>:</label>
        <input type="text" class="mid" name="name" id="name" onFocus="fcs();"/><span id="name_error"></span>

    </div>

script //on submit of form how I am appending errorbox

if($("#listcontact #name").val()==""){
    $("#name_error").append("<div class='formerror'>Please enter your name</div>");
}

//the on Focus function is like

    function fcs()
{
$(".formerror").remove();}

Upvotes: 1

Views: 2396

Answers (4)

Popsyjunior
Popsyjunior

Reputation: 305

I'm not sure how you want to implement it, but, I hope this helps:

<div class="rowform">
    <label for="name">Name<span class='name-check'>*</span>:</label>
    <input type="text" class="mid" name="name" id="name" onFocus="fcs('name', this);"/><span id="name_error"></span>
</div>

<script>
    function fcs(err,obj) {
        if( $(obj).val() == "" ) {
            $("." + err + "-check").show();
        }
        else {
            $("." + err + "-check").hide();
        }
    }
</script>

Upvotes: 0

Matthijs
Matthijs

Reputation: 568

Something like:

$(".rowform").on("focus", "input", function(){
    $(this).closest(".rowform").find(".formerror").hide();
});

Update: Indeed no need of event delegation like Ian said.

$(".rowform").find('[type="text"]').on("focus", function(){
    $(this).closest(".rowform").find(".formerror").hide();
});

Working fiddle: http://jsfiddle.net/Ar7AT/

Upvotes: 3

Sara Goodarzi
Sara Goodarzi

Reputation: 237

you can use .remove() instead .hide()

$(".rowform").on("focus", "input", function(){
    $(this).closest(".rowform").find(".formerror").remove();
});

Upvotes: 0

maverickosama92
maverickosama92

Reputation: 2725

try following

$("#name").focus(function(){
    $(".formerror").remove();
});

$("#btn").on("click",function(){

 $(".formerror").remove();

 if($("#name").val()==""){  
    $("#name_error").append("<div class='formerror'>Please enter your name</div>");
 }
});

working fiddle here: http://jsfiddle.net/fzS95/1/

i hope it helps.

Upvotes: 0

Related Questions