AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

How to save custom option if "No Results Match" with .select?

I'm still debating whether text_field or select is the more appropriate form helper.

With text_field you can save your custom text.

With select you choose from a list provided.

I want a hybrid where when a user clicks on the field, a drop down menu appears with options, but the user can ignore it and type away his own custom option.

I tried select2 and looked into a variety of jquery plugins provided here, but if you type a custom option it will give back "No results matched" and then you're unable to save it.

What's the best way to create this hybrid? I'm using Ruby on Rails.

Upvotes: 1

Views: 1414

Answers (2)

sadaf2605
sadaf2605

Reputation: 7540

You can simply utilize createSearchChoice option of select2 which will add new choice rather than showing "no results". See it running at jsfiddle

Html:

<input type="hidden" id="tags" style="width: 300px"/>

Javascript:

var lastResults = [];

$("#tags").select2({
    //multiple: true,
    placeholder: "Please enter tags",
    //tokenSeparators: [","],
    ajax: {
        multiple: true,
        url: "/echo/json/",
        dataType: "json",
        type: "POST",
        data: function (term, page) {
            return {
                json: JSON.stringify({results: [{id: "foo", text:"foo"},{id:"bar", text:"bar"}]}),
                q: term
            };
        },
        results: function (data, page) {
            lastResults = data.results;
            return data;
        }
    },
    createSearchChoice: function (term) {
        var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
        return { id: term, text: text };
    },
});

Jsfiddle: http://jsfiddle.net/XQ8Fw/674/

Upvotes: 2

Prakash
Prakash

Reputation: 576

See if this helps out you. It is straightforward and simple.

$('select').change(function() {
  modify();
})

function modify() {
  $('input').val($('select').val());
  output();
}

function output() {
  $('p').text('value: ' + $('input').val());
}

$('input').on('click', function() {
  $(this).select()
}).on('blur', function() {
  output();
})

modify();
select {
  position: absolute;
  width: 160px;
  height: 23px;
  left: 0;
  top: 0;
  border: 0;
}
input {
  position: absolute;
  width: 140px;
  height: 17px;
  left: 0;
  top: 0;
}
p {
  position: relative;
  margin-top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body>
  <select>
    <option selected="selected" value="Wednesday">Wednesday</option>
    <option value="Sunday">Sunday</option>
    <option value="Monday">Monday</option>
    <option value="Tuesday">Tuesday</option>
  </select>
  <input type="text" name="" value="">
  <p>value:</p>
</body>

</html>

Upvotes: 1

Related Questions