How to copy another elements onclick function - javascript

I have been able to successfully get another elements onclick function by doing this:
document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')
This gives me the exact text that I want to put into a different elements onchange event, so I thought I could do this:
<select onchange="document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')">
This does not work though. Does anyone have any ideas, I am stumped?

You can't just dump a function into an attribute like that. I recommend that you start writing unobtrusive JavaScript.
HTML
<select id="mySelect">
<!-- snip -->
</select>
JavaScript
var select = document.getElementById('mySelect');
select.onchange = function () {
var id = this.options[this.selectedIndex].text,
clickHandler = document.getElementById(id).onclick;
clickHandler.apply(this);
};
Demo →
Edit re: OP's comment
"Is there an easy way to apply this to all the selects on the page?"
Of course there is! But you need to be careful about not creating functions in a loop (it won't work).
var selects = document.getElementsByTagName('select'),
numSelects = selects.length,
i;
function setClickHandler(element) {
element.onchange = function () {
var id = this.options[this.selectedIndex].text,
clickHandler = document.getElementById(id).onclick;
clickHandler.apply(this);
}
}
for (i=0; i<numSelects; i++) {
setClickHandler(selects[i]);
}

I haven't tested this, but perhaps:
var handler = document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick');
var selectEl = document.getElementsByTagName('select')[indexOfSelect];
selectEl.setAttribute('onClick',handler);
The following works (more or less the same as above, except using the 'onFocus' attribute on the select element):
var handler = document.getElementById('first').getAttribute('onclick');
var selectEl = document.getElementsByTagName('select')[0];
selectEl.setAttribute('onfocus',handler);
JS Fiddle demo

This is not recommended but the simplest fix that would work,
<select onchange="function() {document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')();}">

Related

Value from HTML to another via registered element

I'm totally newbie when talking about HTML, so this can be obvious to you, but I hope you can help me.
We have a top-menu.html which have some dropdown menus. One of these menus is a checkbox menu.
I have to get the value (and the change event of it) in another HTML, the index.html.
There's a JS code registering an element that can be used by index.html. Still, I don't know how to retrieve the checkbox value.
top-menu.html JS:
function build_component() {
var template = (document._currentScript || document.currentScript)
.ownerDocument.querySelector('#top-menu-template');
var topMenu = Object.create(HTMLElement.prototype);
topMenu.createdCallback = function() {
// import template into
var clone = document.importNode(template.content, true);
this.appendChild(clone);
};
document.registerElement('page-top-menu', { prototype: topMenu });
}
Ok, so I can use <page-top-menu> in index.html. How to get checkbox.checked value now?
Using jquery you can easily do this
html:
<input type="checkbox" value="0" class="check1">
jquery: You can use local storage to save your value
$('.check1').on('change',function(){
var val1 = $(this).val();
localStorage.setItem("value", val1);
alert(val1);
}
To retrieve that you can use following code remove it if you don't want any more
var valnew = localStorage.getItem("value");
alert(valnew);
localStorage.removeItem("value");

Use addEventListener on a class not working

I am trying to convert my script using addEventListener with getElementById on a var for a getElementByClassName but this doesn't work. How to fix it?
See my code
Javascript:
var input = document.getElementByClassName('myClass');
_slider.noUiSlider.on('update', function( values, handle ) {
var value = values[handle];
if ( handle ) {
input.value = Math.round(value);
});
input.addEventListener('change', function(){
_slider.noUiSlider.set([null, this.value]);
}, false);
HTML:
<input type="number" class="myClass">
This script work perfectly if I find my div with an ID, but not work with a CLASS.
There is no getElementByClassName. There is getElementsByClassName that returns a collection. If there is only one, than select the first index.
var input = document.getElementsByClassName('myClass')[0];
Other option is querySelector
var input = document.querySelector('.myClass');
My guess is that you do not have just one element, but multiple, than you need to loop over the collection.
var inputs = document.getElementsByClassName('myClass');
//or
//var inputs = document.querySelectorAll('.myClass');
for( var i=0; i<inputs.length; i++){
inputs[i].addEventListener("click", function() { console.log(this); } );
}
var input = document.getElementById('id_name')
...here addEventListener will work because "id" will unique but in case of "class" there might be same values entered...So you have to select which element you want to manipulate...example ==>
var input = document.getElementsByClassName('class_name')[0] // after this addEventListener will work.
Hope this might help you :)

exchanging values in a select list with jQuery

I'm trying to swap select option values with jQuery when a links clicked, at the moment its just resetting the select when the links clicked, not sure what's going wrong?:
jQuery:
$(function () {
$("#swapCurrency").click(function (e) {
var selectOne = $("#currency-from").html();
var selectTwo = $("#currency-to").html();
$("#currency-from").html(selectTwo);
$("#currency-to").html(selectOne);
return false;
});
});
JS Fiddle here: http://jsfiddle.net/tchh2/
I wrote it in a step-by-step way so it is easier to understand:
$("#swapCurrency").click(function (e) {
//get the DOM elements for the selects, store them into variables
var selectOne = $("#currency-from");
var selectTwo = $("#currency-to");
//get all the direct children of the selects (option or optgroup elements)
//and remove them from the DOM but keep events and data (detach)
//and store them into variables
//after this, both selects will be empty
var childrenOne = selectOne.children().detach();
var childrenTwo = selectTwo.children().detach();
//put the children into their new home
childrenOne.appendTo(selectTwo);
childrenTwo.appendTo(selectOne);
return false;
});
jsFiddle Demo
Your approach works with transforming DOM elements to HTML and back. The problem is you lose important information this way, like which element was selected (it is stored in a DOM property, not an HTML attribute, it just gives the starting point).
children()
detach()
appendTo()
That happens because you remove all elements from both <select> fields and put them as new again. To make it working as expected you'd better move the actual elements as follows:
$("#swapCurrency").click(function(e) {
var options = $("#currency-from > option").detach();
$("#currency-to > option").appendTo("#currency-from");
$("#currency-to").append(options);
return false;
});
DEMO: http://jsfiddle.net/tchh2/2/
You are replacing the whole HTML (every option) within the <select>. As long as each select has the same amount of options and they correspond to each other, you can use the selected index property to swap them:
$("#swapCurrency").click(function (e) {
var selOne = document.getElementById('currency-from'),
selTwo = document.getElementById('currency-to');
var selectOne = selOne.selectedIndex;
var selectTwo = selTwo.selectedIndex;
selOne.selectedIndex = selectTwo;
selTwo.selectedIndex = selectOne;
return false;
});
JSFiddle

Fire a change function without changing focus

I have a table that is sortable and filterable, and everything works fine if I change my filter using a select field. But, if a user doesn't select a filter after x number of seconds, I want it to filter based on a designated option. I have no problem changing the selection after a set time, but the javascript to filter doesn't recognize this is a change() event. How can I get it to recognize it as a change, or by some other way register the default selection after a set period of time?
For reference, I'm using this script for the table filtering/sorting:
http://www.javascripttoolbox.com/lib/table/
I'd like to pass it my own values for Table.filter(this,this).
I think something like this should work:
var defaultFilter = 3;
var filterTimeout = 5000;
window.setTimeout(function() {
var select = document.getElementById("select");
select.selectedIndex = defaultFilter;
Table.filter(select, select);
}, filterTimeout);
HTML:
<select id="select" onchange="Table.filter(this,this)">... </select>
Javascript:
var select = document.getElementById("select");
var secondsToChange = 2;
select.onclick = function() {
window.setTimeout(function(){select.onchange.apply(select)},secondsToChange*1000);
};
I think that should work...

Remove onclick event from img tag

Heres my code:
<div id="cmdt_1_1d" class="dt_state1" onclick="sel_test(this.id)">
<img id="cmdt_1_1i" onclick="dropit('cmdt_1_1');" src="/site/hitechpackaging/images/items/bags_menu.jpg ">
<span class="dt_link">
BAGS
</span>
</div>
Unfortunately I cannot modify this file, is there a way using javascript to disable the onclick from the img tag only.
I was using this script but it disable the onclick event from all images. But i want only from this component
var anchorElements = document.getElementsByTagName('img');
// for (var i in anchorElements)
// anchorElements[i].onclick = function() {
// alert(this.id);
// return false;
// }
Any ideas will be appreciated.
Edited:
Is there a way to stop the function dropit from executing, is it possible using javascript. On page load, etc.
another option is can i rename the img file using javascript??
document.getElementById('cmdt_1_1i').removeAttribute("onclick");
var eles = document.getElementById('cmdt_1_1d').getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
eles[i].onclick = function() {
return false;
}
Lots of answers, but the simplest is:
document.getElementById('cmdt_1_1i').onclick = '';
try something like this:
var badImage = document.getElementById("cmdt_1_1i");
badImage.onclick = null;
badImage.addEventlistener("click",function(e){
e.preventDefault();
e.stopPropagation();
return null;
},true);
If you later need to restore the onclick property, you can save it in a field before overwriting it:
document.getElementById(id).saved=document.getElementById(id).onclick;
document.getElementById(id).onclick = '';
so that later you can restore it:
document.getElementById(id).onclick=document.getElementById(id).saved;
This can be useful especially in the case, in which the original onclick property contained some dynamically computed value.
You can programmatically reassign event listeners. So in this case, it might look something like:
const images = document.querySelectorAll('#cmdt_1_1d img')
for (let i = 0; i < images.length; i++) {
images[i].onclick = function() => {}
}
...where the query above returns all of the img tags that are descendants of the element with ID cmdt_1_1d, and reassigns each of their onclick listeners to an empty function. Therefore no actions will take place when those images are clicked.

Categories