Question :
How to pass parameters from one function to another?
Follow the code:
<body onload="getfoucs()">
<select id="select_compra" data-limit="3">
<option disabled selected style="display: none">Aaaaaaaaaaaaa</option>
<option>Bbbbbbbbb</option>
<option>Ccccccc</option>
<option>Ddddddddddd</option>
</select>
<script>
function datalimit(limit)
{
var selects = document.querySelectorAll('[data-limit]');
[].forEach.call
(
selects, function(select)
{
var limit = select.getAttribute('data-limit');
[].forEach.call
(
select.options, function(option)
{
var text = option.innerHTML.substring(0, limit);
option.innerHTML = text;
}
);
}
);
}
function getfoucs()
{
datalimit();
select_compra.addEventListener
(
'change', function()
{
datalimit(50);
/*
Como eu altero o valor de "limit" e
Chamo novamente a função datalimit()
*/
}
);
}
</script>
</body>
My intention is that when firing the event change
the value of limit
is changed to behave more characters and later when the select
loses the focus
back to the initial value that is 3
(but let’s break it down).
Answer :
Here’s a suggestion:
(function(selects) {
var limite = 3;
function verificarLimite(opts) {
var originais = opts.map(function(option) {
return option.innerHTML;
});
return function(e) {
opts.forEach(function(option, i) {
option.innerHTML = e.type == 'blur' ? originais[i].slice(0, limite) : originais[i];
});
}
}
selects.forEach(function(select) {
var verificador = verificarLimite(Array.from(select.children));
select.addEventListener('focus', verificador);
select.addEventListener('blur', verificador);
verificador({type:'blur'});
});
})(Array.from(document.querySelectorAll('[data-limit]')));
<select id="select_compra" data-limit="3">
<option disabled selected style="display: none">Aaaaaaaaaaaaa</option>
<option>Bbbbbbbbb</option>
<option>Ccccccc</option>
<option>Ddddddddddd</option>
</select>
The code is well contained and does what you want.
One more resolution to the problem
<body onload="getfoucs()">
<select id="select_compra" data-limit="3">
<option disabled selected style="display: none" data-texto="Aaaaaaaaaaaaa">Aaaaaaaaaaaaa</option>
<option data-texto="Bbbbbbbbb">Bbbbbbbbb</option>
<option data-texto="Ccccccc">Ccccccc</option>
<option data-texto="Ddddddddddd">Ddddddddddd</option>
</select>
</body>
<script>
function LimitInput()
{
select = document.querySelector('[data-limit]');
limit = select.getAttribute('data-limit');
[].forEach.call
(
select.options,
function(option)
{
text = option.innerHTML.substring(0, limit);
option.innerHTML = text;
}
);
}
function getfoucs()
{
LimitInput();
select_compra.addEventListener
(
'focus', function()
{
var elmnt = document.getElementById('select_compra');
for(var i=0; i < elmnt.options.length; i++)
{
var texto = elmnt.options[i].getAttribute('data-texto');
elmnt.options[i].innerHTML = texto;
}
}
);
select_compra.addEventListener
(
'blur', function()
{
LimitInput();
}
);
}
</script>