KDD
KDD

Reputation: 75

Checkboxes with anchors

I have a ton of check-box's that are linked to anchors. When a check-box is clicked it goes to that anchor which is in the same page. Is there a better way to code this? I have about 50 check-box's so this function is packed with if statements.This is the working code for 2 of them:

<input type="checkbox" id="1" value="1" onclick="return send();"/>
<input type="checkbox" id="2" value="2" onclick="return send();"/>

<script>
function send(){
    if(document.getElementById('1').checked){
        window.location='#buy';
        return false;
    }
    if(document.getElementById('2').checked){
        window.location='#order';
        return false;
    }

//and this function goes on and on and on...
        return true;

    }
    </script>

And then in the page where I want it to go has

<a name="buy"></a>
<a name="order"></a>

Upvotes: 0

Views: 1055

Answers (3)

brenjt
brenjt

Reputation: 16297

If you added the hash into the value of the input like so:

<input type="checkbox" id="2" value="buy" onclick="return send(this);"/>

You could do it like so

<script>
function send(input)
{
    if(input.checked)
    {
        window.location = input.value;
        return true;
    }

    return true;
}
</script>

If that doesn't work you could also switch out the value to use ID or even a custom attribute. Whatever suits your fancy.

Upvotes: 1

Michael Kunst
Michael Kunst

Reputation: 2988

HTML:

<input type="checkbox" id="checkbox1" value="1" data-target="buy" onclick=" send(this)">
<input type="checkbox" id="checkbox2" value="2" data-target="order" onclick="send(this)">

Javscript:

function send(el){
  var target = '#' + el.getAttribute('data-target');
  window.location = target ;
}

Upvotes: 1

beautifulcoder
beautifulcoder

Reputation: 11340

jQuery will save your nerves here:

$('input:checkbox').click(function () {
  windows.location = $(this).attr('value');
});

Simply make sure you change the anchors to match the checkboxes.

Upvotes: 2

Related Questions