Convert to jquery

Asked

Viewed 650 times

0

Good morning guys, after researching a lot, "I realized" how practical jquery is, but I came across an obstacle. How the script below would look in jquery format?

function enableQuantity(prod,quantity)
{

if(document.getElementById(prod).checked)
document.getElementById(quantity).disabled = false;          
else
document.getElementById(quantity).disabled = true;
document.getElementById(quantity).selectedIndex = 0;
document.getElementById('subtotal1').value = 0;
document.getElementById('subtotal2').value = 0;
document.getElementById('subtotal3').value = 0;
document.getElementById(quantity).value = total;
calculateTotal();		
}
function calculateTotal()
{
var products = new Array("Product10","Product20","Product30");
var i=0;
var total = 0;
var subtotal = 0;
for(i;i<products.length;i++)
	if(document.getElementById(products[i]).checked)
	{
		total  = total + parseInt(document.getElementById(products[i]).value) * parseInt(document.getElementById('QuantityProd'+(i+1)).value);
		
		subtotal1  = parseInt(document.getElementById('Product10').value) * parseInt(document.getElementById('QuantityProd1').value);
		subtotal2  = parseInt(document.getElementById('Product20').value) * parseInt(document.getElementById('QuantityProd2').value);
		subtotal3  = parseInt(document.getElementById('Product30').value) * parseInt(document.getElementById('QuantityProd3').value);

	}
	
document.getElementById('subtotal1').innerHTML = subtotal1;
document.getElementById('subtotal2').innerHTML = subtotal2;
document.getElementById('subtotal3').innerHTML = subtotal3;
document.getElementById('Total').value = total;

}
window.addEvent('domready', function() {
enableQuantity('Product10','QuantityProd1');
enableQuantity('Product20','QuantityProd2');
enableQuantity('Product30','QuantityProd3');
});
<div>
<label>Marca se Quero o Produto 1 (R$25)</label>
<input type="checkbox" value="25" id="Product10" onclick="enableQuantity('Product10','QuantityProd1');">
/
<label>Quantidade</label>
<select id="QuantityProd1" onchange="calculateTotal();">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<span>/ Exibe Subtotal no span = R$<span id="subtotal1">0</span></span></div>

<label>Marca se Quero o Produto 2 (R$35)</label>
<input type="checkbox" value="35" id="Product20" onclick="enableQuantity('Product20','QuantityProd2');">
/
<label>Quantidade</label>
<select id="QuantityProd2" onchange="calculateTotal();">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<span>/ Exibe Subtotal no span = R$<span id="subtotal2"></span></span>
</div>

<div>
<label>Marca se Quero o Produto 3 (R$45)</label>
<input type="checkbox" value="45" id="Product30" onclick="enableQuantity('Product30','QuantityProd3');">
/
<label>Quantidade</label>
<select id="QuantityProd3" onchange="calculateTotal();">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>

<span>/ Exibe Subtotal no span = R$<span id="subtotal3"></span></span>
</div>

<br>
<span>(essa div oculta se o produto1 não for selecionado)</span>
<div id="produto1_linha">
<span id="nome_produto1">Produto 1</span> /
<span id="quantidade_produto1"> {exibe quantidade selecionada}</span> /
<span id="subtotal_produto1"> {exibe subtotal}</span>
</div>
<br>

<span>(essa div oculta se o produto2 não for selecionado)</span>
<div id="produto2_linha">
<span id="nome_produto2">Produto 2</span> /
<span id="quantidade_produto2"> {exibe quantidade selecionada}</span> /
<span id="subtotal_produto2"> {exibe subtotal}</span>
</div>
<br>

<span>(essa div oculta se o produto3 não for selecionado)</span>
<div id="produto3_linha">
<span id="nome_produto3">Produto 3</span> /
<span id="quantidade_produto3"> {exibe quantidade selecionada}</span> /
<span id="subtotal_produto3"> {exibe subtotal}</span>
</div>
<br>
<div>
<label>Total</label>
<input type="text" value="0" id="Total" size="20">
</div>

This JS is for use in a Joomla plugin, so I made an HTML here quickly for viewing but it contains several errors. It’s basically a calculator. From now on, thank you

  • 2

    The live code of your example is not working here for me.

  • 2

    Put your HTML and arrange your snippet please. Maybe you can even improve your logic.

  • Thanks for the prompt return by mounting the sample html now for example.

  • @Danilofagundes, a Javascript tip, avoid searching for DOM elements unnecessarily, $('#id') and document.getElementById('id') are functions that involve a cost... so do them only once, store in a variable, then use this variable in your code.

2 answers

4


Danilo, first that I reserve the right to disagree that jQuery is more practical than Javascript, if we take into account only modern browsers and excluding the depedencia that some frameworks have with jQuery, I only see advantages in not using it.

$(function() {
  var total = $("#Total");
  var produtos = [$("#Product10"), $("#Product20"), $("#Product30")];
  var quantidades = [$("#QuantityProd1"), $("#QuantityProd2"), $("#QuantityProd3")];
  var subTotais = [$("#subtotal1"), $("#subtotal2"), $("#subtotal3")];

  function enableQuantity(produto, quantidade)
  {
    quantidade.prop("disabled", !produto.prop("checked"));
    quantidade.val('');
    calculateTotal();       
  }

  function calculateTotal()
  {
    var soma = 0;
    var subTotal = 0;
    for (var indice = 0; indice < 3; indice++) {
      if (produtos[indice].prop("checked")) {
        subTotal = parseInt(produtos[indice].val()) * parseInt(quantidade[indice].val());
        subTotais[indice].value = subTotal;
        soma += subTotal;
      }
    }
    total.val(soma);
  }

  for (var indice = 0; indice < 3; indice++) {
    enableQuantity(produtos[indice], quantidades[indice]);
  }
});

In the above code, I have made some improvements that I found pertinent, but it is possible to improve a little more:

$(function() {
  var total = $("#Total");
  var produtos = [$("#Product10"), $("#Product20"), $("#Product30")];
  var quantidades = [$("#QuantityProd1"), $("#QuantityProd2"), $("#QuantityProd3")];
  var subTotais = [$("#subtotal1"), $("#subtotal2"), $("#subtotal3")];
  var subTotal = 0;
  var soma = 0;

  for (var indice = 0; indice < 3; indice++) {
    quantidade.prop("disabled", !produto.prop("checked"));
    quantidade.val('');
    if (produtos[indice].prop("checked")) {
      subTotal = parseInt(produtos[indice].val()) * parseInt(quantidade[indice].val());
      subTotais[indice].value = subTotal;
      soma += subTotal;
    }
  }
  total.val(soma);
});

but see, what made the code here more compact, was not the choice by jQuery, but some decisions, now let’s see the same code using without jQuery:

document.addEventListener("readystatechange", function (event) {
  if (document.readyState == "interactive") {
    var sel = function sel(id) { 
      return document.getElementById(id);
    }
    var total = sel("Total");
    var produtos = [sel("Product10"), sel("Product20"), sel("Product30")];
    var quantidades = [sel("QuantityProd1"), sel("QuantityProd2"), sel("QuantityProd3")];
    var subTotais = [sel("subtotal1"), sel("subtotal2"), sel("subtotal3")];    
    var subTotal = 0;
    var soma = 0;

    for (var indice = 0; indice < 3; indice++) {
      quantidade.disabled = !produto.checked";
      quantidade.selectedIndex = 0;
      if (produtos[indice].checked) {
        subTotal = parseInt(produtos[indice].value) * parseInt(quantidade[indice].value);
        subTotais[indice].value = subTotal;
        soma += subTotal;
      }
    }
    total.value = soma;
  }  
});
  • Good afternoon friend, thank you for the prompt reply. I updated with an HTML example of what in practice should be the result, I saw that there are errors.On the issue of Jquery, it was involuntarily a comment from someone (I ;) who was impressed with some practical examples with so little code, but this idea is totally reversible, beginner thing.

  • @Danilofagundes, I do not deny the importance of jQuery, he brought a "standardization" between the browsers, a more flexible way to search for elements on the page and a series of methods that helped to manipulate the content... but the browsers have evolved, today there is already a certain "standardization", the added methods querySelector and querySelectorAll, was made available the prototype, and many objects have gained new methods through it, for example forEach, map, reduce, filter for the Arrays.

  • @Danilofagundes, a hint when using the Snippet to write your example code... select all (Ctrl + A) then use Shift + Tab... this will index your HTML, Javascript or CSS.

  • 2

    +1 for the first sentence and for the trouble of converting all the code, -jQuery, +Vanillajs.

  • @Danilofagundes, I updated the codes of my reply in view of your updated script.

  • @Tobymosque, This is my first post, I saw that I missed the way to post the code. I tried to fix now, the next I will do correctly. About the codes I will mount with html and put here working.

Show 1 more comment

2

The advantage of using a framework like Jquery is reuse of cross-browser compatibility and functions.

Note that many confuse Jquery as if it were a distinct Javascript language. Jquey is a framework written in Javascript.

However, that is not the focus of the question, so let’s answer.

In the script you posted, converting to Jquery functions is simple. Below are examples of what needs to be converted. A list of obvious locations where I was able to identify in a superficial view.

I refrain from rewriting the entire script as this is your job. The most I can provide you with is guidance on what to do.

Method getElementById()

Where do you have: document.getElementById, with Jquery would look like $().

Example:

document.getElementById('id_do_elemento')

Modify to

$('#id_do_elemento')

Note that it is the Sharp #character, which tells Jquery that it is the ID attribute.

Domready event

The excerpt window.addEvent('domready', function() {, just change to

$().ready(function() {

innerHTML method

Where has .innerHTML = 'bla bla';. swap for

.html('bla bla');

Example: $('#id_do_elemento').html('bla bla');

Checked attribute

if(document.getElementById(products[i]).checked)

Would look like this: if($('#'+products[i]+':checked').val())

Attribute value

Where has .value = 'bla bla';. swap for

.val('bla bla');

Example: $('#id_do_elemento').val('bla bla');

Disabled attribute

Where has .disabled = false;. swap for

.prop('disabled', false);

Example: $('#id_do_elemento').prop('disabled', false);

Attribute selectedIndex

Where has .selectedIndex = 0;. swap for

.prop('selectedIndex', 0);

Example: $('#id_do_elemento').prop('selectedIndex', 0);

  • @Renan when so you can edit it yourself.

  • Thanks @Daniel, following these valuable tips I will try to convert another code here for learning effect.

Browser other questions tagged

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