backbone-forms with conditional fields - javascript

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.

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

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

Related

How do I pass the value of drop down with form submit?

I have these 2 drop downs:
I have to provide values of Select Item drop down based on the value chosen in the Select Category drop down.
This is my PHP for Select Category drop down:
<form>
...
<select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onclick="document.form.submit();">
<option value="" disabled selected>Select Category</option>
...
<input type="submit" name="submit" style="width:20%;padding:15px;" value="Update"</input>
...</form>
But nothing is happening. How do I do it?
Try onchange instead of onclick
<form>
...
<select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onchange="document.forms[0].submit();">
<option value="" disabled selected>Select Category</option>
...
<input type="submit" name="submit" style="width:20%;padding:15px;" value="Update"</input>
...</form>
Two more things you should notice
onchange="document.form.submit();" this will not work because
document doesn't have a property form it is forms so you should
use onchange="document.forms[0].submit();"
You have named your submit button as submit which will prevent the
form from submitting because submit is a javascript function so
rename your submit button to something else.
If you dont have many possible values for your dropdowns, you can use plain old javascript for that purpose. See this http://jsfiddle.net/mplungjan/65Q9L/, but it requires all values to be loaded at once on the page load like this:
var stateObject = {
"California": {
"Monterey": ["Salinas", "Gonzales"],
"Alameda": ["Oakland", "Berkeley"]
},
"Oregon": {
"Douglas": ["Roseburg", "Winston"],
"Jackson": ["Medford", "Jacksonville"]
}
}
document.form.submit(); will submit the form which is not the requirement.
Instead you need to make an ajax call with the selected value from first dropdown and the response will be use to build the options of second dropdown.
use change which will trigger on change of option
$('category').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value; // will give value of selected option
$.ajax({
url:"someUrl", // this url will return response from backend
// other methods
success:function(response){
//use this response to build the second dropdown
}
})
});

Jquery Validation Plugin, Use option's data element as check for validation

I'm looking for a way to have JQuery validate plugin check the value of a selected option's data element to determine if the selection is valid or invalid. The reason invalid options need to be included in the select is primarily for display purposes. i.e. if I have a select with the question "What colour is your house?" and I have options "Red", "Blue", "Green", the end user needs to be explicitly shown that "Green" is not a valid choice.
Right now I'm using 'validate' for everything else but I had to write in a separate function to check these fields and I'd like to be able to do it all with just 'validate'.
Here is a more detailed example of what I'm looking for:
HTML:
<html>
<head>
<script type="text/javascript" src="./js/jquery-validate-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
// BASIC VALIDATION
// Set Validator Defaults and rules
$.validator.setDefaults({
errorPlacement: function(error, element) {
$(element).attr({"title": error.append()});
},
highlight: function(element){
$(element).addClass("error");
},
unhighlight: function(element){
$(element).removeClass("error");
}
});
$("#myform").validate({
rules: {
email: {
required: true,
email: true
},
myselect: {
// HOW DO I DEFINE THIS RULE SO THAT
// IF OPTION 3 IS SELECTED THIS RETURNS
// INVALID
}
}
});
});
</script>
</head>
<body>
<form id='myform' name='myform'>
<input type='text' id='email' name='email value='' />
<select id='myselect' name='myselect'>
<option id='1' data-is_valid='1'>Option 1</option>
<option id='2' data-is_valid='1'>Option 2</option>
<option id='3' data-is_valid='0'>Option 3</option>
<option id='4' data-is_valid='1'>Option 4</option>
</select>
</form>
Quote OP:
"I had to write in a separate function to check these fields and I'd like to be able to do it all with just validate."
You could use the .addMethod() method to wrap your separate function and turn it into a rule.
However, if you'd take the time to explain why you'd want to restrict a select to certain options, when you're already in control of how the select is created in the first place, a better answer or workaround could possibly be suggested. (this is one way that SO benefits everyone else long after the OP is satisfied)
Here's how I ended up solving it:
Thankyou to Sparky for pointing me in the right direction
jQuery.validator.addMethod("valid_option", function(value, element) {
if ($(":selected", element).data('is_valid') == "1") {
return true;
}
return false;
}, "&nbsp&nbspError, Invalid Selection");

Binding an event handler to an HTML select.option

I want to show a warning message if a user selects a specific option, but the warning isn't appearing. How can I modify my code so that this works correctly? Here is a demo on jsFiddle which reproduces the problem?
HTML :
<input type="text" id="mail_address"/>
<select>
<option value='google.com'>google.com</option>
<option onClick="warningaa()" value=''>Don't send mail</option>
</select>
JS:
function warningaa() {
alert('If you choose this option, you can not receive any information');
}
You can not use on click action in dropdown option. One solution is to use change on select element:
html
<input type="text" id="mail_address" />
<select onchange="warningaa(this);">
<option value='google.com'>google.com</option>
<option value='error'>error</option>
</select>
js
function warningaa(obj) {
if(obj.value == "error") {
alert('If you choose this option, you can not receive any infomation');
}
}
fiddle
The option tag does not support the onclick event. Use the onchange event on the select instead.
HTML
<input type="text" id="mail_address"/>
<select id="selectbox" onchange="warning(this)">
<option value='google.com'>google.com</option>
<option value='warning'>Do not send me any kind of shit</option>
</select>
JS
function warning(obj) {
if(obj.value == 'warning') {
alert('If you choose this option, you can not receive any infomation');
}
}
You need to set an event handler on the SELECT element, and watch the "value" of select, as below:
document.getElementById('mySelect').addEventListener('change', warn, true);
function warn(e) {
e.preventDefault();
e.stopPropagation();
if (e.currentTarget.value === 'the value you want') {
// do something
} else {
return;
}
The key here is using CHANGE event vs CLICK, since you want to react to a "change in value" and if that value = something, warn the user.
using addEventListener is also a better approach overall, it clearly distinguishes your HTML from your JavaScript.
More on this here:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
and here:
https://developer.mozilla.org/en/docs/Web/API/Event

How to structure the code to process multiple variables from mulitple form elements in JavaScript and remember the choices?

E.g. I have an HTML form:
<form role="search" method="get" id="searchform" action="" >
<!-- DIRECT SEARCH INPUT TO SEARCH STRING -->
<input type="text" value="" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
<!-- DROPDOWN TO SELECT ONE CHOICE -->
<select name='country' id='country' class='postform' >
<option class="level-0" value="2">USA</option>
<option class="level-0" value="3">Canada</option>
<option class="level-0" value="4">Mexico</option>
<option class="level-0" value="5">Cuba</option>
</select>
<!-- CHECKBOXES TO SELECT MULTIPLE CHOICES -->
<div id="color">
<input type="checkbox" name="" value="21" />Beachfront
<input type="checkbox" name="" value="16" />TV
<input type="checkbox" name="" value="20" />Internet
<input type="checkbox" name="" value="17" />Pets Allowed
</div>
</form>
<div id="results"><!-- THE AJAX RESULTS GOES HERE --></div>
And I want to be able to make AJAX request every time the user:
1) write something in the search input box and click search button
OR
2) select one choice from the dropdown menu
OR
3) select one or multiple choices from the checkboxes that are checked
The problem is that I don't know how to structure my JavaScript code correctly and what is the best way to remember and manage choices that the user selected before, to take all things in account. For example, not just the search term when he write something and click search button, but also to take in count the dropdown choice (probably done one step before) and maybe the checked options from checkboxes if he has checked something before. Here is what I have so far:
jQuery(document).ready(function($){
// RESULTS SHOULD APPEAR IN #results DIV AFTER AJAX IS DONE
var $maincontent = $('#results');
// SEARCH INPUT PROCESSING
$('#searchsubmit').click(function(e){
e.preventDefault();
var searchval = $('#s').val();
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
searchval : searchval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
}
);
});
// COUNTRY DROPDOWN CHOICE PROCESSING
$('#country').on('change', function() {
var countryval = this.value;
$maincontent.animate({ opacity : '0.1' })
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
countryval : countryval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
$maincontent.animate({ opacity : '1' })
}
);
return false;
});
// CHECKBOXES PROCESSING
$('#color input[type=checkbox]').click(function() {
if (this.checked) {
// code if checked
}
else {
// nothing
}
});
});
As you can see, it's very bad. Because one "function" checks only click, one change and I don't know how to grab values from the checkboxes and make an array and send it via ajax ;(.
Any idea how to structure the JavaScript code so it is not so separated and the checks are somehow in one part (or more logical) instead of three separated parts?
Any ideas are welcome.
Create som logic :
var _do = {
bind: function() {
var self = this;
$('#searchsubmit').on('click', function(e){
e.preventDefault();
self.ajax('searchval', $('#s').val());
});
$('#country').on('change', function() {
self.ajax('countryval', this.value);
});
return self;
},
ajax: function(key, value) {
var data = {action: 'ajax_search_action_do'};
data[key] = value;
$.post(
WPaAjax.ajaxurl, data, function( response ) {
$maincontent.empty().append( response );
}
);
}
}
jQuery(document).ready(function($){
_do.bind();
});
Maybe use jquery.form.js?
http://malsup.com/jquery/form/
It's a great plugin, just structure the form like it was a normal redirection form, add array in name of checkboxes
<input type="checkbox" name="types[]" value="21" />Beachfront
Add target URL to the form, and then...
When u want to submit the form just do
$('searchform').ajaxSubmit({
success: function() {
// callback
}
)
Trigger this on checkboxes change, dropdown change etc. To make the code clean, use one selector
$('#country, #s, #color input').on('change', sendAjaxForm);

Select box to change url

I want to use a select to change the query on the end of a url to change it's sort options. e.g:
<select id="sort">
<option value="?order_by=date">Recent</option>
<option value="?order_by=random">Popular</option>
<option value="?order_by=random">Random</option>
<option value="">Staff Picks</option>
</select>
so for example by default a list of posts will be shown by date and then if a user chooses an option it will reload the page with the query string on the end of the URL. If possible looking to use jQuery to achieve this. Thanks.
Attach a handler to the change event for the select box that adds the value of the selected option to the current window location with everything after the ? snipped off:
$('#sort').change(function(e){
var locAppend = $(this).find('option:selected').val(),
locSnip = window.location.href.split('?')[0];
window.location.href = locSnip + locAppend;
});
Here's an example ࢐ (it doesn't redirect, but you get the idea...)
To have the appropriate value selected on page load, you can run the following function before you bind the change handler:
function selectCurSort() {
var match = window.location.href.split('?')[1];
$('#sort').find('option[value$="'+match+'"]').attr('selected',true);
}
selectCurSort();
I'm not quite sure why you aren't just using something like:
<form method="GET">
<input type="hidden" name="query" value="..." />
<select id="sort" name="order_by">
<option value="date">Recent</option>
<option value="popular">Popular</option>
<option value="random">Random</option>
<option value="staff">Staff Picks</option>
</select>
<input type="submit" value="Sort" />
</form>
And, for the JS, if any, just:
$('#sort').change(function() {
$(this).parents('form').submit();
});
Then, you don't require anyone to have JavaScript enabled.
Like this?
$("#sort").change(function(){
window.location = $(this).find("option:selected").val();
});
Add
onchange="if (this.value && /^\?/.test(this.value)) location = location.path + this.value"
to your <select>.
You might want to put a blank option at the top too.
$(function() {
$("#sort").change(function() {
var myVal = $(this).val();
window.location = "www.mywebsite.com/"+ myVal;
});
var qs = window.location.pathname;
$("#sort option").each(function() {
if(qs.contains($(this).val()))
$(this).addAttr("selected","selected");
});
});
Try that.

Categories

Resources