user2390604
user2390604

Reputation: 3

display selected checkbox options on the page

was wondering if i could get a little help. I have 3 checkboxes and want to display the text before each checkbox back to the user.

<form id="extras" onchange="calculate()">
    option 1<input type="checkbox" name="box" value="2000" id="snow" onchange="calculate()" checked><br>
    option 2<input type="checkbox" name="box" value="500" id="water" onchange="calculate()" checked><br>
    option 3<input type="checkbox" name="box" value="150" id="air" onchange="calculate()"><br><br>
</form>

so i can say you have selected option 1 and option 2 if they are both selected. Ive managed to to this for my dropdown using innerHTML but am unsure how to achieve this for the checkboxes. any ideas on how i can do this? thanks for any advice.

Upvotes: 0

Views: 2076

Answers (2)

Rob R
Rob R

Reputation: 1161

Here you go. I wrote this in jQuery, but you can convert it to vanilla JS.

http://jsfiddle.net/P2BfF/

Essentially you need to create labels for your checkboxes:

<label for='snow'>option 1</label>

Then based on checked, you can display the innerHTML of that element.

Here is my JS:

    var checkboxes = $('#extras').find('input[type=checkbox]');

checkboxes.on('click',function() {
    var selected = [];
    checkboxes.each(function(idx,item) {

        if (item.checked)
           selected.push( $('label[for="' + item.id + '"]').html() );
    });

    return alert(selected);
});        

Upvotes: 0

G&#246;khan Girgin
G&#246;khan Girgin

Reputation: 1164

HTML

<form id="extras">
    <label id="lbl_1">option 1</label><input type="checkbox" name="box" value="2000" id="1" onchange="calculate()"><br>
        <label id="lbl_2">option 2</label><input id="2" type="checkbox" name="box" value="500" onchange="calculate()"><br>
        <label id="lbl_3">option 3</label><input type="checkbox" name="box" value="150" id="3" onchange="calculate()"><br><br>
</form>
        <span id="txt"></span>

Calculate function

function calculate()
    {
        document.getElementById("txt").innerHTML = "";
      var checkBoxes = document.getElementsByName("box");
      for(var i=0; i < checkBoxes.length;i++)
      { 
          if(checkBoxes[i].checked)
          {           
document.getElementById("txt").innerHTML += document.getElementById("lbl_" checkBoxes[i].id).innerHTML
          }
      }

    }

And JsFiddle

Upvotes: 1

Related Questions