Brandrally
Brandrally

Reputation: 849

Javascript If-else

Attempting to do my first bit of Javascript if / else. Basically I would like to display DIVs according to the number selected from the Radio box field. If option 3 is selected, I would like div 1, 2 and 3 to be visible. I am clearly going wrong somewhere. Thoughts / help is very much appreciated.

<script type="text/javascript" >

$(document).ready(function() {

$("input[name$='supplier']").click(function() {

var test = $(this).val();

if (test=1)
{
$("div.hidesupplier").hide();
$("#suppliersourced1").show();
}

else if (test=2)
{
$("div.hidesupplier").hide();
$("#suppliersourced1").show();
$("#suppliersourced2").show();
}

else if (test==3)
{
$("#suppliersourced1").show();
$("#suppliersourced2").show();
$("#suppliersourced3").show();
}

});
});
</script>

Number of Suppliers:
<label><input name="supplier" type="radio" value="1">1.</label> 
<label><input name="supplier" type="radio" value="2">2.</label>
<label><input name="supplier" type="radio" value="3">3.</label>

<div id="suppliersourced1" class="CF hidesupplier" style="display: none;">Supplier One</div>
<div id="suppliersourced2" class="CF hidesupplier" style="display: none;">Supplier Two</div>
<div id="suppliersourced3" class="CF hidesupplier" style="display: none;">Supplier Three</div>

Upvotes: 1

Views: 579

Answers (2)

techfoobar
techfoobar

Reputation: 66693

A cleaner and faster version would be:

$("input[name$='supplier']").click(function() {
    var test = $(this).val();
    $("div.hidesupplier").each(function() {

        // get the id of the current supplier, eg: "suppliersourced1"   
        var myID = $(this).attr('id');

        // get the last character and convert it to a number
        myID = parseInt(myID.substring(myID.length()-1, 1), 10);

        // show all with id less than or eq to test 
        // hide all with id more than test
        if(myID <= test) $(this).show(); else $(this).hide();
    });
});

Cleaner because you have almost no repeating code. Faster because you dont blindly hide everything and show specific elements, but only hide and show appropriate elements in one go. Faster also because there is lesser bytes of JS code to be transferred, parsed and executed.

Upvotes: 5

AnthonyM
AnthonyM

Reputation: 1145

You have = instead of == in your first 2 conditions.

Upvotes: 4

Related Questions