0

I'm somewhat new to jQuery. I'm pretty sure this is possible, but I'm not quote certain how to code this.

What I'm looking to do is to use a dropdown with selections that represent ranges (e.g. if someone were searching for bedrooms, the dropdown selctions would look like "0-2", "3-5", "6+"). Then when someone chooses a selection, two hidden fields would by dynamically filled. One field with the minimum of the range, and the other field with the maximum of the range.

Here is an example of how I'm trying to structure this:

    <select id="bedrooms" class="dropdown">
      <option>Bedrooms</option>
      <option></option>
      <option value="1">0-2</option>
      <option value="2">3-5</option>
      <option value="3">6+</option>
    </select>

    <input type="hidden" name="bedrooms-from" value=''>
    <input type="hidden" name="bedrooms-to" value=''>

I suppose the values of each option could change, I wasn't sure what the best way to approach that would be.

Kurt
  • 1
  • 1

2 Answers2

1

I haven't actually run this, but I think it should work:

$("#bedrooms").change(function ()
{
    // Get a local reference to the JQuery-wrapped select and hidden field elements:
    var sel = $(this);
    var minValInput = $("input[name='bedrooms-from']");
    var maxValInput = $("input[name='bedrooms-to']");

    // Blank the values of the two hidden fields if appropriate:
    if (sel.val() == "") {
        minValInput.val("");
        maxValInput.val("");
        return; 
    }

    // Get the selected option:
    var opt = sel.children("[value='" + sel.val() + "']:first");

    // Get the text of the selected option and split it on anything other than 0-9:
    var values = opt.attr("text").split(/[^0-9]+/);

    // Set the values to bedroom-from and bedroom-to:
    minValInput.val(values[0]);
    maxValInput.val((values[1] != "") ? values[1] : 99999999);
});
Steve Wilkes
  • 7,085
  • 3
  • 29
  • 32
  • This is along the lines of what I was thinking. Nice suggestion. I think the OP could consider use better values than "1,2,3" in the options though which could aid in the splitting perhaps? Personal preference of course, I just prefer using value over text for these sorts of things. – WesleyJohnson Jun 07 '11 at 21:47
  • Thanks :) Yeah, I think it would be simpler to have the ranges in the option values, too. – Steve Wilkes Jun 08 '11 at 05:14
0
$("select").on("change", function() {
    $("form").append( /* <input type='hidden'> tag here */ );
});
Ben Roux
  • 7,308
  • 1
  • 18
  • 21
  • This may result in multiple values being transmitted to the server -- imagine the control this changed multiple times. This may or may not be desired. It also doesn't show hot to extract the values. ([0,2] from "0-2", [6,?] from "6+") –  Jun 07 '11 at 21:06
  • Good call... it would need an array that stores [select.id] => hasBeenSet and then do a .value() if so – Ben Roux Jun 07 '11 at 21:15