Solved

JavaScript - if selected value of dropdownlist is......

Posted on 2014-01-14
9
339 Views
Last Modified: 2014-01-15
Hi Experts,

I'm out of my skillset here so need some help, I have a small JavaScript function which I managed to cobble- together from examples found on the web:

<script type="text/javascript" language="javascript">
        function TryParseInt(str, defaultValue) {
            var retValue = defaultValue;
            if (str != null) {
                if (str.length > 0) {
                    if (!isNaN(str)) {
                        retValue = parseInt(str);
                    }
                }
            } return retValue;
        }

        function TryParseDecimal(str, defaultValue) {
            var retValue = defaultValue;
            if (str != null) {
                if (str.length > 0) {
                    if (!isNaN(str)) {
                        retValue = parseFloat(str);
                    }
                }
            } return retValue;
        }

        function VATcalc() {
           
            var qty = document.getElementById('<%=txtQuantity1.ClientID%>');
            var uc = document.getElementById('<%=txtUnitCost.ClientID%>');
            var rate = document.getElementById('<%=txtVATRate.ClientID%>');

            document.getElementById('<%=txtNetTotal.ClientID%>').value = TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0);
            document.getElementById('<%=txtVAT.ClientID%>').value = (TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
            document.getElementById('<%=txtTotal.ClientID%>').value = ((TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0))) + (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
        }

    </script>

Open in new window


As you will see, I am using it to autopopulate some text boxes - it's calculating the VAT and gross based on net, VAT-rate and quantity. Works fine, very happy.

However due to an unforseen change I would now like to be able to add an if statement which looks at the value selected from a dropdownlist and based on that performs an alternative version of the function above. I can work out how to write the new function what I'm not sure how to do is say if dropdownlist value is xxxx. Is this straightforward ?? My alternative would be to add a checkbox and say if checked, but again I'm not sure how to write that either!

This is the dropdown:
<asp:DropDownList ID="DDLNominal" runat="server" DataSourceID="NominalTable" DataTextField="account_title"
                                            DataValueField="nominal">
                                        </asp:DropDownList>

Open in new window

The datasource is a SQL select.

Many thanks in advance.
0
Comment
Question by:forsters
  • 6
  • 3
9 Comments
 
LVL 44

Assisted Solution

by:Rainer Jeschor
Rainer Jeschor earned 500 total points
ID: 39778968
Hi,
should be pretty straight forward like:
var ddList = document.getElementById('<%=DDLNominal.ClientID%>');
var selectedValue= ddList .options[ddList .selectedIndex].value;

Open in new window


HTH
Rainer
0
 

Author Comment

by:forsters
ID: 39778988
Hi Rainer,

Oh great thank you, (obvious when you know how) I will give that a try now...
0
 

Author Comment

by:forsters
ID: 39779016
Hmm, I'm getting an error:
Unable to get value of the property 'options': object is null or undefined

any ideas?
0
 

Author Comment

by:forsters
ID: 39779036
Ah actually I think thats a timing thing, need a if (!Page.IsPostBack) equivalent...the DDL won't be populated at pageload, hmm in fact it's in a panel which only appears after a postback so...need a way of calling my JavaScript on the ddlSelectedItem Change maybe?
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 44

Expert Comment

by:Rainer Jeschor
ID: 39779060
Hi,
hm - its hard for me to understand the current logic without seeing/knowing your server side code.

And I think there are some typos in my code(blank spaces).

At the moment when you want to call your client side VATCalc function, the DDL is not yet existing / filled?
Perhaps you might want to check if the options exist first - if not run a default calculation ...

var ddList = document.getElementById('<%=DDLNominal.ClientID%>');
var selectedValue;
if (typeof ddList.options === undefined || null === ddList.options) {
  selectedValue = "XXX";
} else {
 selectedValue = ddList.options[ddList.selectedIndex].value;
}

Open in new window

0
 

Author Comment

by:forsters
ID: 39779110
Hi,

Thanks for this, the JavaScript function is part of an aspx page using c# for code behind, but I have the JavaScript code just in the head of my page. But the page contains numerous panels and update panels so on firstload none of the controls referred to in the JavaScript function are visible, they are all in the second panel which is only visible after a button_click event on the first. All the functionality for the page aside from this one piece of JavaScript is built in asp.net AJAX & C#.

See below:

 
<!------------  FIRST SCREEN STARTS HERE - SELECT SUPPLIER & SAVE ------------>
            <asp:Panel ID="PanelNewOrder" runat="server">
                <asp:PlaceHolder ID="holder1" Visible="true" runat="server">
                    <h2>Create New Order</h2>
                    <table>
                        <tr>
                            <td>Select Supplier:<br />
                                <br />
                            </td>
                            <td>
                                <asp:DropDownList ID="DDLSupplier" runat="server" DataSourceID="Supplier" DataTextField="SupplierName"
                                    DataValueField="SupplierID">
                                </asp:DropDownList>
                                <asp:SqlDataSource ID="Supplier" runat="server" ConnectionString="<%$ ConnectionStrings:Supplier %>"
                                    SelectCommand="SELECT * FROM [SupplierDetails] Order By SupplierName"></asp:SqlDataSource>
                                <br />
                                <br />
                            </td>
                        </tr>
                        <tr>
                            <td>Invoice No:<br />
                                <br />
                            </td>
                            <td>
                                <asp:TextBox ID="TxtInvoiceNo" runat="server" Width="300" />
                                <br />
                                <br />
                            </td>
                        </tr>
                        <tr>
                            <td>Invoice Date:<br />
                                <br />
                            </td>
                            <td>
                                <asp:TextBox ID="TxtInvoiceDate" runat="server" Width="300" />
                                <br />
                                <br />
                            </td>
                        </tr>
                        <tr>
                            <td>Invoice Total:<br />
                                <br />
                            </td>
                            <td>
                                <asp:TextBox ID="TxtInvoiceTotal" runat="server" Width="300" />
                                <br />
                                <br />
                            </td>
                        </tr>
                    </table>
                    <asp:Button ID="ButtonSave" runat="server" Text=" Save" OnClick="ButtonSave_Click" />
                </asp:PlaceHolder>
            </asp:Panel>
            <!----------------------  FIRST SCREEN CLOSES - HOLDER1 HIDDEN ----------------->
            <!-----------  SECOND SCREEN STARTS HERE - DETAILS VIEW OF NEWLY CREATED ORDER ---------->
            <!----------------------------- THE DETAILS VIEW - ORDER SUMMARY ------------------------>
            <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                <ContentTemplate>
                    <asp:PlaceHolder ID="holder2" Visible="false" runat="server">
                        <h2>New Order</h2>
                        <asp:DetailsView ID="DVOrder" DataSourceID="OrderView" runat="server" Height="50px"
                            Width="525px" AutoGenerateRows="false" GridLines="None">
                            <Fields>
                                <asp:BoundField DataField="OrderID" HeaderText="Order Ref" ReadOnly="true" />
                                <asp:BoundField DataField="SupplierName" HeaderText="Supplier" ReadOnly="true" />
                                <asp:BoundField DataField="InvoiceNo" HeaderText="Invoice No." ReadOnly="true" />
                                <asp:BoundField DataField="InvoiceDate" HeaderText="Invoice Date" ReadOnly="true" />
                                <asp:BoundField DataField="OrderDate" HeaderText="Date Created" DataFormatString="{0:f}" HtmlEncode="false" ReadOnly="true" />
                                <asp:BoundField DataField="Creator" HeaderText="Created By" ReadOnly="true" />
                                <asp:BoundField DataField="InvoiceTotal" HeaderText="Invoice Total" ReadOnly="true" />
                            </Fields>
                        </asp:DetailsView>
                        <asp:Label ID="LabelTest" runat="server" />
                        <asp:Button ID="ButtonEdit" runat="server" Text="Edit" OnClick="ButtonEdit_Click" />
                        <asp:Button ID="ButtonDelete" runat="server" Text="Delete" OnClick="ButtonDelete_Click" />
                    </asp:PlaceHolder>
                </ContentTemplate>
            </asp:UpdatePanel>
            <!------------------------------THE GRID - SHOWS ITEMS ON ORDER------------------------->
            <!----------------------------INCLUDES FOOTER TEMPLATE TO ADD ITEMS--------------------->
            <asp:Panel ID="panel3" runat="server" Visible="false">
                <asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <div id="formbg">
                            <table style="padding-top: -30px;">
                                <tr>
                                    <td>
                                        <h2>Add items to this order below:
                                        </h2>
                                    </td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td>Item Description:
                                    </td>
                                    <td>
                                        <asp:TextBox ID="txtItemDescription" runat="server" Width="300px"></asp:TextBox>
                                    </td>
                                    <br />
                                    <br />
                                </tr>
                                <tr>
                                    <td>Category:
                                    </td>
                                    <td>
                                        <asp:DropDownList ID="DDLCategory" runat="server" DataSourceID="Category" DataTextField="Category"
                                            DataValueField="CategoryID">
                                        </asp:DropDownList>
                                    </td>
                                </tr>
                                <asp:SqlDataSource ID="Category" runat="server" ConnectionString="<%$ ConnectionStrings:Purchase %>"
                                    SelectCommand="SELECT * FROM [ItemTypes]"></asp:SqlDataSource>
                                <br />
                                <br />
                                <tr>
                                    <td>Nominal:
                                    </td>
                                    <td>
                                        <asp:DropDownList ID="DDLNominal" runat="server" DataSourceID="NominalTable" DataTextField="account_title"
                                            DataValueField="nominal">
                                        </asp:DropDownList>
                                        <asp:SqlDataSource ID="Nominal" runat="server" ConnectionString="<%$ ConnectionStrings:Nominals %>"
                                            SelectCommand="GetITNominals" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
                                        <br />
                                        <br />
                                        <asp:SqlDataSource ID="NominalTable" runat="server" ConnectionString="<%$ ConnectionStrings:Purchase %>"
                                            SelectCommand="Select * FROM nominals"></asp:SqlDataSource>
                                    </td>
                                </tr>

                                <tr>
                                    <td>Unit cost:
                                    </td>
                                    <td>
                                        <asp:TextBox ID="txtUnitCost" onchange="VATcalc();" runat="server" Width="200px"></asp:TextBox><br />
                                        <br />
                                    </td>
                                </tr>
                                <tr>
                                    <td>Quantity - Set to 1 for Fixed Assets:
                                    </td>
                                    <td>
                                        <asp:TextBox ID="txtQuantity1" onchange="VATcalc();" runat="server" Width="40px"></asp:TextBox><br />
                                        <br />
                                    </td>
                                </tr>
                                <tr>
                                    <td>Net total (per item):
                                    </td>
                                    <td>
                                        <asp:TextBox ID="txtNetTotal" runat="server" Width="200px"></asp:TextBox><br />
                                        <br />
                                    </td>
                                </tr>
                                <tr>
                                    <td>VAT Rate:
                                    </td>
                                    <td>
                                        <asp:TextBox ID="txtVATRate" onchange="VATcalc();" runat="server" Text="0.2" TextMode="SingleLine" ReadOnly="false" Width="200px"></asp:TextBox><br />
                                        <br />
                                    </td>
                                </tr>
                                <tr>
                                    <td>VAT (per item):
                                    </td>
                                    <td>
                                        <asp:TextBox ID="txtVAT" runat="server" Width="200px"></asp:TextBox><br />
                                        <br />
                                    </td>
                                </tr>
                                <tr>
                                    <td>Total (per item):
                                    </td>
                                    <td>
                                        <asp:TextBox ID="txtTotal" runat="server" Width="200px"></asp:TextBox><br />
                                        <br />
                                    </td>
                                </tr>
                                <tr>
                                    <td>Quantity - always set to actual quantity:
                                    </td>
                                    <td>
                                        <asp:TextBox ID="txtQuantity" runat="server" Width="40px"></asp:TextBox><br />
                                        <br />
                                    </td>
                                </tr>
                            </table>
                            <asp:Button ID="ButtonSaveItem" runat="server" Text="Add" OnClick="ButtonSaveItem_Click" />
                            <asp:Button ID="ButtonSaveItems" runat="server" Text="Add Fixed Asset" OnClick="ButtonSaveItems_Click" />
                        </div>
                        <br />

Open in new window


In the code behind Pahe_Load event the following exists:

 
if (Request.QueryString["OrderID"] != null)
        {
            Session["OrderID"] = Request.QueryString["OrderID"];
            holder1.Visible = false;
            holder2.Visible = true;
            panel3.Visible = true;
            holder4.Visible = true;
        }

Open in new window



Hope that makes sense, I can understand your suggestion above but I can't set a default in this case.
0
 

Author Comment

by:forsters
ID: 39779225
Ahhh Sorry, newbie mistake I had added the code you gave me originally outside of my main JS function - so of course it runs on pageload not when called.

Hmm so I don't get an error now but I must have got something wrong as the calc no longer seems to respond, can you tell me if I have the right syntax...

 <script type="text/javascript" language="javascript">
        function TryParseInt(str, defaultValue) {
            var retValue = defaultValue;
            if (str != null) {
                if (str.length > 0) {
                    if (!isNaN(str)) {
                        retValue = parseInt(str);
                    }
                }
            } return retValue;
        }

        function TryParseDecimal(str, defaultValue) {
            var retValue = defaultValue;
            if (str != null) {
                if (str.length > 0) {
                    if (!isNaN(str)) {
                        retValue = parseFloat(str);
                    }
                }
            } return retValue;
        }

        function VATcalc() {
        var ddList = document.getElementById('<%=DDLNominal.ClientID%>');
        var selectedValue = ddList.options[ddList.selectedIndex].value;

           if (selectedValue = 84001.0001) {
                var qty = 1;
                var uc = document.getElementById('<%=txtUnitCost.ClientID%>');
                var rate = document.getElementById('<%=txtVATRate.ClientID%>');

                document.getElementById('<%=txtNetTotal.ClientID%>').value = TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0);
                document.getElementById('<%=txtVAT.ClientID%>').value = (TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
                document.getElementById('<%=txtTotal.ClientID%>').value = ((TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0))) + (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
            }
else {

            function VATcalc() {

     var qty = document.getElementById('<%=txtQuantity1.ClientID%>');
     var uc = document.getElementById('<%=txtUnitCost.ClientID%>');
     var rate = document.getElementById('<%=txtVATRate.ClientID%>');

     document.getElementById('<%=txtNetTotal.ClientID%>').value = TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0);
     document.getElementById('<%=txtVAT.ClientID%>').value = (TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
     document.getElementById('<%=txtTotal.ClientID%>').value = ((TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0))) + (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
 }

        
        }


            }

    </script>

Open in new window

0
 
LVL 44

Accepted Solution

by:
Rainer Jeschor earned 500 total points
ID: 39779352
Hi,
there are a couple of typos in the script:
First you assigen a value to the variable (=) instead of checking it (==), second the value will probably be of type string.
Second you should/cannot have a function keyword inside the else case.

Adjusted function:
function VATcalc() {
	var ddList = document.getElementById('<%=DDLNominal.ClientID%>');
	var selectedValue = ddList.options[ddList.selectedIndex].value;

	if (selectedValue == '84001.0001') {
		var qty = 1;
		var uc = document.getElementById('<%=txtUnitCost.ClientID%>');
		var rate = document.getElementById('<%=txtVATRate.ClientID%>');

		document.getElementById('<%=txtNetTotal.ClientID%>').value = TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0);
		document.getElementById('<%=txtVAT.ClientID%>').value = (TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
		document.getElementById('<%=txtTotal.ClientID%>').value = ((TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0))) + (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
	}
	else {
		var qty = document.getElementById('<%=txtQuantity1.ClientID%>');
		var uc = document.getElementById('<%=txtUnitCost.ClientID%>');
		var rate = document.getElementById('<%=txtVATRate.ClientID%>');

		document.getElementById('<%=txtNetTotal.ClientID%>').value = TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0);
		document.getElementById('<%=txtVAT.ClientID%>').value = (TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
		document.getElementById('<%=txtTotal.ClientID%>').value = ((TryParseDecimal(rate.value, 0.2) * (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0))) + (TryParseInt(qty.value, 1) * TryParseDecimal(uc.value, 0)));
	}
 }

Open in new window


HTH
Rainer
0
 

Author Comment

by:forsters
ID: 39779433
Ahh yes thats perfect, thank you very much.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to count occurrences of each item in an array.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now