Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy input with .each() to multiple divs

Tags:

jquery

each

keyup

i want to copy the input from a user to multiple div's. I tried to use .each() because i want to apply it to every div that follows. I wrote this code so far, but it's only working for the first div.

<input type="text" name="someText" id="someText">



$("#someText").keyup(function() {
    var x = $("#someText").val();
    $("#copy").each(function () {
        $(this).html(x);
    });
});


<div id="copy"></div>
<div id="copy"></div>

Best Regards,

Felix

like image 727
Felix Avatar asked Feb 16 '26 06:02

Felix


1 Answers

IDs have to be unique:

id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.

Most browsers will return the first element of a document with a given ID, though the behaviour is unspecified.

Use classes instead if you want to select multiple elements:

HTML:

<div class="copy"></div>
<div class="copy"></div>

JavaScript:

$("#someText").keyup(function() {
    $(".copy").text(this.value);
});

Some other points:

  • You don't have to use .each, setter methods are normally always applied to all elements of the set.
  • Inside the event handler, this refers to the element the handler is bound to. You don't have to use the selector again.
  • If you already have a reference to a DOM element, it is often simpler to just access one of its properties directly instead of going through jQuery.
like image 131
Felix Kling Avatar answered Feb 17 '26 19:02

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!