Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

javascript - Dynamically Change Multiple Hidden Form Fields

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...