JQuery on adding to optgroup trigger event - javascript

I have a select box which contains an optgroup. I need to add an event listener to it such as onclick, or onchange that will fire an event, but only when I add a new option into it.
Here's how I'm selecting it:
var $selectedExam = $("#formExam_released"); //this is the <optgroup>
I tried
$selectedExam.on("change", function(){
removeDuplicates('exam');
});
but that will trigger "removeDuplicates" only when I click on an item in the optgroup.
Any ideas?

Something like this?
$().ready(function() {
$("optgroup").each(function() {
$(this).on("change", function() {
var id = $(this).attr(id);
var arrrayOfElements = [];
$("optgroup").each(function() {
if($(this).attr("id") == id) {
$(this + " option").each(function() {
arrrayOfElements[arrrayOfElements.length] = $(this).val();
});
}
});
for (var i = 0; i < arrrayOfElements.length; i++) {
for(var j = 0; j < arrrayOfElements.length; j++) {
if(arrrayOfElements[i] == arrrayOfElements[j]) {
$("optgroup option[value='"+ arrrayOfElements[i] +"']").each(function() {
$(this).remove();
});
}
}
}
});
});
});
This code should remove all duplicated from the select options. This could be trigerred on the .on("change",...);
After edit, as long you add attribute ID with unique identifier you could search for this value.

Related

Set CSS property with pure JS, display:none

I need to hide a <section> in my HTML with JavaScript while highlighting the text or to show it otherwise.
My selection works in this way:
document.addEventListener('click', function(){
var selected = window.getSelection();
var links = document.getElementsByClassName("linkAnnotation");
if (selected == '') {
links.setAttribute('style', 'display:block;');
} else {
links.setAttribute('style', 'display:none;');
}
})
but this setAttribute does not work as other hundreds of tries that I have done.
Can someone save my life??
Every setAttribute, style.innerHTML, etc.
when you are selecting links it retuns HTMLCollection forExample : [linkAnnotation1, linkAnnotation2] it not returns one element because your code doesnot works you must write for loop example:
document.addEventListener('click', function () {
var selected = window.getSelection();
var links = document.getElementsByClassName('linkAnnotation')
if (selected == '') {
for (let i = 0; i <= links.length - 1; i++) {
links[i].setAttribute('style', 'display:block')
}
}else {
for(let i = 0; i <= links.length - 1; i++) {
links[i].setAttribute('style', 'display:none')
}
}
})
getElementsByClassName returns a HTMLCollection (Which returns an array-like object of all child elements which have all of the given class name(s)). You have to iterate through all of those elements and change properties.
So, you have to use the following code:
document.addEventListener('click', function() {
var selected = window.getSelection();
var links = document.getElementsByClassName("linkAnnotation");
if (selected === '') {
links.forEach(val => { val.setAttribute('style', 'display:block;'); });
} else {
links.forEach(val => { val.setAttribute('style', 'display:none;'); });
}
})

todolist double click to add class?

I am making a todo list... When the task is finished i need to be able to click it and then add a class to that item... It works but I have to double click.. Any suggestions?
list.onclick = function() {
var list = document.getElementsByTagName('li');
for (var i = 0; i < list.length; i++) {
list[i].onclick = function() {
if (!this.classList.contains("checked") || this.classList.contains("checked")) {
this.classList.add("checked");
} else {
this.classList.remove("checked");
}
}
}
}
As I understand purpose of this function is to check or uncheck list element each time user clicks on it. For this purpose, first of all we need to identify if 'class' exists or not and remove it. In other cases just add that 'class' to classList attribute.
list.onclick = function()
{
var list = document.getElementsByTagName('li');
for (var i = 0; i < list.length; i++)
{
list[i].onclick = function()
{
if (this.classList.contains("checked")
{
this.classList.remove("checked");
}
else
{
this.classList.add("checked");
}
}
}
}

Values selected in select box cannot be retrieved- jQuery

I am building an application in which I have table with form elements like select, input etc. I want to populate the values selected in form elements to another table.
You can find my code here
JS:
$('button').click(function() {
var rows = $('#table1 tbody tr');
var previewTable = $('#table2 tbody');
previewTable.find('tr').remove();
for (var i = 0; i < rows.length; i++) {
var tr = $('<tr> </tr>');
previewTable.append(tr);
var row_cloned = $(rows[i]).clone();
var cols = rows[i].getElementsByTagName("td");
for (var j = 0; j < cols.length; j++) {
var col_cloned = row_cloned.find('td').clone();
previewTable.find('tr').eq(i).append(col_cloned[j]);
if ($(col_cloned[j]).children().length > 0) {
$(col_cloned[j]).children().each(function(index, item) {
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).val());
}
} else if ($(item).is('label')) {
var selected = [];
$(item).find('input:checked').each(function(index, item) {
selected.push($(item).val());
$(col_cloned[j]).append(selected + '<br>');
})
}
})
} else {
$(col_cloned[j]).text($(col_cloned[j]).text());
}
}
}
})
My steps:
Get table1 and table2
Count the number of rows in the table1
Add so many empty rows in the table2
Get each row in table1
Count the td in each row of table1
Find the children in each td
Check if children is select, input, or just plain text
If children is select, determine if it is multi-select or single
Act accordingly for each form elements to copy only values and then append to table2
finish
All this on a button click COPY
Problem: Somehow managed to get the checked input form element values. But failing to get the values selected in select box.
For multi select box my code:
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
}
For single select box :
else {
$(col_cloned[j]).text($(item).val());
}
What is my mistake exactly? Thanks in Advance
For selected .val() does not work.You will have to use find() as in reality when you select a select box , its value does not change.
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
foo[i] = $(selected).find(":selected").text(); // see this
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).find(":selected").text()); // see this
}
For <select> you can't use val().
Using the .val() function on a multi-select list will return an array of the selected values:
This code:
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).val());
}
}
Change to this:
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = $('#multipleSelect').val();
$(col_cloned[j]).text(foo);
} else {
var optionSelected = $(item).find("option:selected");
$(col_cloned[j]).text(optionSelected.val());
}
}

Display the value on click of check box in an array

I have an array of 10 checkboxes. onclick of checkbox i want to get the value of that particular checkbox. That I am able to achieve using my code.When I click in serial order it is working fine. When I click on checkbox 5 after clicking on checkbox 7 the value of checkbox 5 ie..5 is getting added befor 7. I dont want in that order. I want the values to displayed in whatever order I click. My js file is as follows
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
function test() {
$('#catalog_table input:checkbox').change(function() {
var emails = [];
$('#catalog_table input:checkbox:checked').each(function() {
emails.push($(this).val());
});
var textField = document.getElementById("root");
textField.value = emails;
});
}
My HTML code is something like this
<table id="catalog_table"> </table>
<textarea id="root"></textarea>
Can any one please tell me how to do this?
Demo
Its messy, but it works:
http://jsfiddle.net/za7m8/1/
var selected = new Array();
$(document).ready(function(){
$("input[type='checkbox']").on('change', function() {
// check if we are adding, or removing a selected item
if ($(this).is(":checked")) {
selected.push($(this).val());
} else {
for(var i = 0; i<selected.length;i++) {
if (selected[i] == $(this).val()) {
// remove the item from the array
selected.splice(i, 1);
}
}
}
// output selected
var output = "";
for (var o = 0; o<selected.length; o++) {
if (output.length) {
output += ", " + selected[o];
} else {
output += selected[o];
}
}
$("#root").val(output);
});
});
You just have to change your javascript like this.
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
var emails = [];
function test() {
$('#catalog_table input:checkbox').change(function() {
if (this.checked)
{
if ( emails.indexOf( $(this).val() ) === -1 )
{
emails.push($(this).val());
}
} else
{
if ( emails.indexOf( $(this).val() ) !== -1 )
{
var index = emails.indexOf( $(this).val() );
emails.splice(index, 1);
}
}
var textField = document.getElementById("root");
textField.value = emails;
});
}
You need to clear up your code a bit, like this:
I assume that unchecking removes the value from the array, and checking adds.
var selected = new Array(); // What for is this here ?
$(document).ready(function () {
checkBoxTest();
});
function checkBoxTest() {
for (i = 0; i < 10; i++) {
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' + i + ' "/><td></tr>');
}
test();
}
function test() {
var emails = [],
textField = document.getElementById("root");
$('#catalog_table input:checkbox').change(function () {
var val = $(this).val();
// if you don't want removal of values on `uncheck`, comment out everything below excluding `emails.push(val)` and the last line
if(this.checked){ // if checked
emails.push(val); // add it
}else{
emails.splice(emails.indexOf(val), 1); // remove it if not checked
}
textField.value = emails; // set the value
});
}
DEMO

How to disable the hyperlinks in a div

How can I disable all hyperlinks in a div element? I don't want any active links in my div(editable).
jQuery:
$("#myEditableDiv a").click(function(e){ e.preventDefault(); });
Old and considered bad.
$("#myEditableDiv a").click(function(){ return false; });
using javascript you can write a simple method as given below -
function disableLinksByElement(el) {
if (document.getElementById && document.getElementsByTagName) {
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
var anchors = el.getElementsByTagName('a');
for (var i=0, end=anchors.length; i<end; i++) {
anchors[i].onclick = function() {
return false;
};
}
}
}
//Call to function as
disableLinksByElement('mydiv');
First grab all the links.
var links = editable.getElementsByTagName('a'); // where "editable" is a var pointing to your div
Then set the onclick to false.
for (var i = 0; i < links.length; i++) {
var link = links[i];
link.onclick = function() { return false; };
}

Categories