Add div outside parent of input

I am new to javascript and I just cannot figure it out despite my trying to research. How to track input change in div and trigger append to outer div? My code looks like this:

Add h3 with "Wait" after typing ".image-value" with changing value

<!-- APPEND <h3> -->
<h3>Best Overall Costume<div class="pending">Pending</div></h3>
<div>
  <div class="select-form">
    <img src="images/vote.jpg" data-value="image_value">
    <img src="images/vote.jpg" data-value="image_value2">
    <img src="images/vote.jpg" data-value="image_value3">
    <img src="images/vote.jpg" data-value="image_value4">
    <img src="images/vote.jpg" data-value="image_value5">
    <!-- Track the change of this input -->
    <input type="hidden" class="image-value" name="selected_image" value="">
  </div>
</div>

      

I've tried this:

function changeStatus(statusValue) {
    $("input",".select-form").val(statusValue).trigger("change");
}

$("input",".select-form").change(function(){
    if (!$(this).val()){
        $("<div class='pending'>Pending</div>").appendTo($("h3").prev($(this)));
    }
});

      

But that didn't seem to work. Any ideas?

+3


source to share


3 answers


place an empty div where you want your new div and give it an ie ( <div id='myDiv'><div>

) id and then add what you want like this.

$( "#myDiv" ).append( "<div class='pending'>Pending</div>" );

      

You can also check Append Explained



for more explanation.

Thank.

+1


source


I've done a couple of things here ... First, I'm not sure why you had all of this in a named function. When you use event listeners that are often unnecessary.

Then I don't know what the val check was for, so I canceled it.

Finally, I use one()

one that only works once. This case seemed to demand.



$('.select-form').one('change', 'input', function () {
    if ( $(this).val() ) { alert('asdgf');
        $("<div class='pending'>Pending</div>")
            .appendTo($(this).parent().prev('h3'));
    }
});

      

Fiddle

+1


source


try this:

$("input",".select-form").on("change", function(){
     var $this = $(this);
     if (!$this.val()){
            var elem = $('<h3>Best Overall Costume<div class="pending">Pending</div></h3>');                
            $this.parent().parent().before(elem);
     }
});

      

you can also put a check if the pending div has already been added, rather than add it again.

Of course, this solution assumes there are no other nested divs between the target div (before which you want to add) and the input control

0


source







All Articles