vipul sharma vipul sharma - 4 months ago 8
HTML Question

How to use jquery to change html dynamicly with custum attribute

I want to create a jquery function which will check the custum attribute of a div and change its html according to that.

Like if we have n number of divs with same class

<div class="dynamic" data-rate="2"></div>
<div class="dynamic" data-rate="3"></div>
<div class="dynamic" data-rate="4"></div>


as you can see all have different data-rate values

I want its output like this

<div class="dynamic" data-rate="2">
1
2
</div>

<div class="dynamic" data-rate="3">
1
2
3
</div>


even after page load if i change the value of data-rate than it will able to change the html inside it according to data-rate value

Answer

Try this code

<html>
<head>
<title>Dynamic add html</title>
<script src="jquery-1.7.2.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $('.dynamic').each(function(){  
            var val=$(this).attr('data-rate');
            if(val!='')
            {
                for(i=1;i<=val;i++)
                {                   
                    $(this).append(i)+ "\n";
                }
            }
        });
    }); 
</script>
</head>
<body>
    <div class="dynamic" data-rate="2"></div>
    <div class="dynamic" data-rate="3"></div> 
    <div class="dynamic" data-rate="4"></div>
</body>
</html>