Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone-forms with conditional fields

First of all thanks to the guys of backbone-forms who made a tool which perfectly integrates in the backbone.js framework.

I'm using backbone.js with the backbone-forms plugin, but I need to make conditional fields.

Let's say I've the following form. I want to show (or not) a single line input with thext or a textarea according to the value selected in the select.

<form method="post" action="">                  
    <select > 
        <option value="" selected="selected">choose one</option>
        <option value="1" >line</option>
        <option value="2" >area</option>
    </select>
    <input id="element_1" /> 
    <textarea id="element_2" ></textarea> 
</form> 

A behaviour like this one is implemented by default in backbone?

If not, how can I implement it with javascript and backone-forms?

thanks.

like image 497
Daniele B Avatar asked Jul 11 '12 13:07

Daniele B


2 Answers

You can bind events to the select element and have them toggle the visibility of other form elements.

Try this:

$(function() {

    //The form
    var form = new Backbone.Form({
        schema: {
            inputType: { type: 'Select', options: ['line', 'area'] },
            line: 'Text',
            area: 'TextArea'
        }
    }).render();

    form.fields['area'].$el.hide();

    form.on('inputType:change', function(form, editor) {         
        form.fields['line'].$el.toggle();
        form.fields['area'].$el.toggle();
    });

    //Add it to the page
    $('body').append(form.el);
});

Here's some live code: http://jsfiddle.net/shioyama/grn6y/

Derived from this: https://groups.google.com/d/topic/backbone-forms/X5eVdTZWluQ/discussion

like image 158
Chris Salzberg Avatar answered Oct 25 '22 13:10

Chris Salzberg


There is no default implementation.In fact, completely on your own is also very simple, please reference the following code:

//Pseudo code 
var line = $("element_1"),area = $("element_2");
if(selectvalue ==="1"){
  line.show();
  area.hide();
}
else{
  line.hide();
  area.show();
}
like image 34
Justin wong Avatar answered Oct 25 '22 11:10

Justin wong