user9903025
user9903025

Reputation:

Remove the dynamically added label text on entering the value

I've appended all the label text to the div#test if the value of the input is empty and would like to remove the same when the user is entering/selecting values in the textbox/dropdown.

<div id="test">
</div>
$('input, select').each(function(){
    var $element = $(this)

    if ($element.val() == '') {
        var $label = $("label[for='"+this.id+"']");
        $("#test").append($label.text());
    }

}); 

Note: Added only the relevant code as the form is big.

Upvotes: 1

Views: 667

Answers (1)

Gustav P Svensson
Gustav P Svensson

Reputation: 517

Im not exactly sure this is what you want. If I understod your question you want to remove the labels that have a value in the input field from the #test div.

HTML code:

<label for="input_1">Label</label><br />
<input type="text" name="input_1"/><br />
<label for="input_2">Label2</label><br />
<input type="text" name="input_2" />

Javascript code:

function addEmptyToDiv() {
    $('input, select').each(function(){
        var $element = $(this)

        if ($element.val() == '') {
          var $label = $("label[for='"+this.name+"']");
          $("#test").append($label.text());
        }
    }); 
}
addEmptyToDiv();


$('input, select').on("change paste keyup blur", function() {
    // Remove everything from the #test div
    $("#test").empty();
    addEmptyToDiv();

});

Working fiddle: https://jsfiddle.net/6csyoL24/

Upvotes: 0

Related Questions