Home > DeveloperSection > Forums > How to get and set attribute in jquery
Andrew Watson
Andrew Watson

Total Post:39

Points:273
Posted on    February-20-2015 6:19 AM

 JavaScript JQuery  Jquery Selectors 
Ratings:


 1 Reply(s)
 639  View(s)
Rate this:

Hi I’m trying to get attribute and then after set attribute

Here is my code

 

<div class="box" style="width:100px;height:300px;background-color:#ffd800;">

    <p>Are you want to jquery</p>

</div>

 

<input type="button" class="btn" value="Green" style="background-color:green;color:#fff;" />

<input type="button" class="btn" value="Red" style="background-color:red;color:#fff;" />

<input type="button" class="btn" value="Blue" style="background-color:blue;color:#fff;" />

 

 

<script>

    $(document).ready(function () {

        $('.btn').click(function () {

            var btnvalue = $(this).getAttribute('value');

            $('.box').setAttribute('style', 'background-color:' + btnvalue);

        });

    });

</script>

 

My question is when click on green button that time box color green and when click red button that time box color red.

My code is not work properly.



Sanjay Sharma
Sanjay Sharma

Total Post:45

Points:315
Posted on    February-20-2015 6:30 AM

Hi you can use this code for get and set attribute

<div class="box" style="width:100px;height:300px;background-color:#ffd800;">

    <p>Are you want to jquery</p>

</div>

 

<input type="button" class="btn" value="Green" style="background-color:green;color:#fff;" />

<input type="button" class="btn" value="Red" style="background-color:red;color:#fff;" />

<input type="button" class="btn" value="Blue" style="background-color:blue;color:#fff;" />

 

 

<script>

    $(document).ready(function () {

        $('.btn').click(function () {

 

            //here we get attribute of clicked button

            var btnvalue = $(this).attr('value');

 

            //here we set attribute in box div

            $('.box').attr('style', 'background-color:' + btnvalue);

        });

    });

</script>


Don't want to miss updates? Please click the below button!

Follow MindStick