user image

Mahmoud Santos
Published in : 2022-02-27

How select specific tag in jQuery using if else statement?

Javascript

I would like to click the button and make the value appear in <h3> inside the <div> and according to that value the background-color would change.

For example, when I typed a value (Your number) and clicked on Click Me!, h3 inside the div should show this typed value and the background-color would also change accordingly.

For example, if I typed 33 in Your number and then clicked, the value to appear would be 33 and the color would be orange. Thus:

My code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form name="myform">
 Your number: 
 <input type="text" name="inputbox" id='textBox' value="" />
 <input type="button" name="button" value="Click me!" />
 <div class='box1' style='background-color:lime;width:33.33%;padding-left:15px;padding-right:15px;'>
  <h3>
  0
  </h3>
  <p>
  Valor
  </p>
 </div>
</form>
<script>
 $(function() {

  $('.member').click(function() {
   var answer = $("#textBox").val();
   if (answer <= 20) {
    $('.box1').css('background-color','red');
   } else if (answer <= 50) {
    $('.box1').css('background-color','orange');
   } else {
    $('.box1').css('background-color','steelblue');
   }
  });

 });

</script> 

So I wanted to select the h3 tag and change it with if else statement.

Comments

Eslam Zedan Date : 2022-02-27

Best answers

8

Best answers

8

Please check the solution :

$(document).ready(function() {

    $('.member').click(function() {
      let answer = $("#textBox").val();
      let color;
      if (answer <= 20) {
        color = 'red';
      } else if (answer <= 50) {
        color = 'orange';
      } else {
        color = 'steelblue';
      }
      
      $('.box1').css('background-color',color).find('h3').html(answer);
      
    });

  });

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Can we add a javascript or jQuery to the URL?
Publish date: 2022-03-05 | Comments: 2

Tag: Javascript

Adding an id number at the first index to an array of objects
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript

Simple HTML date picker is showing not showing calendar icon!
Publish date: 2022-03-01 | Comments: 2

Tag: Javascript

javascript: Uncaught TypeError: undefined is not a function
Publish date: 2022-03-02 | Comments: 2

Tag: Javascript

How to get audio input and audio output as one stream?
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript

Coping plain text into form bug.
Publish date: 2022-02-11 | Comments: 1

Tag: Javascript

How to open URL in new tab & focus on it in Javascript?
Publish date: 2021-12-22 | Comments: 1

Tag: Javascript