I'm running into a problem. How can I console.log the selected option/value from the datalist when selecting/clicking with my mouse?
var input = document.querySelector("input");
var options = Array.from(document.querySelector("datalist").options).map(function(el){
return el.innerHTML;
}); //Optional if you have data
input.addEventListener('keypress', function(e){
if(e.keyCode == 13){
var relevantOptions = options.filter(function(option){
return option.toLowerCase().includes(input.value.toLowerCase());
}); // filtering the data list based on input query
if(relevantOptions.length > 0){
input.value = relevantOptions.shift(); //Taking the first
console.log(input.value)
}
}
});
<input list='typesOfFruit' placeholder="Enter a fruit...">
<datalist id='typesOfFruit'>
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</datalist>
If I understand correctly, select your element and add an eventListener to it that listens to 'change'
const input = document.querySelector('input');
input.addEventListener('change', (e) => { console.log(e.target.value) })
In your example just do this
var input = document.querySelector("input");
// above mentioned eventListener
input.addEventListener('change', function(event){
console.log(`selected value: ${event.target.value}`)
})
var options = Array.from(document.querySelector("datalist").options).map(function (el) {
return el.innerHTML;
}); //Optional if you have data
input.addEventListener('keypress', function (e) {
if (e.keyCode == 13) {
var relevantOptions = options.filter(function (option) {
return option.toLowerCase().includes(input.value.toLowerCase());
}); // filtering the data list based on input query
if (relevantOptions.length > 0) {
input.value = relevantOptions.shift(); //Taking the first
console.log(input.value)
}
}
});
Related
I have a simple textarea. I want to check this area for text, when you push button and if your textarea is empty it fills it with default email.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.textContent != null) {
x.textContent = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function(e) {
e.preventDefault();
putDefaultMail();
});
<form>
<textarea id="smth"></textarea>
<button id="btn">Sumbit</button>
</form>
But something went wrong. It just calls once.
textContent is not the proper way of getting values from textarea. And also, a blank textarea's value is "", not null.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.textContent != null) {
x.textContent = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
<form>
<textarea id="smth"></textarea>
<button id="btn">Sumbit</button>
</form>
Instead, try .value:
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.value == '') {
x.value = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
<form>
<label>Text: <textarea id="smth"></textarea></label>
<button id="btn">Sumbit</button>
</form>
By the way, you should add labels to the controls like above.
However, if the user enters spaces, then it passes. Like #MuhammadAliMalekzadeh said below, trim() should remove the spaces around for you.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.value
.trim() // <-- here
== '') {
x.value = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
<form>
<label>Write here: <textarea id="smth"></textarea></label>
<button id="btn">Sumbit</button>
</form>
Textarea has a value. You should check if value empty or not.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.value == "") { // if empty
x.value = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
I have a table populated with animals and need to filter them by population and i want to use a range slider to filter them without using jQuery, just plain javascript, already have 2 filters using array.prototype. Here is my html code:
<fieldset>
<legend>Search by population</legend>
<input id="populationSlider" class="range-slider__range" type="range" value="100" min="194" max="500000" onchange="updateSliderNumber('populationNumber', this.value);">
<input id="populationNumber" type="number" value="100" min="194" max="500000" onchange="updateSliderNumber('populationSlider', this.value);">
<span class="range-slider__value"></span>
</fieldset>
and here is my sript:
(function(document) {
var AnimalFilter = (function(Arr) {
var _input;
var _select;
function _onInputEvent(e) {
_input = e.target;
var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filter);
});
});
}
function _onSelectEvent(e) {
_select = e.target;
var tables = document.getElementsByClassName(_select.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filterSelect);
});
});
}
function _filter(row) {
var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
}
function _filterSelect(row) {
var text_select = row.textContent.toLowerCase(), val_select = _select.options[_select.selectedIndex].value.toLowerCase();
row.style.display = text_select.indexOf(val_select) === -1 ? 'none' : 'table-row';
}
return {
init: function() {
var inputs = document.getElementsByClassName('table-filter');
var selects = document.getElementsByClassName('select-table-filter');
Arr.forEach.call(inputs, function(input) {
input.oninput = _onInputEvent;
});
Arr.forEach.call(selects, function(select) {
select.onchange = _onSelectEvent;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
AnimalFilter.init();
}
});
})(document);
// Range-slider
function updateSliderNumber(id, value){
document.getElementById(id).value = value;
}
Ant suggestions?Do i need to call another function, or extend my prototype.array?
Thank you in advance!
How can I prevent duplicate values being added to a combobox? I also need to prevent the space value. This is my code but its not working.
An entry is entered the first time input but the second time I enter input its alerting me that I have entered a duplicate value even when I enter different values.
Please see this jsFiddle https://jsfiddle.net/adLxoakv/
<HTML>
<HEAD>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
Selected: <input type="text" name="selected" id="selected"/>
IMEI Selected: <input type="text" name="imei" id="imei"/>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
$("#txtCombo").on("keydown", function (e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function(){
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function () {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if (combo.length) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
</script>
To find the duplicate you can use following function(using jQuery)
function isDuplicate(value,text){
/*Get text of the option identified by given value form the combobox and then check if its text matches the given text*/
if($('#combo select option[value="' + value + '"]').text() == text)
return true;
else
return false;
}
Update:
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
var value = textb.value.trim();
option.text = value;
option.value = value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if ($('#combo option[value="' + value + '"]').text() == value ) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
<input type="text"> event: <span id="result"></span>
<script>
var input = document.body.children[0];
input.oncopy = function(e) {
debugger
e = e || event;
// document.getElementById('result').innerHTML = e.type +' '+input.value;
// return false;
}
I want get text when copying .It is possible?
Just try with:
input.oncopy = function(e) {
var value = this.value.substring(this.selectionStart, this.selectionEnd);
}
demo
I want after add a input and remove it, arrange the numbers in input name element array by jQuery but don't work for me after remove input. How can fix it?
DEMO: http://jsfiddle.net/mUMdW/
My Code:
Html:
<div class="ch">
Add
</div>
<p class="ffdd"></p>
jQuery:
function removeidx(clss, type){
var remove = $(this).closest(clss);
remove.fadeOut('slow', function () {
$(this).remove(); // or change next line to $('.RowCheck:visible')
$(clss).each(function (idx) {
var checkBoxes = $('input[type="'+type+'"]',this);
checkBoxes.each(function(i) {
var str = $(this).attr('name');
var currentIdx = parseInt(str.match(/\d+/)[0], 10);
$(this).attr('name', str.replace(currentIdx,idx));
})
});
});
}
$(document).on('click change', 'a.adding', function(e) {
e.preventDefault();
var idx = $('.Row').length;
$('.ffdd').append('<div class="Row"> <input name="arr['+idx+'][]" type="text" value=""> Remove</div>');
});
$('.ffdd').on('click','a', function(e){
$(this).closest('.Row').remove();
removeidx('.ffdd', 'text');
})
I guess that you want to re-number the inputs after a remove, so that the array is made of contiguous numbers.
I have rewritten some things, among which the renumbering function, using an index contextual to the parent function.
function removeidx(context, clss, type) {
var remove = $(context).closest(clss);
remove.fadeOut('slow', function () {
$(this).remove();
var idx = 0;
$(clss).each(function () {
var checkBoxes = $('input[type="' + type + '"]', this);
checkBoxes.each(function () {
var name = $(this).attr('name');
name = name.replace(/\d+/, idx);
$(this).attr('name', name);
idx = idx + 1;
});
});
});
}
$(document).on('click change', 'a.adding', function (e) {
e.preventDefault();
var idx = $('.Row').length;
$('.ffdd').append('<div class="Row"> <input name="arr[' + idx + '][]" type="text" value=""> Remove</div>');
});
$('.ffdd').on('click', 'a', function (e) {
removeidx(this, '.Row', 'text');
})
You can see a working version there : http://jsfiddle.net/8sVWp/