Dynamically Change Multiple Hidden Form Fields

2019-08-27 04:11发布

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.

2条回答
Melony?
2楼-- · 2019-08-27 04:55
$("select").on("change", function() {
    $("form").append( /* <input type='hidden'> tag here */ );
});
查看更多
乱世女痞
3楼-- · 2019-08-27 04:56

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);
});
查看更多
登录 后发表回答