Convert and input into a Select
Should create an input with it's original event handlers
by sidouglas
HTML
<label for="Checkout_shipRegion">a Label</label>
<input class="form-control" data-key="shipRegion" data-prompt="Please select" data-updatestate="1" name="Checkout[shipRegion]" id="Checkout_shipRegion" type="text">
<input class="form-control" name="captainwoft" id="anotherinput" type="text">
<br>
<a href="#" id="convert">Convert to select</a>
JavaScript
(function($) {
$(function (){
$('#Checkout_shipRegion').on('click',function(){ console.log('click') });
$('#Checkout_shipRegion').on('blur',function(){ console.log('blur') });
$('#convert').on('click', function(){
convertInputToSelect( $('#Checkout_shipRegion'), addSomeOptionElements );
});
/**
* [convertInputToSelect]
* NOTE: the $input must have an id
* @param {$} $input <input> element
* @return new <select> elm.
*/
function convertInputToSelect($input,cb) {
var textProps = {};
var id = $input.attr('id');
var $select = $('<select>');
if (!id) {
throw 'there must be an id on the passed $input';
}
if (!$input instanceof $) {
throw 'pass a jQuery element';
}
if ($input.length > 1) {
throw 'pass extactly 1 jQuery element';
}
// copy across the input's attributes
$input.each(function() {
$.each(this.attributes, function() {
if (this.specified) {
if (this.value === 'text') {
return;
}
$select.attr( this.name , this.value );
}
});
});
//copy across the input's event handlers
$.each($._data($input.get(0), 'events'), function() {
$.each(this, function() {
$select.on(this.type, this.handler);
});
});
$input.replaceWith($select);
if( typeof cb === 'function') {
cb.call($select);
...