Value from HTML to another via registered element - javascript

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");

Related

How to select/Deselect all checkboxes in oracle apex form

I have a page region in Oracle Apex, that contains many checkboxes (apex form).
I want a functionality to add a checkbox at the header of every checkbox item, that will Select/Deselect all the checkbox items underneath.
I am new to Apex development, and need help on this.
Here's a solution that assumes the text above the checkboxes is from the item's label (somehow I don't think that's the case). If needed, I can update the answer to better fit your page when I know more about it.
First, go into each checkbox where you want to add this "toggle" functionality. Scroll down to the CSS Classes attribute and put toggle-cb in the field.
Next, go to the page level attributes and add the following code to the Function and Global Variable Declaration attribute:
function enableToggle() {
var $wrapperDiv = $(this);
var $label = $wrapperDiv.find('.t-Form-label');
var $item = $wrapperDiv.find('.apex-item-checkbox');
var buttonHtml = '<button type="button" class="t-Button t-Button--tiny t-Button--simple">Toggle all</button>';
$label.html($label.text() + ' ' + buttonHtml);
$label.find('button').on('click', function(event) {
var $button = $(this);
var $checkboxes = $item.find('input[type="checkbox"]');
var checkedCount = $checkboxes.filter(function() {
return this.checked === true;
}).length;
var check = checkedCount < $checkboxes.length;
$checkboxes.each(function() {
this.checked = check;
});
event.stopPropagation();
$button.blur();
});
}
Finally, add the following code to the Execute when Page Loads attribute of the page:
$('.toggle-cb').each(enableToggle);
This will add a button to each item's label (provided the checkbox has the toggle-cb class) that does the toggle:
See the following to learn more about the code used above:
https://www.youtube.com/watch?v=Pjur4Zkkwsk&list=PLUo-NIMouZ_sgdQpMbXXwhHKpwRggCY34&index=1

Using click events on dynamically added DOM elements

Question: Why does it work when element is hard-coded into HTML but does not work when added dynamically via Jquery?
I am teaching my self Jquery within my self learning of javascript, and I am just creating a simple troubleshooting assistant app for the sake of learning.
I actually have my code posted here: https://repl.it/#jllrk1/OrganicBothRay.
The way I have it set up so far is the user clicks on the header block to begin, which is set up with a onetime click function to create a UL for some products at my job in which we provide IT Service.
I then am trying to be able to click each product in that list to pull troubleshooting walkthroughs for that specific product (it will guide the user based on what they click or enter).
For testing purposes I just tried having the background of the list item in which is clicked to change to red.
I cannot get this to work, or my console.log to fire telling me that the function is not getting called.
however, if I hard code in the ul into the html, using the same code for the click events, it works just fine.
Am I doing something wrong?
Just looking to gain a better understanding!
$(function () {
//*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_
//set up variables
//*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_
//var $liItems = $('.product li');
var $chief = $(".chiefblock");
var $container = $("#container");
var $this = $(this);
var $error = '';
var initList = function () {
console.log("initList initiated");
$container.append('<div class="product"><ul><li>TASC</li><li>TABE</li><li>Las Links</li><li>TerraNova</li><li>E-Direct</li></ul></div>');
$("p").text("Start by selecting a product");
}
var navItems = function (event){
console.log("navItems initiated");
var target = $(event.target);
if (target.is("li") ) {
target.css("background-color", "red" );
}
}
var nObject = function () {
$container.append('<div id = "tasc"><h2>Tasc</h2><p></p></div></div>');
$('#newItem').prepend('<h2>Item</h2>');
}
$('.chiefblock').one('click', initList)
//$('li').on('click', navItems) this i tried and does not work
$('#newObject').on('click', nObject)
$('ul').on('click', navItems)
//$liItems.on('click', navItems)this i tried and does not work
});
for dynamically added DOM elements use
$(document).on('click', '#element', function() {
console.log($(this))
})

Troubleshooting Conditional Form

I'm new to Javascript and trying to build a conditional form using bootstrap and JQuery. I would really appreciate the help as I've been working most of the day on this to no avail.
I'm trying to show the div with id physician (and subsequent field) when the select field with the name AppointmentType has a value of Orthopedic or Rheumatology. Here is the link to the live form.
Here is my javascript:
$( document ).ready(function() { //wait until body loads
//Inputs that determine what fields to show
var appttype = $('#secureform input:select[name=AppointmentType]');
var physician = document.getElementById("physician");
appttype.change(function(){ //when the Appointment Type changes
var value=this.value;
physician.addClass('hidden'); //hide everything and reveal as needed
if (value === 'Orthopedic' || value === 'Rheumatology'){
physician.removeClass('hidden'); //show doctors
}
else {}
});
});
These lines are going to cause errors (which you should see in your devtools console):
var appttype = $('#secureform input:select[name=AppointmentType]'); // `input:select` is not a valid selector and causes the rest of the script to fail
physician.addClass('hidden'); // `addClass` is a jQuery method, so this should be `$(physician).addClass('hidden')`
physician.removeClass('hidden');// `removeClass` is a jQuery method, so this should be `$(physician).removeClass('hidden')`
Correct those lines and it should work.
If it helps, I would write it like this:
$( document ).ready(function () {
//Inputs that determine what fields to show
var apptType = $('#secureform select[name="AppointmentType"]'); // dropped the `input:` part
var physician = document.getElementById('physician');
physician.classList.add('hidden'); //hide this initially, outside the change handler
apptType.change(function () { // when the Appointment Type changes
var value = $(this).val().toLowerCase(); // leave case-sensitivity out of it.
var showables = [ // using an array as I prefer using a simple `indexOf` for multiple comparisons
'orthopedic',
'rheumatology',
];
var isShowable = showables.indexOf(value) > -1;
physician.classList.toggle('hidden', !isShowable);
// or, the jQuery equivalent:
// $(physician).toggleClass('hidden', !isShowable);
});
});
Your selector is incorrect:
var appttype = $('#secureform input:select[name=AppointmentType]');
// this should be
var appttype = $('#secureform select[name=AppointmentType]');
Furthermore you are mixing jquery with vanilla JS. Your are using vanilla js here
var physician = document.getElementById("physician");
Physician is now a dom object and not a jquery object. You should use this instead:
var physician = $("#physician");
Additionally you should replace
var value=this.value;
with this
var value= $(this).val();

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

How to copy another elements onclick function

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')();}">

Categories