简体   繁体   中英

How can I select Price range with Input provided in textbox in jquery?

I have one DropDownList which contains price range as depicted below

  • Up to 50L
  • 50L to 1CR
  • 1CR to 5CR
  • 5CR to 10CR

I also have one textbox which allows users to put input price in textbox. Now I want whenever user provides some valid price money then selected item should be set as per given price. eg if I put 2345 or 543245 or 887 then DropDownList's selected item should be Up to 50L and if I put 8432321 then selected value should be 50L to 1CR . I have tried to put the following code for that but not working as per expectation.

Javascript Code:

jQuery(function ($) {
        debugger;
        $('#txtPrice').on('change', function () {
            var value = parseInt(this.value, 10),
            dd = document.getElementById('ddlPriceRange'),
            index = 0;

            $.each(dd.options, function (i) {
                if (parseInt(this.text, 10) <= value) {
                    index = i;
                }
            });

            dd.selectedIndex = index; // set selected option
        });
    });

.ASPX Code:

<asp:DropDownList ID="ddlPriceRange" runat="server" ClientIDMode="Static"/>
<asp:TextBox ID="txtPrice" runat="server" ClientIDMode="Static"/>

Output which is being produced with above given code is given below

产生的输出像给定的

I have made two minor changes to your logic.

  1. I added the minimum value allowed for given range as the value attribute on the option elements. So instead of comparing the input value with the text of the option, you can compare it to the absolute value.

    <option value="5000000">50L to 1CR</option>

  2. Instead of observing the change event, I added the event on input event so that the dropdown is updated as the user types in the number.

 jQuery(function($) { $('#txtPrice').on('input', function() { var value = parseInt(this.value, 10), dd = document.getElementById('ddlPriceRange'), index = 0; $.each(dd.options, function(i) { if (parseInt(this.value, 10) <= value) { index = i; } }); dd.selectedIndex = index; // set selected option }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="ddlPriceRange"> <option value="0">Up to 50L</option> <option value="5000000">50L to 1CR</option> <option value="10000000">1CR to 5CR</option> <option value="50000000">5CR to 10CR</option> <option value="9007199254740991">Above 10CR</option> </select> <input type="text" id="txtPrice" value="0" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM