my javascript variables
var select1 = document.getElementById('status-kehadiran1');
select1.onchange = function () {
select1.classList.remove("hijau");
select1.classList.remove("merah");
select1.classList.add(this.options[this.selectedIndex].className);
}
var select2 = document.getElementById('status-kehadiran2');
select2.onchange = function () {
select2.classList.remove("hijau");
select2.classList.remove("merah");
select2.classList.add(this.options[this.selectedIndex].className);
}
var select3 = document.getElementById('status-kehadiran3');
select3.onchange = function () {
select3.classList.remove("hijau");
select3.classList.remove("merah");
select3.classList.add(this.options[this.selectedIndex].className);
}
var select4 = document.getElementById('status-kehadiran4');
select4.onchange = function () {
select4.classList.remove("hijau");
select4.classList.remove("merah");
select4.classList.add(this.options[this.selectedIndex].className);
}
var select5 = document.getElementById('status-kehadiran5');
select5.onchange = function () {
select5.classList.remove("hijau");
select5.classList.remove("merah");
select5.classList.add(this.options[this.selectedIndex].className);
}
var select6 = document.getElementById('status-kehadiran6');
select6.onchange = function () {
select6.classList.remove("hijau");
select6.classList.remove("merah");
select6.classList.add(this.options[this.selectedIndex].className);
}
var select7 = document.getElementById('status-kehadiran7');
select7.onchange = function () {
select7.classList.remove("hijau");
select7.classList.remove("merah");
select7.classList.add(this.options[this.selectedIndex].className);
}
var select8 = document.getElementById('status-kehadiran8');
select8.onchange = function () {
select8.classList.remove("hijau");
select8.classList.remove("merah");
select8.classList.add(this.options[this.selectedIndex].className);
}
var select9 = document.getElementById('status-kehadiran9');
select9.onchange = function () {
select9.classList.remove("hijau");
select9.classList.remove("merah");
select9.classList.add(this.options[this.selectedIndex].className);
}
var select10 = document.getElementById('status-kehadiran10');
select10.onchange = function () {
select10.classList.remove("hijau");
select10.classList.remove("merah");
select10.classList.add(this.options[this.selectedIndex].className);
}
is there a way to create a looping for those variable to make it more simple?
my html select elements
because i have 10 select element with different id
view
the purpose of each variable is to change the text color of each select when there is a change of selected option
i hope you can understand my explanation
Don't use IDs, use a common selector instead for all of those selects - such as [name^="pertemuan"] (name attribute starts with pertemuan):
for (const select of document.querySelectorAll('[name^="pertemuan"]')) {
select.addEventListener('change', () => {
select.classList.remove("hijau", "merah");
select.classList.add(select.options[select.selectedIndex].className);
});
}
You could drop the ids and move status-kehadiran to the selects class list. The you can select all of them with .querySelectorAll() and loop over them with .forEach()
document.querySelectorAll('.status-kehadiran')
.forEach(function(select) {
select.addEventListener('change', function() {
this.classList.remove('hijau', 'merah');
this.classList.add(this.selectedOptions[0].className);
});
});
As mentioned by others you can use query selector with name and ids, but you can also assign them a common class and use -
document.getElementsByClassName('.name of class')
.forEach(function(select) {
select.addEventListener('change', function() {
this.classList.remove('hijau', 'merah');
this.classList.add(this.selectedOptions[0].className);
});
});
You can first select all the elements with ids using Document.querySelectorAll() and then loop through them and attach the event (change) one by one using EventTarget.addEventListener().
You can try the following way:
//you can select by exact id
//var sel = document.querySelectorAll('#status-kehadiran1, #status-kehadiran2, #status-kehadiran3, #status-kehadiran4, #status-kehadiran5, #status-kehadiran6, #status-kehadiran7, #status-kehadiran8, #status-kehadiran9, #status-kehadiran10');
//you can select by id startsWith selector by matching the common part of each id
var sel = document.querySelectorAll('[id^=status-kehadiran]');
sel.forEach(function(el){
el.addEventListener('change', function(){
el.classList.remove("hijau", "merah"); //you can remove multiple class separating them with comma
el.classList.add(el.options[el.selectedIndex].className);
});
});
Related
I have few textarea on which I want to get the default text selected when I tabbing upon it.
For a single textarea I've found a script which I adapted to my situation but is not an elegant solution.
How can I shorten it.
<script type="text/javascript">
var textBox1 = document.getElementById("textarea_1");
var textBox2 = document.getElementById("textarea_2");
var textBox3 = document.getElementById("textarea_3");
textBox1.onfocus = function() {
textBox1.select();
// Work around Chrome's little problem
textBox1.onmouseup = function() {
// Prevent further mouseup intervention
textBox1.onmouseup = null;
return false;
};
};
textBox2.onfocus = function() {
textBox2.select();
textBox2.onmouseup = function() {
textBox2.onmouseup = null;
return false;
};
};
textBox3.onfocus = function() {
textBox3.select();
textBox3.onmouseup = function() {
textBox3.onmouseup = null;
return false;
};
};
</script>
You can add a dedicated class name and refactor the code to be more generic using class name as selector an make it work for multiple textareas like this:
// Add the class 'auto-selectable' to the desired <texarea/> elements
var textBoxes = document.getElementByClassName('auto-selectable');
for(var i = 0; i < textBoxes.length; i++) {
var textBox = textBoxes[i];
textBox.select();
// Work around Chrome's little problem
textBox.onmouseup = function() {
// Prevent further mouseup intervention
textBox.onmouseup = null;
return false;
};
}
a small correction to Plamen's answer: Elements not Element
var textBoxes = document.getElementsByClassName('auto-selectable');
instead of:
var textBoxes = document.getElementByClassName('auto-selectable');
I want to select first <span> and second <span> , then get their innerText.
Bur i try to use xpath or document.querySelector , they are no working. I console.log my array show null.
// I want to select first <span>
function getDate() {
var date = document.querySelector('div.movie_intro_info_r li').selectedIndex = 1;
return Array.prototype.map.call(date, function (e) {
return e.innerHTML;
});
};
// I want to select second <span>
function getMovieLength() {
var movieLength = document.querySelectorAll(x('//*[#class="movie_intro_info_r"]/span[2]'));
return Array.prototype.map.call(movieLength, function (e) {
return e.innerText;
});
};
casper.then(function () {
casper.each(movieHref, function (casper, url) {
casper.thenOpen(url, function () {
casper.waitForSelector('div.btn_gray_info.gabtn', function () {
console.log('wait for element');
});
releaseDate[urlCount] = this.evaluate(getDate);
console.log(releaseDate[urlCount]);// show null
movieLength[urlCount] = this.evaluate(getMovieLength);
console.log(movieLength[urlCount]);// show null
urlCount++;
});
});
});
How can I just select specified element and get its innerText?
Your code is a bit too complex for what you are trying to do. You should consider using the fetchText method with CSS selectors:
var casper = require('casper').create();
casper.start('YOUR_URL', function () {
this.echo(this.fetchText('.movie_intro_info_r > span:first-of-type'));
this.echo(this.fetchText('.movie_intro_info_r > span:nth-of-type(2)'));
}).run();
I am trying to filter one dropdown from the selection of another in a Rails 4 app with jquery. As of now, I have:
$(document).ready(function(){
$('#task_id').change(function (){
var subtasks = $('#subtask_id').html(); //works
var tasks = $(this).find(:selected).text(); //works
var options = $(subtasks).filter("optgroup[label ='#{task}']").html(); // returns undefined in console.log
if(options != '')
$('#subtask_id').html(options);
else
$('#subtask_id').empty();
});
});
The task list is a regular collection_select and the subtask list is a grouped_collection_select. Both which work as expected. The problem is that even with this code listed above I can't get the correct subtasks to display for the selected task.
NOTE: I also tried var tasks=$(this).find(:selected).val() that return the correct number but the options filtering still didn't work.
Try something like this instead (untested but should work).
$(function () {
var $parent = $('#task_id'),
$child = $('#subtask_id'),
$cloned = $child.clone().css('display', 'none');
function getParentOption() {
return $parent.find('option:selected');
}
function updateChildOptions($options) {
$child.empty();
$child.append($options);
}
$parent.change(function (e) {
var $option = getParentOption();
var label = $option.prop('value'); // could use $option.text() instead for your case
var $options = $cloned.find('optgroup[label="' + label + '"]');
updateChildOptions($options);
});
});
Am getting key Combination from the server. Based on that am assigning key Combination to function dynamically. The below code is working for last iteration in loop. how below code is work for all iterations.
In my page i have two buttons save and cancel the below code is working for last iteration in for loop, It means btnCanel button triggers if i press key for save function.Any suggestions. hope understand my question.
$(document).ready(function fn() {
var keyCombination = new Object();
keyCombination['btnAdd'] = "Alt+S";
keyCombination['btnCancel'] = "Alt+C";
for (var k in keyCombination) {
if (keyCombination.hasOwnProperty(k)) {
shortcut.add(String(keyCombination[k]), function () {
var btnAdd = document.getElementById(String(k));
btnAdd.focus();
btnAdd.click();
});
}
}
});
if i give like this means it is working
shortcut.add("Alt+S", function () {
var btnAdd = document.getElementById('btnAdd ');
btnAdd .focus();
btnAdd .click();
});
shortcut.add("Alt+C", function () {
var btnCancel = document.getElementById('btnCancel');
btnCancel.focus();
btnCancel.click();
});
but if i try to add dynamically its overriding help me this issue.
Thanks in Advance.
I created a separate function outside the document.ready function like this now its working fine.
$(document).ready(function fn() {
var keyCombination = new Object();
keyCombination['btnAdd'] = "Alt+S";
keyCombination['btnCancel'] = "Alt+C";
for (var k in keyCombination) {
if (keyCombination.hasOwnProperty(k)) {
Set_KeyCombinations(k, keyCombination);
}
}
});
function Set_KeyCombinations(k, keyCombination) {
shortcut.add(String(keyCombination[k]), function () {
var eleId = document.getElementById(String(k));
if (eleId) {
if ($('#' + String(k).trim()).css('display') !== 'none' && eleId.getAttribute("disabled") !== "disabled") {
eleId.click();
eleId.focus();
}
}
});
}
Try this:
var keyCombinations = [ "Ctrl+Shift+X" , "Ctrl+Shift+Y" ];
for(var i=0; i<keyCombinations.length; i++){
(function(shorcutCombination){
shortcut.add(shorcutCombination,function() {
alert("i am " + shorcutCombination);
});
})(keyCombinations[i]);
}
The idea is that you need to preserve the value of keyCombinations[i]
as i increases in the loop. Tested this here: Openjs
I am using event-delegation on n-number of rows, my older approach was binding each row with event the code looked something like this:
function getDiv (data) {
var div = $("<div class='theDiv'>");
div.click(function () {
console.log(data);
});
return div;
}
function getContainer() {
var i, container;
container = $("<div class='container'></div>");
for (i = 0 ; i < 1000 ; i++) {
container.append(getDiv(i));
}
return container;
}
$("body").append(getContainer());
Note: In this approach each row element (theDiv) is having access to their data.
Now the question is, I want to bind a single click on container and access the data, the event-delegation approach would look like this:
function getNewDiv (data) {
var div = $("<div class='theDiv'>");
return div;
}
function getNewContainer() {
var i, container;
container = $("<div class='container'></div>");
for (i = 0 ; i < 1000 ; i++) {
container.append(getNewDiv(i));
}
container.click (function (e) {
var targetElem = e.target;
console.dir(e);
if ($(targetElem).hasClass("theDiv")) {
console.log("row was clicked");
}
})
return container;
}
$("body").append(getNewContainer());
Now, how to access the data associated with each row?
As per my learning:
I can add the data to
data-*, but this would limit me to simple data type
$.data associated to element
Is there any other way todo this?
.on allows you to do event delegation:
container.on('click', '.theDiv', function () {
//`this` is `.theDiv`.
});
You can use $.data() inside getNewDiv() to store a reference index:
function getNewDiv (dataIndex) {
return $("<div class='theDiv'>").data('idx', dataIndex);
}
Then, use each element's data index variable to reference an object in your big array of data:
var mydata = [{ ... }, { ... }, { ... }];
container.on('click', '.theDiv', function () {
var data = mydata[$(this).data('idx')];
console.log("row was clicked");
});