darkraja darkraja - 1 month ago 5
HTML Question

jQuery used to change multiple values on html texts with dropdowns

I have this html code :

<div class="option">
<h4 class="form-label">Quantité de data</h4>
<select class="selectpicker" name="Quantité de data" id=datanb>
<option value="10">10 gb</option>
<option value="20" selected>20 gb</option>
<option value="30">30 gb</option>
</select>
</div>


and these selects

<h4 class="form-label">Nombre de Semaine</h4>
<select class="selectpicker" name="Nombre de Semaine" id="weeknb">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>



<div class="option">
<h4 class="form-label">Quantité de data</h4>
<select class="selectpicker" name="Quantité de data" id=datanb>
<option value="10">10 gb</option>
<option value="20" selected>20 gb</option>
<option value="30">30 gb</option>
</select>
</div>
</div>


and I want to change the this code

<h2 class="price" id="lol"> 29€ - 1semaine - 20gb </h2>


the value 20 to be 10 or 30 depending the option value

I've tried this with jquery and is doesn't work.

$('#datanb').change(function() {
var nbweek = $('#weeknb');
var price = temp + 9;
$('#lol').text(price + '€ - ' + nbweek + 'semaine - ' +
var temp = (this.value * nbweek) + 'GB');
});

Answer

This is not valid syntax:

$('#lol').text(price + '€ - ' + nbweek + 'semaine - ' + 
  var temp = (this.value * nbweek) + 'GB'); 

you need to remove the var temp = also this: var nbweek = $('#weeknb'); should be var nbweek = $('#weeknb').val();

Here is a fixed version

$(function() {
  $('#datanb, #weeknb').on("change", function() {
    var nbweek = $('#weeknb').val(),
      gb = $('#datanb').val(),
      price = nbweek + 9;
    $('#lol').text(price + '€ - ' + nbweek + ' semaine' +
      (nbweek == "1" ? "" : "s") + ' - ' +
      (gb * nbweek) + 'GB');
  }).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="option">
  <h4 class="form-label">Quantité de data</h4>
  <select class="selectpicker" name="Quantité de data" id=datanb>
    <option value="10">10 gb</option>
    <option value="20" selected>20 gb</option>
    <option value="30">30 gb</option>
  </select>
</div>
<h4 class="form-label">Nombre de Semaine</h4>
<select class="selectpicker" name="Nombre de Semaine" id="weeknb">
  <option value="1" selected>1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<h2 class="price" id="lol"></h2>

Comments