3

I want to clear the input value with class "inputF" generated by the append in jQuery,

<script type="text/javascript" src="jquery.min.js"></script>
<script>
$(document).ready(function () {
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID

    $(add_button).click(function (e) { //on add input button click
        e.preventDefault();

        $(wrapper).append('<div><input type="text" class="inputF" name="mytext[]"/>\n\
                <button name="remove" class="remove_field">x</button>\n\
                <button name="clear" class="clear_field">clear</button>\n\
                <input type="checkbox" class="check" group="check">\n\
              </div>'),
    });

});
</script>
<div class="input_fields_wrap">
<button class="add_field_button">+</button>
<button class="show_field_button">show all</button>

This didn't worked for me,

    $(wrapper).on("click", ".clear_field", function () {
        $(this).find('.inputF').val('');
    });

What is the proper way to write it?

1
  • Vesion of jQuery is v1.12.3 Commented May 19, 2016 at 14:33

3 Answers 3

2

While your html structure looks like

<div>
     <input type="text" class="inputF" name="mytext[]"/>
     <button name="remove" class="remove_field">x</button>
     <button name="clear" class="clear_field">clear</button>
     <input type="checkbox" class="check" group="check">
</div>

you need to use .parent();

$(wrapper).on("click", ".clear_field", function () {
     $(this).parent('div').find('.inputF').val('');
});

or .closest();

$(wrapper).on("click", ".clear_field", function () {
     $(this).closest('div').find('.inputF').val('');
});
Sign up to request clarification or add additional context in comments.

Comments

1

You have incorrect selector to target sibling element:

$(wrapper).delegate("click", ".clear_field", function () {
    $(this).closest('div').find('.inputF').val('');
});

4 Comments

What have you changed? Isn't that exact copy of OP code
@Keyur:what version of js you are using and where are you binding the event.
@Tushar: OP was using delegate , i suggested using .on instead
Vesion of jQuery is v1.12.3 @MilindAnantwar
1

Just replace :

$(this).find('.inputF').val('');

With :

$(wrapper).find('.inputF').val('');

1 Comment

Thank you very much. But it is removing all textbox values. Which I don't want to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.