How to remove some item based on ID - javascript

I am getting all file upload control through the following code
var fileuploadControls = $( "input[type='file']" );
Now I want to loop thorugh the fileuploadControls and remove if ID is not matching something like this
for(var i=0;i<fileuploadControls .length;++i)
{
if(fileuploadControls[i].id != "A")
{
//remove the item and fileUploadcontrols should be same type of abject as returned by the jquery not an array
}
}
I have tried splice it works but it returns an array which I don't want after removal of item fileuploadControls should of same type of object as it was before removal only one item should be less
Can someone help in coding this
I am using the following celltemplate in Angular ui-grid
cellTemplate: '<div class="ui-grid-cell-contents"> <input name="curfewRegularizationFile" id="curfewRegularizationFile" type="file" class="k-state-disabled" /></div>',
and in javascript file I am doing this
fileuploadControls[i].kendoUpload({ // Do something as per kendo});

You can can create a function to remove element
for(var i=0;i<fileuploadControls .length;++i)
{
if(fileuploadControls[i].id != "A")
{
remove(fileuploadControls[i].id);
}
}
function remove(id) {
return (el=document.getElementById(id)).parentNode.removeChild(el);
}

Remove from DOM too:
In your loop you can do it this way:
for(var i = 0; i < fileuploadControls.length; ++i ) {
if( fileuploadControls[i].id !== "A" )
fileuploadControls.eq(i).remove();
}
But I would do it in the jQuery way, in a loop with jQuery objects you can do it with each. But this is even the slowest option to choose.
fileuploadControls.each(function() {
if( $(this).attr("id") !== "A" )
$(this).remove();
});
Or directly as a sub-selector:
fileuploadControls.not("#A").remove();
Remove only from Object:
By better initial selector:
var fileuploadControls = $("input[type=file]:not(#A)");
By trim down the jQuery object:
fileuploadControls = fileuploadControls.not("#A");
By filter:
fileuploadControls = fileuploadControls.filter(function() {
return $(this).attr("id") !== "A";
});

Related

converting javascript to jquery function not correctly working

I am trying to convert a small script from javascript to jquery, but I don't know where I should be putting the [i] in jquery?. I am nearly there, I just need someone to point out where I have gone wrong.
This script expands a search input when focused, if the input contains any values, it retains it's expanded state, or else if the entry is removed and clicks elsewhere, it will snap back.
Here is the javascript:
const searchInput = document.querySelectorAll('.search');
for (i = 0; i < searchInput.length; ++i) {
searchInput[i].addEventListener("change", function() {
if(this.value == '') {
this.classList.remove('not-empty')
} else {
this.classList.add('not-empty')
}
});
}
and converting to jquery:
var $searchInput = $(".search");
for (i = 0; i < $searchInput.length; ++i) {
$searchInput.on("change", function () {
if ($(this).value == "") {
$(this).removeClass("not-empty");
} else {
$(this).addClass("not-empty");
}
});
}
Note the key benefit of jQuery that it works on collections of elements: methods such as .on automatically loop over the collection, so you don't need any more than this:
$('.search').on("change", function() {
this.classList.toggle('not-empty', this.value != "");
});
This adds a change event listener for each of the .search elements. I've used classList.toggle as it accepts a second argument telling it whether to add or remove the class, so the if statement isn't needed either.

get index of input element in javascript

If I have 3 input boxes on a web page and the user clicks the second input, I need to get the input index, the position of the input on the page. I need it in pure javascript. This is what I have so far but it doesn't work...
document.querySelector('html').onclick = function (e) {
log(e);
}
function log(obj) {
var nodeName = obj.target.nodeName
var idx = nodeName.length
console.log(nodeName, idx);
}
Any help would be appreciated!
Pure javascript:
function getIndexFromSet(set, elm){
var setArr = [].slice.call(set);
for( var i in setArr )
if( setArr[i] == elm )
return i;
}
The above function can be used like so:
function checkInputFocus(e){
if(e.target && e.target.nodeName == 'input' )
index = getIndexFromSet(inputs, e.target);
}
var inputs = document.querySelectorAll('input');
document.addEventListener("click", checkInputFocus);
using jQuery, if you run this on this page (in your console)
var inputs = $('input'); // get all input elements on the page
inputs.index( $('#save-pinned-sites-btn') ); // find the index of spesific one
you will get a number representing the index of an $('#save-pinned-sites-btn') element
Inline:
<input onclick="for(i=0;i<this.parentNode.getElementsByTagName('input').length;i++){if(this==this.parentNode.getElementsByTagName('input')[i]){alert(i);}}">
Or change that to
onclick="show_index(this)"
And Add:
function show_index(which) {
for(i=0;i<which.parentNode.getElementsByTagName('input').length;i++){
if(which==which.parentNode.getElementsByTagName('input')[i]){
alert(i);
}}

jQuery check if class exists or has more than one class

I have a class js-bootstrap3 that is generated by a cms. What I need to do is check if the containing element just has js-bootstrap3and .unwrap() the contents, but if the element has multiple classes which include js-bootstrap3 then I'm trying to just remove that class.
jsFiddle
$('.jsn-bootstrap3').each(function(){
if( $(this).attr('class') !== undefined && $(this).attr('class').match(/jsn-bootstrap3/) ) {
console.log("match");
$(this).contents().unwrap();
$(this).removeClass('jsn-bootstrap3');
}
});
This just seems to detect any element with js-bootstrap3as a class and unwraps it.
this.className is a string with all of the classes for the element (space delimited), so if it's not just "jsn-bootstrap3" you know it has more than one class:
$('.jsn-bootstrap3').each(function(){
if( $.trim(this.className) !== "jsn-bootstrap3") {
// Just jsn-bootstrap3
$(this).contents().unwrap();
} else {
// More than just jsn-bootstarp3
$(this).removeClass('jsn-bootstrap3');
}
});
Dependeing on the browsers you need to support element.classlist (IE10+) might or might not be what you need.
classList returns a token list of the class attribute of the element.
classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.className. It contains the following methods:
Otherwise you're looking at splitting the className into an array like so to count the values:
var classes = element.className.split(" ");
Building on your example you could do something liket his:
$('.jsn-bootstrap3').each(function(i, el){
if( el.className.indexOf('jsn-bootstrap3') != -1 ) {
console.log("match");
if ( el.className.split(" ").length > 1 ) {
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
}
});
Try this code.
$(document).ready(function(){
$('.jsn-bootstrap3').each(function(){
var classes = $(this).attr('class');
var new_cls = classes.split(' ');
if( new_cls.length > 1 ){
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
});
});

Hide/unhide table row given the row index and table ID

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

jQuery.css('display') only returns inline

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/

Categories