Jquery Mask in dynamically created fields

Asked

Viewed 1,306 times

5

I have a product values registration page, where I have an input field with value mask in R$. But since this field is created dynamically after a search in the comic book, the mask then works only in the first input. I know of a solution but it doesn’t stay friendly beyond slowing down the page. I wanted a practical and viable solution. Follow the codigo.

HTML:

<?php foreach ($produtos as $produto) {
    echo "<div class='produtos'>
        <div style='float:left;'><img src=".base_url()."uploads/produtos/".$produto->foto." title=".$produto->nome."></div>
                <div class='descricao_produto'>
                    <font size='4'>".$produto->nome."</font><br>
                    <font size='2'>".$produto->descricao."</font><br>
                    <input type='text' name='preco_produto' style='width:60px;' value='' placeholder='Preço' id='preco'>
                </div>
            </div>";
} ?>

JS:

$(document).ready(function(){
   $("#preco").maskMoney({symbol:'R$ ', 
   showSymbol:true, thousands:'.', decimal:',', symbolStay: true});
});

2 answers

4

Instead of using id '#price', try using a class, '.price' for example.

Your code would look like this:

$(".preco").maskMoney({symbol:'R$ ', ...

4


A major flaw you’re commenting on is putting the same id in various elements with this foreach() in his , ideal is that you replace it with a class.

Php

<?php foreach ($produtos as $produto) {
    echo "<div class='produtos'>
        <div style='float:left;'><img src=".base_url()."uploads/produtos/".$produto->foto." title=".$produto->nome."></div>
                <div class='descricao_produto'>
                    <font size='4'>".$produto->nome."</font><br>
                    <font size='2'>".$produto->descricao."</font><br>
                    <input type='text' name='preco_produto' style='width:60px;' value='' placeholder='Preço' class='preco'>
                </div>
            </div>";
} ?>

jQuery

$(document).ready(function(){
   $(".preco").maskMoney({symbol:'R$ ', showSymbol:true, thousands:'.', decimal:',', symbolStay: true});
});

You can check the result in this jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.