Currently I have this code to delete a table row:
var remove = document.getElementById(dataID); (this is the id of an object in the row I wish to hide)
if(remove!=null){
var v = remove.parentNode.parentNode.rowIndex;
document.getElementById(tid).deleteRow(v); (tid is the table id, not the row id)
}
However, instead of delete it, I'd just like to hide it. What's a good way to do this?
Also, in the future, I'm going to want to 'unhide' it at user request, so how can I check if it has been hidden? The if(remove!=null) is what checked if a row was already removed, so I'd need something similar.
Thank you for your time.
document.getElementById(tid).children[dataID].style.display = 'none';
You may need -1 on dataID
And block to show it again (or inline or whatever it originally was, for a div it's block).
JQuery:
$('#'+tid+':nth-child('+dataID+')').hide();
My own approach, in plain JavaScript:
function toggleRow(settings) {
// if there's no settings, we can do nothing, so return false:
if (!settings) {
return false;
}
// otherwise, if we have an origin,
// and that origin has a nodeType of 1 (so is an element-node):
else if (settings.origin && settings.origin.nodeType) {
// moving up through the ancestors of the origin, until
// we find a 'tr' element-node:
while (settings.origin.tagName.toLowerCase() !== 'tr') {
settings.origin = settings.origin.parentNode;
}
// if that tr element-node is hidden, we show it,
// otherwise we hide it:
settings.origin.style.display = settings.origin.style.display == 'none' ? 'table-row' : 'none';
}
// a simple test to see if we have an array, in the settings.arrayOf object,
// and that we have a relevant table to act upon:
else if ('join' in settings.arrayOf && settings.table) {
// iterate through that array:
for (var i = 0, len = settings.arrayOf.length; i < len; i++) {
// toggle the rows, of the indices supplied:
toggleRow({
origin: table.getElementsByTagName('tr')[parseInt(settings.arrayOf[i], 10)]
});
}
}
}
// you need an up-to-date browser (you could use 'document.getElementById()',
// but I'm also using 'addEventListener()', so it makes little difference:
var table = document.querySelector('#demo'),
button = document.querySelector('#toggle');
// binding a click event-handler to the 'table' element-node:
table.addEventListener('click', function (e) {
// caching the e.target node:
var t = e.target;
// making sure the element is a button, and has the class 'removeRow':
if (t.tagName.toLowerCase() === 'button' && t.classList.contains('removeRow')) {
// calling the function, setting the 'origin' property of the object:
toggleRow({
origin: t
});
}
});
// binding click-handler to the button:
button.addEventListener('click', function () {
// calling the function, setting the 'arrayOf' and 'table' properties:
toggleRow({
'arrayOf': document.querySelector('#input').value.split(/\s+/) || false,
'table': table
});
});
JS Fiddle demo.
References:
document.querySelector().
e.target.addEventListener().
Node.nodeType.
String.split().
As you've asked for a jQuery solution...how about
var $remove = $('#' + dataID);
if ($remove) {
$remove.closest('tr').closest().hide();
}
?
Related
my concern is there is a list and every list item has a button in front of them so i have to perform some action when user click on the button ,so how can i target the multiple buttons with same class_Name in java_script, Here is my j_s code =
function getActiveCampaigns() {
fetch('http://example/api/sign/in', {
method: 'GET',
headers: {
token: "token"
}
}).then(
res => {
res.json().then(
data => {
console.log(data.response.campaign, 'campaign');
if (data.response.campaign.length > 0) {
let temp = "";
data.response.campaign.forEach((itemData) => {
temp += "<ul>";
temp += "<li>" + itemData.name + "</li>";
temp += '<li><button class="btn1">Add to campaigns</button></li></ul>'
});
document.getElementById("ds").innerHTML = temp;
}
}
)
}
)
}
this code is that i have been tried but did not worked=
$("btn1").each(function click1(index, element) {
var clas = $(element).attr("class");
if(clas.length > 2) {
// do something
console.log("Hello World!");
}
});
A single click event listener can handle 1, 10, or 1,000 buttons with ease.
In my snippet, most of the code is concerned with creating and displaying 20 li elements, each with a button and some text.
A single click event listener handles clicks on any of the buttons. I've used an AND conditional to process the subset of events that occur on a button AND that are in a li of the correct class name (incase you have multiple lists and want to do different things on each. This is the event listener:
document.addEventListener('click', event => {
if (event.target.tagName == 'BUTTON' && event.target.parentElement.className == 'list-item') {
// stuff to execute
alert(`${event.target.innerHTML} button pressed`);
} // end if;
}); // end event listener;
Any number of if blocks could be added to the same event listener to deal with any other parts of the page for which you wish to process click events.
Note, no ids or anything complicated was needed to distinguish the target from others (that is the job of the lisener). This example didn't even need a class attribute but I included it so you can see how extra specificty can be achieved (e.g. you might have two lists with buttons and want to do different things with them).
Here is the working snippet:
let list = document.getElementsByTagName('ul')[0];
for (let i=0; i<20; i++) {
let listItem = document.createElement('li');
listItem.setAttribute("class", "list-item");
listItem.innerHTML = `<button>element ${i}</button> list item ${i}`;
list.appendChild(listItem);
} // next.
document.addEventListener('click', event => {
if (event.target.tagName == 'BUTTON' && event.target.parentElement.className == 'list-item') {
// stuff to execute
alert(`${event.target.innerHTML} button pressed`);
}
});
<ul>
</ul>
const collection = document.getElementsByClassName("classname");
getElementsByClassName method returns 'an array' ("a live HTMLCollection, which is very similar to an array" - user1599011) . You can iterate thru it like
foreach (element in array) {
Do anything with element}
In HTML5 I have a dropdown menu . When choosing different options I hide or show different parts of my page. Here is that script:
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
However what I want to do now, in another script is to preload an option from the dropdown. I can do it easily with this script:
setSelectedIndex(document.getElementById('target'),'content_1');
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
This is where my problem comes up, my dropdow will get the value I want, but the part that I want to be shown when choosing that option won't come up.
That is because change events need to happen from the browser.
When the user commits the change explicitly (e.g. by selecting a value
from a 's dropdown with a mouse click, by selecting a date
from a date picker for , by selecting a file in the
file picker for , etc.);
If your using Jquery you can:
$("#id").val("value").trigger('change');
or you can use javascript if your not worried about building the event object:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
I would recommend moving your anonymous onchange function into a named function that you can call once onload, and again onchange.
Here is the function I wrote:
function setContent(id) {
//get the current visible content
var vis = document.querySelector('.vis');
//get the target element by id
var target = document.getElementById(id);
//make current vis element inv
if (vis) vis.className = "inv";
//make target element vis
if (target) target.className = 'vis';
}
and a fiddle
edited: got rid of querySelectorAll to stick closer to OP original code and updated fiddle. clarified and commented code.
The problem you have is changing a vale or the selected value of an input with JavaScript does not trigger any change event. So you would need to manually trigger the event.
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
//Setting the selected value with JavaScript does not trigger the change event so you need to manually trigger the change event
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
s.dispatchEvent(evt);
} else {
s.fireEvent("onchange");
}
return;
}
I have a selected object that was clicked. When this happens, i would like to retrieve the object and then find the children with a specific class value so i can disable them.
I am able to get the object but when i access the children i always get "undefined" even though i can see the children.
I browsed the object and i can see the class attributes values i am looking for.
Can somebody please tell me if i am referencing this correctly?
Below is my code,
The specific line with the issue is,
var kids = clicked_obj.children('.ui-selected');
// manually trigger the "select" of clicked elements
$(".page").click(function (e) {
console.log(e);
//var selected_divs = $(".page").find("div[class*='ui-selected']");
var selected_divs = $(".page").find(".existingFieldItem.ui-selected");
selected_divs.each(function () {
if (e.ctrlKey == true) {
var clicked_obj = e.target.parentElement;
var kids = clicked_obj.children('.ui-selected');
console.log("Ctrl clicked");
console.log($(this).attr("id"));
kids.each(function () {
$(this).removeClass("ui-selected");
});
// if command key is pressed don't deselect existing elements
$(this).removeClass("ui-selected");
$(this).addClass("ui-selecting");
}
else {
if ($(this).hasClass("ui-selected")) {
// remove selected class from element if already selected
$(this).removeClass("ui-selected");
}
else {
// add selecting class if not
$(this).addClass("ui-selecting");
}
}
});
$(".page").data("ui-selectable")._mouseStop(null);
});
});
You're missing a jQuery selection:
var clicked_obj = $(e.target.parentElement);
e.target.parentElement is a DOM element object, not a jQuery selection.
I'm having this webpage
http://pocolocoadventures.be/reizen/
And it should filter (with isotope.js) the travelboxes on the page.It does in safari, chrome, firefox, opera, .. but in IE, the filter doesn't work. Even worse, JS doesn't react at all at a click event on te span.
This is the piece of js
// Travel Isotope
var container = $('#travel-wrap');
container.isotope({
animationEngine : 'best-available',
itemSelector: '.travel-box ',
animationOptions : {
duration : 200,
queue : false
},
});
$(".filters span").click(function(){
var elfilters = $(this).parents().eq(1);
if( (elfilters.attr("id") == "alleReizen") && elfilters.hasClass("non-active") )
{
$(".label").each(function(){
inActive( $(this) );
});
setActive(elfilters);
}
else{
//set label alleReizen inactive
inActive( $("#alleReizen") );
if( elfilters.hasClass("non-active") ){
setActive(elfilters);
}
else{
inActive(elfilters);
}
}
checkFilter();
var filters=[];
$(".search.filters").children().each(function(){
var filter = $(this).children().children().attr("data-filter");
if( $(this).hasClass("non-active") ){
filters = jQuery.grep(filters, function(value){
return value != filter;
});
}
else{
if(jQuery.inArray(filter,filters) == -1){
filters.push(filter);
}
}
});
filters = filters.join("");
filterItems(filters);
});
function filterItems(filters){
console.log("filter items with filters:" + filters);
container.isotope({
filter : filters,
}, function noResultsCheck(){
var numItems = $('.travel-box:not(.isotope-hidden)').length;
if (numItems == 0) {
$("#no-results").fadeIn();
$("#no-results").css("display", "block");
}
else{
$("#no-results").fadeOut();
$("#no-results").css("display", "none");
}
});
}
function setActive(el){
el.removeClass("non-active");
var span = el.find('i');
span.removeClass("fa-check-circle-o").addClass("fa-ban");
}
function inActive(el){
el.addClass("non-active");
var span = el.find('i');
span.removeClass("fa-ban").addClass("fa-check-circle-o")
}
function checkFilter(){
var filterdivs = $('.filters span').parent().parent();
if( filterdivs.not('.non-active').length == 0 ){
setActive( $("#alleReizen") );
}
var filterLabels = $(".filters .label");
if( filterLabels.not('.non-active').length == 0){
setActive( $("#alleReizen") );
}
}
function noResultsCheck() {
var numItems = $('.item:not(.isotope-hidden)').length;
if (numItems == 0) {
//do something here, like turn on a div, or insert a msg with jQuery's .html() function
alert("There are no results");
}
}
Probably something small and stupid; but I can't find it..
Thanks in advance!
On your website you've build the buttons like this:
<button>
<span>
</span>
</button>
Now the button element is designed to be a button. It differs from the input button. In the latter you'd set the caption using value. In the button element you set it as a text node. The button element can contain elements like a span. The spec isn't very clear about whether or not you should have event handlers on the children of the button element. It's a browser developers interpretation of allowing it or not.
This problem has been posted here before (a few times)
span inside button, is not clickable in ff
Missing click event for <span> inside <button> element on firefox
It seems that Firefox is allowing it, based upon your findings. IE isn't. So to be on the safe side: use the button the way it was intended.
Wrap the button inside a span (not really logical)
Put the click handler on the button.
$(".filters button").click(...);
played around in the console a bit, and this seemed to work well.
$(".filters").on('click', 'span', function(){
// foo here
console.log('foo');
});
Maybe the filters are manipulated by one of your js files after page load?
.on will allow you to select a container which listens on changes that happen inside it, passing the element you want the actual action to work on.
If it's ok for you, I'd suggest to use the <button> element, instead of the <span>.
Let me know if that works for you.
I am trying to get checked options from a table which are set inline. There is a search function, which sets $(element).css('display','none') on objects in which there is no match with the search. Anyways, this piece of code will only return inline, no matter what the elements are set to. Even if I manually set all of them to display: none in the table itself, the alert will return inline for every single object in the table. Is there any solution to this?
JS code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).css('display') === 'inline') {
array.push($(this).val());
}
});
}
Fundamentally, css("display") does work, so something else is going on.
I suspect one of two things:
The checkboxes that you're making display: none are never checked, and so you don't see them in your each loop.
You're not making the checkboxes display: none, but instead doing that to some ancestor element of them. In that case, $(this).is(":visible") is what you're looking for.
Here's an example of #2: Live Copy | Live Source
<div id="ancestor">
<input type="checkbox" checked>
</div>
<script>
$("#ancestor").css("display", "none");
console.log("display property is now: " +
$("input:checkbox:checked").css("display"));
console.log("visible tells us what's going on: " +
$("input:checkbox:checked").is(":visible"));
</script>
...which outputs:
display property is now: inline-block
visible tells us what's going on: false
Applying that to your code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).is(':visible')) {
// Change is here -----------------^^^^^^^^^^^^^^
array.push($(this).val());
}
});
}
Side note: Every time you call $(), jQuery has to do some work. When you find yourself calling it repeatedly in the same scope, probably best to do that work once:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
var $this = $(this); // <=== Once
i++;
alert($this.css('display'));
if ($this.val() !== 0 && $this.is(':visible')) {
// Other change is here -------^^^^^^^^^^^^^^
array.push($this.val());
}
});
}
try following:
$("input:checkbox:checked").each(function(i,o){
console.log($(this).css("display"));
});
working fiddle here: http://jsfiddle.net/BcfvR/2/