1

i've tried to count the value of selected option of the following multiple combo box.

<form method="post" name="transaksi" action="proc.php">

<select name="bulan_catering[]" id="id_cur_month_catering" size="12" multiple="multiple" onchange="update_catering()">
<option value="jul-20132014-3500">[2013-2014] July</option>
<option value="aug-20132014-3700">[2013-2014] August </option>
<option value="sep-20132014-4100">[2013-2014] September </option>
<option value="oct-20132014-4200">[2013-2014] October </option>
<option value="nov-20132014-4800">[2013-2014] November </option>
<option value="dec-20132014-5100">[2013-2014] December </option>
</select>
Total payment: <input type="text" name="catering">

And i use this simple javascript to get the value.

<script type="text/javascript" language="javascript">
function update_catering() {
   var num_month_catering = document.getElementBy("id_cur_month_catering").value;
   var cur_payment_catering = num_month_catering.substring(13);
   document.transaksi.catering.value = cur_payment_catering;
}
</script>

What i need to do is, for example if user selects july, august and september, it should count 3500+3700+4100. and the result for total payment should 11300. But it doesn't work as i want. It is only showing value of the last selected option. in this case it shows 4100 (last value). Can some one help me to do the right way in javascript as i explained above, please.

Thank You.

3 Answers 3

1

This is a fairly basic solution. You should do research before posting a question on StackOverflow. But here's your solution

var intNumber = 0;
var arrListOptions = document.getElementById('id_cur_month_catering').options;
for(intIterator = 0; intIterator < arrListOptions.length; intIterator ++){
    if (arrListOptions[intIterator].selected == true){
       intNumber += parseInt(arrListOptions[intIterator].value.split('-')[2]);
    }
}

intNumber would contain the sum of each number selected in the list.

Here's the list of link that would allow you to learn the basis on javascript for this short script:

Also, here's an example of a similar question you could have inspired yourself from:

I would also recommand you to learn jQuery as this would allow you to have access to more coding functionnality that are relatively common nowday (like foreach in php, would be .each in jQuery). That would help you be more prepared later when doing development.

I hope this have been helpful :-)

Sign up to request clarification or add additional context in comments.

7 Comments

w3schools is deprecated as a reliable source of information. Also, there's no need to send the OP down the jQuery rabbit hole.
Thank you for your answer, it is working well. And also for the link resources. I've searched the similar problem before. but i haven't found the best solution. and the case that you gave in your link (stackoverflow) is not what i need, it's different. And yes. i'll think to use jquery next. Thank you Loïc Lavoie
@torazaburo For the basics, it's still a valid website, especially with beginner's question. For the jQuery, it's all a matter of personnal choice, but I recommand strongly to any Front-end developer to at least know one of the main JS framework (jQuery, Bootstrap, etc...). It saves time an allow more long-term professionnal development.
@Bersama You're welcome :-) Happy to have helped :-)
jQuery is not a framework, it's a library, quite a different thing.
|
0

The cool thing is that jQuery .val() method returns an array of values for select box with multiple attribute, so, just go through that array and collect the prices ( with .replace() and regex for example ), and calculate the sum of values with .reduce().

$( '#id_cur_month_catering' ).on( 'change', function() {

    var sum = $(this).val()
        .map( function( value ) {
            return value.replace( /.+?-(\d+)$/, function( match, num ) { return num; });
        })
        .reduce( function(a, b) { 
            return parseInt(a, 10) + parseInt(b, 10); 
        });

    $( 'input[name=catering]' ).val( sum );

})

However, I'm not sure whether is jQuery relevant for this question.

FIDDLE

2 Comments

You should ask in a comment whether the OP is interested in a jQuery solution.
Thank you Danijel, but for now i prefer to use javacsript
0

I'd personally suggest:

function update_catering() {
  // getting all the options, and turning them into an Array (from a NodeList),
  // iterating over that array to keep only those that are selected:
  var selectedOptions = [].slice.call(this.options, 0).filter(function(opt) {
      return opt.selected;
    }),
  // iterating over the selectedOptions array to form a map of the values:
  values = selectedOptions.map(function(opt) {
    // keeping the numeric last-numbers from the value of the option element:
    return parseFloat((/\d+$/).exec(opt.value));
  });
  // setting the value of the <input> element to the sum of the selected
  // <option> elements' numbers:
  document.getElementById('result').value = values.reduce(function(a, b) {
    return a + b;
  });
}

// binding the change event-handler outside of the HTML, for a less
// obtrusive approach:
document.getElementById('id_cur_month_catering').addEventListener('change', update_catering, false);
<form method="post" name="transaksi" action="proc.php">

  <select name="bulan_catering[]" id="id_cur_month_catering" size="12" multiple="multiple">
    <option value="jul-20132014-3500">[2013-2014] July</option>
    <option value="aug-20132014-3700">[2013-2014] August</option>
    <option value="sep-20132014-4100">[2013-2014] September</option>
    <option value="oct-20132014-4200">[2013-2014] October</option>
    <option value="nov-20132014-4800">[2013-2014] November</option>
    <option value="dec-20132014-5100">[2013-2014] December</option>
  </select>
  Total payment:
  <input id="result" type="text" name="catering">
</form>

References:

2 Comments

What is this.options? Also, I wonder why you would use a forEach with a push (onto an undeclared variable values) inside, instead of map. Finally, there is no need to do [].slice.call(this.options,0).filter when you can just do [].filter.call(this.option).
this.options is a NodeList (or collection, I can't remember right now) of the <option> elements belonging to the <select> element; this being the <select>. As for map(), honestly I just didn't think of it, but thank you (I'll experiment with it momentarily).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.