Skip to content

Instantly share code, notes, and snippets.

@mdvorscak
Created August 30, 2015 22:14
Show Gist options
  • Save mdvorscak/6ebabe57a8c96bedc871 to your computer and use it in GitHub Desktop.
Save mdvorscak/6ebabe57a8c96bedc871 to your computer and use it in GitHub Desktop.
A couple of functions to generate all types of form elements for testing purposes
function addOptionsToSelect($select, selectedItems){
var options = ['opt1', 'opt2', 'opt3'];
selectedItems = selectedItems || [];
var $currentOpt, currentOptionName, isSelected;
for(var i = 0, len = options.length; i < len; i++){
currentOptionName = options[i];
isSelected = selectedItems.indexOf(currentOptionName) > -1;
$currentOpt = $('<option>', {value: currentOptionName, selected: isSelected}).text(currentOptionName);
$select.append($currentOpt);
}
}
function buildTestForm(elementsWithValues){
elementsWithValues = elementsWithValues || [];
var $MF = $('<form>', {name: 'MainForm', id: 'MainForm'});
var inputFields = {'checkbox' : {value: 'checkbox_value', checked: true},
'date': {value: '1989-05-25'},
'email': {value: '[email protected]'},
'hidden': {value: 'hidden value'},
'number': {value: 42},
'password': {value: 'secretPass123'},
'radio': {value: 'radio_value', checked: true},
'range': {value: 42},
'search': {value: 'search string'},
'tel': {value: '876.5309'},
'text': {value: 'test'},
'url': {value: 'http://leekspin.com/'}
};
var $currentInputField, currentFieldOpts;
for (var key in inputFields){
if(inputFields.hasOwnProperty(key)){
currentFieldOpts = {name: key};
if(elementsWithValues.indexOf(key) > -1){
$.extend(currentFieldOpts, inputFields[key]);
}
$currentInputField = $('<' + key + '>', currentFieldOpts);
$MF.append($currentInputField);
}
}
var $textArea = $('<textarea>', {name: 'textarea_field'});
if(elementsWithValues.indexOf('textarea') > -1){
$textArea.text('just some text in this area');
}
$MF.append($textArea);
var $selectOne = $('<select>', {name: 'select_one_field'});
var selectOneOptions;
if(elementsWithValues.indexOf('select_one_field') > -1){
selectOneOptions = ['opt1'];
}
addOptionsToSelect($selectOne, selectOneOptions);
$MF.append($selectOne);
var $selectMany = $('<select>', {name: 'select_multiple_field', multiple: true});
var selectManyOptions;
if(elementsWithValues.indexOf('select_one_field') > -1){
selectManyOptions = ['opt1', 'opt2'];
}
addOptionsToSelect($selectMany, selectManyOptions);
$MF.append($selectMany);
return $MF;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment