locked
when select dropdownlist item this returns nan value in jquery? RRS feed

  • Question

  • User-1026236167 posted

    hello in my script i want to add dropdownlist1 and i get   textbox3 returns nan value when select item from dropdownlist1 

    here is script

    <script>
    $(document).ready(function () {
    $("#Textbox1, #Textbox2").keyup(function () {
    $("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val());
    });

    $('#<%=DropDownList2.ClientID %>').change(function () {
    if ($(this).val() == "inclusive") {
    parseFloat($("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val()));
    // var main = parseFloat($('#Textbox3').val());
    // var disc = parseFloat($('#Textbox4').val());
    //var dec = (disc / 100).toFixed(2);
    //var mult = main * dec;
    //var discont = main + mult;
    //$('#Textbox3').val(discont);
    }
    else if ($(this).val() == "Exclusive") {
    parseFloat($("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val()));
    var main = parseFloat($('#Textbox3').val());
    var disc = parseFloat($('#DropDownList1').val(18));
    var dec = (disc / 100).toFixed(2);
    var mult = main * dec;
    var discont = main + mult;

    $('#Textbox3').val(discont);
    }
    });

    });
    </script>

    Tuesday, September 8, 2020 12:31 PM

All replies

  • User2103319870 posted

    prabhjot1313

    i get   textbox3 returns nan value when select item from dropdownlist1 

    Looks like You were calling parseFloat at some places which is not needed. Try with below code

    <script>
    		$(document).ready(function () {
    			$("#Textbox1, #Textbox2").keyup(function () {
    				$("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val());
    			});
    
    			$('#<%=DropDownList2.ClientID %>').change(function () {
    				if ($(this).val() == "inclusive") {
    					//Removed parsefloat
    					$("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val());
    				}
    				else if ($(this).val() == "Exclusive") {
    					//Removed parsefloat
    					$("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val());
    
    					var main = parseFloat($('#Textbox3').val());
    					//Removed parsefloat
    					//assigned the value 18 to dropdownlist
    					$('#DropDownList1').val(18);
    					//Get the selected item from Dropdownlist
    					var disc = $("#DropDownList1").children("option:selected").val();
    					var dec = (disc / 100).toFixed(2);
    					var mult = main * dec;
    					var discont = main + mult;
    
    					$('#Textbox3').val(discont);
    				}
    			});
    
    		});
    	</script>
    Tuesday, September 8, 2020 1:22 PM
  • User-474980206 posted

    When you set a .val() like below

       var disc = parseFloat($('#DropDownList1').val(18));

    val(18) returns a jquery object not the value, so parseFloat return nan.

    Tuesday, September 8, 2020 2:18 PM
  • User-1026236167 posted
    sir this is the whole code as you provide answer when i apply this on my side this returns nan

    execute them on his behalf

    aspx


    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm9.aspx.cs" Inherits="Store.WebForm9" %> <asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server"> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="contentbody" runat="server"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script> $(document).ready(function () { $("#Textbox1, #Textbox2").keyup(function () { $("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val()); }); $('#<%=DropDownList2.ClientID %>').change(function () { if ($(this).val() == "inclusive") { //Removed parsefloat $("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val()); } else if ($(this).val() == "Exclusive") { //Removed parsefloat $("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val()); var main = parseFloat($('#Textbox3').val()); //Removed parsefloat //assigned the value 18 to dropdownlist $('#DropDownList1').val(18); $('#DropDownList1').val(3); //Get the selected item from Dropdownlist var disc = $("#DropDownList1").children("option:selected").val(); var dec = (disc / 100).toFixed(2); var mult = main * dec; var discont = main + mult; $('#Textbox3').val(discont); } }); }); </script> <div class="row" style="margin-left:10px;"> <div class="col-sm-3"> <span style="color:black"><b>select party</b></span><br /> <span style="color:black"> <asp:dropdownlist ID ="dd2" runat="server" Width="240px" Height="30" DataTextField="party_name" OnSelectedIndexChanged="dd2_SelectedIndexChanged" AutoPostBack="true" DataValueField="gst_type"/></span><br /> </div> <div class="col-sm-3"> <span style="color:black;"><b> gst type</b></span><br /> <span style="color:black; "><asp:textbox ID ="TB_name" runat="server" Width="240px" /></span><br /> </div> </div> <div class="row" style="margin-left:10px;"> <div class="col-sm-3"> <span style="color:black"><b>select product</b></span><br /> <span style="color:black"> <asp:dropdownlist ID ="dd1" runat="server" Width="240px" Height="30" DataTextField="product_name" OnSelectedIndexChanged="Dropdownlist1_SelectedIndexChanged" AutoPostBack="true" DataValueField="uom"/></span><br /> </div> <div class="col-sm-3"> <span style="color:black"><b>Uom</b></span><br /> <span style="color:black"> <asp:dropdownlist ID ="dd3" runat="server" Width="240px" Height="30" DataTextField="uom" DataValueField="mrp"/></span><br /> </div> <div class="col-sm-2"> <span style="color:black;"><b> Qty</b></span><br /> <span style="color:black; "> <asp:textbox ID ="Textbox2" runat="server" Width="150px" ClientIDMode="Static" /></span><br /> </div> <div class="col-sm-2"> <span style="color:black;"><b> Price</b></span><br /> <span style="color:black; "> <asp:textbox ID ="Textbox1" runat="server" Width="150px" ClientIDMode="Static" /></span><br /> </div> <div class="col-sm-2"> <asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" onselectedindexchanged="ddl_SelectedIndexChanged" Width="200px"> <asp:ListItem Value="0" Selected="false">Select</asp:ListItem> <asp:ListItem>percentage wise</asp:ListItem> <asp:ListItem>amount wise</asp:ListItem> </asp:DropDownList> </div> <div class="col-sm-2"> <span style="color:black;"><b> Disc.Value</b></span><br /> <span style="color:black; "> <asp:textbox ID ="Textbox4" Text="0" runat="server" Width="150px" ClientIDMode="Static" /></span><br /> </div> <div class="col-sm-2"> <span style="color:black;"><b> dummy</b></span><br /> <span style="color:black; "> <asp:textbox ID ="Textbox5" runat="server" Width="150px" /></span><br /> </div> </div> <div class="row" style="margin-left:10px;"> <div class="col-sm-3"> <span style="color:black;"><b> Final Amt</b></span><br /> <span style="color:black; "> <asp:textbox ID ="Textbox3" runat="server" Width="240px" ClientIDMode="Static" /></span><br /> <%-- <input type="text" class="btn btn-primary" id="Textbox3" style="width:180px; height:35px; "/>--%> </div> <div class="col-sm-2"> <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" Width="200px"> <asp:ListItem Value="0" Selected="false">Select</asp:ListItem> <asp:ListItem>inclusive</asp:ListItem> <asp:ListItem>Exclusive</asp:ListItem> </asp:DropDownList> </div> <div class="col-sm-2"> <asp:DropDownList ID="DropDownList1" runat="server" Width="200px" > <asp:ListItem Value="0" Selected="false">Select</asp:ListItem> <asp:ListItem>12</asp:ListItem> <asp:ListItem>18</asp:ListItem> </asp:DropDownList> </div> <div class="col-sm-3"> <%-- <span style="color:black;"><b> Add Product</b></span><br />--%> <br /> <%-- <span style="color:black; "> <asp:textbox ID ="Textbox3" runat="server" Width="240px" ClientIDMode="Static" /></span><br />--%> <%-- <input name="hlo_1" type="text" class="btn btn-primary" id="Textbox7" style="width:90px; height:35px; "/>--%> <asp:Button runat="server" Width="60px" Height="40px" OnClick="AddProduct_Click" Text="Add" class="btn btn-primary"></asp:Button> </div> <%-- <asp:Button ID="AddProduct" runat="server" Style="color: White" Text="Add Product" OnClick="AddProduct_Click" BackColor="#999966" /> --%> <%-- <input type="number" id="cBalance" value=""> <br><br> %      <input type="number" id="chDiscount"> <br><br> Result <input type="number" id="result">--%> </div> <asp:ScriptManager runat="server"></asp:ScriptManager> <div style="margin-left:10px;margin-top:10px"> <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:TemplateField> <ItemTemplate> <div > <table> <tr style="background-color:blue; color:white"> <th>Sr.No</th> <th >Product Information</th> <th>Discount Information</th> <th>Tax Information</th><th>Tax Amount</th><th>Final Amount</th> </tr> <tr> <td> <asp:Label runat="server" Text="Author name:"></asp:Label><asp:Label ID="Label30" runat="server" Text='<%# Eval("AuthorName") %>'></asp:Label><br /> <asp:Label runat="server" Text="Book name:"></asp:Label><asp:Label ID="Label1" runat="server" Text='<%# Eval("book_name") %>'></asp:Label><br /> <asp:Label runat="server" Text="Book type:"></asp:Label><asp:Label ID="Label4" runat="server" Text='<%# Eval("book_type") %>'></asp:Label><br /> <asp:Label runat="server" Text="name:"></asp:Label><asp:Label ID="Label3" runat="server" Text='<%# Eval("publisher") %>'></asp:Label> </td> </tr> </table> </ItemTemplate> </asp:TemplateField> </Columns> <EditRowStyle BackColor="#2461BF" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#EFF3FB" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#F5F7FB" /> <SortedAscendingHeaderStyle BackColor="#6D95E1" /> <SortedDescendingCellStyle BackColor="#E9EBEF" /> <SortedDescendingHeaderStyle BackColor="#4870BE" /> </asp:GridView> </div> </asp:Content> cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace Store { public partial class WebForm9 : System.Web.UI.Page { SqlCommand cmd = new SqlCommand(); SqlConnection con = new SqlConnection(); string connection = System.Configuration.ConfigurationManager.AppSettings["con"].ToString(); public void EstablishConnection(string storeprocedure) { con.ConnectionString = connection; cmd.Connection = con; cmd.Connection.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = storeprocedure; } public void CloseConnection() { cmd.Connection.Close(); cmd.Connection.Dispose(); con.Close(); } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { AddDefaultFirstRecord(); TB_name.Enabled = false; dd3.Enabled = false; dropdown5(); dropdown7(); dropdown6(); } } public void dropdown5() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbl_products ", connection); adp.SelectCommand.CommandType = CommandType.Text; DataTable DT = new DataTable(); adp.Fill(DT); dd1.DataSource = DT; dd1.DataBind(); dd1.Items.Insert(0, new ListItem() { Text = "Select", Value = "0" }); } public void dropdown7() { //SqlDataAdapter adp = new SqlDataAdapter("select * from tbl_products ", connection); //adp.SelectCommand.CommandType = CommandType.Text; //DataTable DT = new DataTable(); //adp.Fill(DT); //dd3.DataSource = DT; //dd3.DataBind(); dd3.Items.Insert(0, new ListItem() { Text = "Select", Value = "0" }); } public void dropdown6() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbl_party ", connection); adp.SelectCommand.CommandType = CommandType.Text; DataTable DT = new DataTable(); adp.Fill(DT); dd2.DataSource = DT; dd2.DataBind(); dd2.Items.Insert(0, new ListItem() { Text = "Select", Value = "0" }); } protected void AddProduct_Click(object sender, EventArgs e) { AddNewRecordRowToGrid(); } private void AddDefaultFirstRecord() { // creating dataTable DataTable dt = new DataTable(); DataRow dr; dt.TableName = "AuthorBooks"; dt.Columns.Add(new DataColumn("AuthorName", typeof(string))); dt.Columns.Add(new DataColumn("book_name", typeof(string))); dt.Columns.Add(new DataColumn("book_type", typeof(string))); dt.Columns.Add(new DataColumn("publisher", typeof(string))); dr = dt.NewRow(); dt.Rows.Add(dr); //saving databale into viewstate ViewState["AuthorBooks"] = dt; //bind Gridview GridView1.DataSource = dt; GridView1.DataBind(); } private void AddNewRecordRowToGrid() { // check view state is not null if (ViewState["AuthorBooks"] != null) { //get datatable from view state DataTable dtCurrentTable = (DataTable)ViewState["AuthorBooks"]; DataRow drCurrentRow = null; if (dtCurrentTable.Rows.Count > 0) { for (int i = 1; i <= dtCurrentTable.Rows.Count; i++) { //add each row into data table drCurrentRow = dtCurrentTable.NewRow(); drCurrentRow["AuthorName"] = Textbox1.Text; drCurrentRow["book_name"] = Textbox4.Text; drCurrentRow["book_type"] = Textbox5.Text; drCurrentRow["publisher"] = Textbox3.Text; } //Remove initial blank row if (dtCurrentTable.Rows[0][0].ToString() == "") { dtCurrentTable.Rows[0].Delete(); dtCurrentTable.AcceptChanges(); } //add created Rows into dataTable dtCurrentTable.Rows.Add(drCurrentRow); //Save Data table into view state after creating each row ViewState["AuthorBooks"] = dtCurrentTable; //Bind Gridview with latest Row GridView1.DataSource = dtCurrentTable; GridView1.DataBind(); } } } protected void BT_Submit_Click(object sender, EventArgs e) { } protected void dd2_SelectedIndexChanged(object sender, EventArgs e) { TB_name.Enabled = false; TB_name.Text = dd2.SelectedValue.ToString(); } protected void Dropdownlist1_SelectedIndexChanged(object sender, EventArgs e) { //dd3.Text = dd1.SelectedValue.ToString(); // Textbox1.Text = dd1.SelectedValue.ToString(); DropDownList ddl = (DropDownList)sender; //GridViewRow row = (GridViewRow)ddl.NamingContainer; //TextBox txt = (TextBox)row.FindControl("txt1"); //TextBox txt2 = (TextBox)row.FindControl("txt2"); // TextBox txt3 = (TextBox)row.FindControl("txt3"); string strquery; String str = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString; SqlConnection con = new SqlConnection(str); con.Open(); strquery = "select uom, mrp from tbl_products where product_name='" + ddl.SelectedItem.Text + "'"; SqlCommand cmd = new SqlCommand(strquery, con); SqlDataReader reader = cmd.ExecuteReader(); List<object> chartData = new List<object>(); if (reader.HasRows) { while (reader.Read()) { //chartData.Add(reader["mrp"].ToString()); dd3.Items.Add(new ListItem(reader["uom"].ToString(), reader["uom"].ToString())); dd3.ClearSelection(); dd3.Items.FindByText(reader["uom"].ToString()).Selected = true; // dd3.Text = reader["uom"].ToString(); Textbox1.Text = reader["mrp"].ToString(); } } } protected void ddl_SelectedIndexChanged(object sender, EventArgs e) { } protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) { } } }

    Wednesday, September 9, 2020 6:46 AM
  • User-1330468790 posted

    Hi prabhjot1313,

     

    Now I think a better way to solve your problem is that we should firstly specify the problem.

    The problem from your description is that you can not assign the value '18' to the select element (Drop down list), correct?

     

    If so, I think you need to change the line of code from

     $('#DropDownList1').val(18);

    to 

     $('#DropDownList1').val('18');

     

    The reason is that jQuery's documentation states:

    [jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.

    This behavior is in jQuery versions 1.2 and above.

    However, in the given select element, I can only see that you have assigned two options '18' and '12', not 18 in number. Therefore, when you assign the value 18 to the select, it cannot match this value hence fail.

     

    I suggest you provide us with a simple demo which could explain the problem.

    This would be much helpful for us targeting and solving the problem easier and faster.

     

    Thank you for understanding.

    Best regards,

    Sean

    Friday, September 11, 2020 6:47 AM
  • User-1026236167 posted

    sir when i apply this code '18' the result is not calculate but nan is not occur so solve them

    <script>
              $(document).ready(function () {
                  $("#Textbox1, #Textbox2").keyup(function () {
                      $("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val());
               
                  });

                  $('#<%=DropDownList1.ClientID %>').change(function () {
                     if ($(this).val() == "12") {
                         parseFloat($("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val()));
                         var main = parseFloat($('#Textbox3').val());
                         var disc = parseFloat($('#Textbox4').val());
                         var dec = (disc / 100).toFixed(2);
                         var mult = main * dec;
                         var discont = main + mult;
                         $('#Textbox3').val(discont);
                
                     }
                     else if ($(this).val() == "18") {
                         parseFloat($("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val()));
                         var main = parseFloat($('#Textbox3').val());
                         var disc = parseFloat($('#Textbox4').val());
                         var dec = (disc / 100).toFixed(2);
                         var mult = main * dec;
                         var discont = main + mult;

                         $('#Textbox3').val(discont);
                     }
                 });

             });
          </script>

    Monday, September 14, 2020 7:25 AM
  • User-1330468790 posted

    Hi prahjot1313,

     

    What do you mean "the result is not calculate"?

     

    I added DropDownList1.ClientID change event handler directly to my above codes and the result is that the codes are working though the two if conditions return the same result.

     

    I suggest you could set print console points in the codes and press F12 to open the dev tools in browsers to check whether the functions are called or not.

     

    For example,

    $('#<%=DropDownList1.ClientID %>').change(function () {
                    console.log($(this).val());
                    if ($(this).val() == "12") {
                        // If this if condition met, 'DDL1 is 12' will be printed. Below codes are in the same check principle.
                        console.log("DDL1 is 12");
                        $("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val());
                        var main = parseFloat($('#Textbox3').val());
                        var disc = parseFloat($('#Textbox4').val());
                        var dec = (disc / 100).toFixed(2);
                        var mult = main * dec;
                        var discont = main + mult;
    
                        // Print values
                        console.log("main value: " + main);
                        console.log("disc value: "+disc);
                        console.log("dec value: " + dec);
                        console.log("mult value: " + mult);
                        console.log("discont value: " + discont);
    
                        $('#Textbox3').val(discont);
    
                    }
                    else if ($(this).val() == "18") {
                        console.log("DDL1 is 18");
                        $("#Textbox3").val($("#Textbox1").val() * $("#Textbox2").val());
                        var main = parseFloat($('#Textbox3').val());
                        var disc = parseFloat($('#Textbox4').val());
                        var dec = (disc / 100).toFixed(2);
                        var mult = main * dec;
                        var discont = main + mult;
    
                        console.log("main value: " + main);
                        console.log("disc value: " + disc);
                        console.log("dec value: " + dec);
                        console.log("mult value: " + mult);
                        console.log("discont value: " + discont);
    
    
                        $('#Textbox3').val(discont);
                    }
                });

    Console result in browser (Mine is Chrome):

     

    Obviously, if there are some lines in the console section of the dev-tool of the browser, it means that the functions are working.

    You could still change the console function's position to check any place of the codes.

     

    Best regards,

    Sean

    Wednesday, September 16, 2020 7:27 AM