How do I convert from JavaScript to jQuery?

Hi, I have a page that needs to be transferred over to jQuery from JavaScript. I’m not sure where to start?

The first thing on the page is a table where you type in the addition between the two numbers. If the typed in number is incorrect the background color turns red.
Then the second part is validating an email. if the email is correct the background is transparent if it is not valid it goes red.

<!Doctype html>
<html>

<head>
<link rel="stylesheet" href="assignment-Jasmine.css">
<title>JavaScript to jQuery </title>
<script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous">
</script>
</head>

<body>

<script type="text/javascript" src="age.js"></script>
	<p id="selectedGrade"></p>

	<br>
<!-- Math Html -->
	<h4>Math!</h4>
	<p>Try to see if you can do the math</p>
		<table id="addition-table">
			<tbody>
				<tr class="Calculation">
					<td>5</td>
					<td>3</td>
					<td><input type="text"></td>
				</tr>
				<tr class="Calculation">
					<td>7</td>
					<td>6</td>
					<td><input type="text"></td>
				</tr>
				<tr class="Calculation">
					<td>5</td>
					<td>5</td>
					<td><input type="text"></td>
				</tr>
				<tr class="Calculation">
					<td>8</td>
					<td>3</td>
					<td><input type="text"></td>
				</tr>
				<tr class="Calculation">
					<td>4</td>
					<td>7</td>
					<td><input type="text"></td>
				</tr>
				<tr class="Calculation">
					<td>3</td>
					<td>9</td>
					<td><input type="text"></td>
				</tr>
				<tr class="Calculation">
					<td>8</td>
					<td>5</td>
					<td><input type="text"></td>
				</tr>
				<tr class="Calculation">
					<td>2</td>
					<td>6</td>
					<td><input type="text"></td>
				</tr>
				<tr class="Calculation">
					<td>5</td>
					<td>9</td>
					<td><input type="text"></td>
				</tr>
				<tr class="Calculation">
					<td>6</td>
					<td>6</td>
					<td><input type="text"></td>
				</tr>
			</tbody>
		</table>
<script type="text/javascript" src="math.js"></script>
	<br>
<!---- Email Html--->
	<h4>Email Validation!</h4>
	<p>Type in Your Email</p>

		<input type="email" id="email">
		<br>
		<br>
<script type="text/javascript" src="email.js"></script>

</body>
</html>
``
//Math Code
	
	(function( math )  { 
			   'use strict';
			   var tr = math.querySelectorAll( 'tr' ), 
				   td = math.querySelectorAll( 'td' ), 
				  inp = math.querySelectorAll( 'input' ),
			   totals = [], c;
		   for ( c = 0; c < tr.length; c ++ ) {
				 totals.push( parseFloat( td[ c * 3 ].textContent ) + 
							  parseFloat( td[ c * 3 + 1 ].textContent ) );
				 inp[ c ].value = ' ';				   
				 inp[ c ].addEventListener( 'blur', check_answer( c ), false );

			}

	function check_answer( c ) {
		   inp[ c ].onblur = function() { 
			  if( inp[ c ].value == totals[ c ] ) {
				  tr[ c ].classList.add( 'right' );
				 }
					  else {
						 tr[ c ].classList.remove( 'right' );
						 tr[ c ].classList.add( 'wrong' );
						 }
					  }			   
				   }
	 }( document ) ); 

//Email Code
var email = document.getElementById(‘email’)

		email.addEventListener('blur', function (event) {
		  event.target.style.backgroundColor = event.target.validity.valid
			? 'transparent'
			: 'red'
		})

Thanks for any help

Check out the .css() jQuery method for changing the background colors to red (e.g. $("#jquery-selector").css("background-color", "red"); ). :slight_smile:

Show us your attempt at converting it.

Would this be close to what the email validation would be?

$ ('#email').blur(function(){
	event.target.style.backgroundColor = event.target.validity.valid
			? 'transparent'
			: 'red'
});	

and would this be close for the math?


$('math').blur(function(){
	 'use strict';
				   var tr = math.querySelectorAll( 'tr' ), 
					   td = math.querySelectorAll( 'td' ), 
					  inp = math.querySelectorAll( 'input' ),
				   totals = [], c;
			   for ( c = 0; c < tr.length; c ++ ) {
					 totals.push( parseFloat( td[ c * 3 ].textContent ) + 
								  parseFloat( td[ c * 3 + 1 ].textContent ) );
					$(inp[ c ]).value = ' ';				   
					 $(inp[ c ]).blur, check_answer( c ), false );
}
});

$('c')onblur(function(){
	   inp[ c ].onblur = function() { 
				  if( inp[ c ].value == totals[ c ] ) {
					  tr[ c ].classList.add( 'right' );
					 }
						  else {
							 tr[ c ].classList.remove( 'right' );
							 tr[ c ].classList.add( 'wrong' );
							 }
						  }			   
					   }
});

The original code that you started with works in a jQuery environment. What I suspect is happening is that you are being asked to convert this to jQuery as a way of teaching you about the library.

jQuery has a CSS method that you might want to use.

Does that code work? It looks like you’ve done some things that just can’t work (such as the math selector) and haven’t converted other things such as document.querySelectorAll.

What would I do to convert the code to jQuery?

/me writes very long post about everything I would do to convert the code to jQuery

/me deletes full post

I’ve learned that presenting all for that information won’t be helpful for you at all.

Instead, if I didn’t know much about jQuery? I would do a google search for jquery combined with different keywords from the code.

For example, searching for jQuery querySelectorAll gives results that show people using the dollar symbol. Searching for jQuery for gives results about the each method. Searching for jQuery textContent gives results about the text method.

That is a suitable pathway that you can take to help with your assignment.

3 Likes

Thanks. In jQuery do you still use the if arguments?

Answer 1: jQuery is not a different language. It’s just a library of useful functions that was originally meant to fix incompatibilities across different web browser, that isn’t needed any more.

Answer 2: Yes.

2 Likes

I asked Google the question: Is jQuery needed anymore? and these are the top ten results that I was given. I’ve sorted them by date too.

Please note that I didn’t ask Google if we shouldn’t use jQuery. My question of Is jQuery needed anymore? allows for both positive and negative responses.

I recommend that you read most of the above articles as that helps to give you a good education about how jQuery is supposed to be used.

Now that isn’t to say that you shouldn’t learn about jQuery. It’s just that the grave has been dug, the funeral director is waiting, the undertakers are leaning on their shovels, and the oven savories are turning hard and dry.

We’ve had a similar experience with waiting for Internet Explorer to die, but it’s still trying to claw its way out no matter how many times we hit it back down with the shovel.

2 Likes

Just a bit of procrastinating, before I start my course.

There’s more to Jquery than it’s selector engine (sizzle), but just to illustrate why it could be so useful prior to querySelectorAll

html example

<div id='lists'>
    <ul class='list-items'>
       <li class='item1'>Some Text</li>
       <li class='item2'>Some Text</li>
       <li class='item3'>Some Text</li>
       <li class='item4'>Some Text</li>
       <li class='item5'>Some Text</li>
    </ul>
    <ul class='list-items'>
      <li class='item1'>Some Text</li>
      <li class='item2'>Some Text</li>
      <li class='item3'>Some Text</li>
      <li class='item4'>Some Text</li>
      <li class='item5'>Some Text</li>
    </ul>
    <ul class='list-items'>
      <li class='item1'>Some Text</li>
      <li class='item2'>Some Text</li>
      <li class='item3'>Some Text</li>
      <li class='item4'>Some Text</li>
      <li class='item5'>Some Text</li>
    </ul>
  </div>

Note: A bit of head scratching trying to remember how to do it the legacy way

Jquery, JS old and new. Select various list items and colour them

// Legacy way of doing it in vanilla JS, before we had querySelectorAll. list item2s

var lists = document.getElementById('lists');
var listItems = lists.getElementsByTagName('LI');

for (var i = 0, len = listItems.length; i < len; i += 1) {
  if ( /\bitem2\b/.test(listItems[i].className) ) {
    listItems[i].style.color = 'red'
  }
}

// Jquery way of doing the same. list item3s
$('#lists .item3').css( 'color', 'green' )

// Current way of doing it in vanilla JS. list item4s
document.querySelectorAll('#lists .item4').forEach( elem => elem.style.color = 'blue' )

Just as a side note, Secrets of the Javascript Ninja, which is written by Jquery’s original creator John Resig gives you a good insight into under the hood of Jquery. The first edition you can pick up second hand for a few dollars.

1 Like

Thats a-lot of help. I think where im confusing myself is when the user puts in the answer the jquery needs to run and change the background color if they are incorrect. so it needs to do the math to see what the answer is supposed to do. I think that is where I make mistakes.

As Paul says you can use ‘if’ inside the function call back.

The higher order bit to it with callbacks, can be confusing I know that, but in the end the callback is just a javascript function. You can mix javascript with your jquery

I don’t know if this confuses things — hopefully it helps.

function jQueryish(select, func /* func is a function/callback you will pass in */) {
  const selection = document.querySelectorAll(select)

  for (let i = 0, len = selection.length; i < len; i +=1) {
      // call the function you give it passing in the element and an index
      func(selection[i], i)
  }
}

jQueryish('#lists li', function( elem /* selection[i] */ ) {

  // this is just the inside of a Javascript function. nothing magic

  if (elem.classList.contains('item2')) {
    elem.style.backgroundColor = 'teal'
  } else if (elem.classList.contains('item4')) {
    elem.textContent = 'bananas'
  }
})

My advice (I don’t know if that is good or bad:)) would be scratch your current JS, then break it down an simplify.
Reduce it down to just one table row, with it’s three table cell elements (‘.calculation td’)

<tr class="calculation">
    <td>5</td>
    <td>9</td>
    <td><input type="text"></td>
</tr>

See if you can work with that first to check if the input value is correct
textContent and val() may come in handy
https://api.jquery.com/val/

1 Like

@jlusty Typically jQuery is used in tandem with (aka: at the same time. In the same script as) regular Javascript code. So when you “convert code to jQuery,” you usually aren’t converting EVERY line of code and EVERY method. There is plenty of vanilla JavaScript code that will be left in there, too.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.