Referencing parameters in the CSS section of a jQuery function - javascript

This function toggles all checkboxes in a given column of an HTML table when selecting or deselecting a checkbox.
function GlobalCheckboxSwitch0(checkboxID, tableID)
{
if ($(checkboxID).is(':checked'))
{
$('#table0 input[type=checkbox]').each(function ()
{
$(this).prop("checked", true);
});
}
else
{
$('#table0 input[type=checkbox]').each(function ()
{
$(this).prop("checked", false);
});
}
}
Invoking it like this works only for table0:
<input type="checkbox" id="selectall0" onClick="GlobalCheckboxSwitch0('#selectall0', '#table0')">
The problem is that table0 is hard coded in the function.
With the help of the second parameter tableID I would like it to work for any table ID.
selectall0 is the ID of the checkbox.
Trying to refer the tableID parameter like this:
$('$(tableID) input[type=checkbox]')
yields a syntax error.
What should I change in the way I refer to tableID?
Thank you.

Use the tableID selector the same way you do for checkboxID along with find().
You can also skip the if and the each and do the following:
function GlobalCheckboxSwitch0(checkboxID, tableID) {
var allChecked = $(checkboxID).is(':checked');
$(tableID).find('input[type=checkbox]').prop('checked', allChecked );
}
jQuery will do the each internally

It's a jQuery selector syntax error, to be precise - it's not actually a JavaScript syntax error.
You need to learn concatenation, which means joining strings and variables/expressions.
As it stands...
$('$(tableID) input[type=checkbox]')
...will be executed literally. In other words, you're telling jQuery to go find an element whose tag name is tableID.
Instead you need to concatenate between the formulaic and dynamic parts of the jQuery selector. Concatenation in JavaScript is done via +.
$('#'+tableID+' input[type=checkbox]') //<-- note #

Related

How to apply range of values to a partial attribute selector? [duplicate]

I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.
I have looked for this myself but have been unable to find information on the syntax and how to use it. Does anyone know where the documentation for the syntax is?
EDIT: The attribute filters allow you to select based on patterns of an attribute value.
You can use the filter function to apply more complicated regex matching.
Here's an example which would just match the first three divs:
$('div')
.filter(function() {
return this.id.match(/abc+d/);
})
.html("Matched!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="abcd">Not matched</div>
<div id="abccd">Not matched</div>
<div id="abcccd">Not matched</div>
<div id="abd">Not matched</div>
James Padolsey created a wonderful filter that allows regex to be used for selection.
Say you have the following div:
<div class="asdf">
Padolsey's :regex filter can select it like so:
$("div:regex(class, .*sd.*)")
Also, check the official documentation on selectors.
UPDATE: : syntax Deprecation JQuery 3.0
Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:
jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
return function (elem) {
var matchParams = expression.split(','),
validLabels = /^(data|css):/,
attr = {
method: matchParams[0].match(validLabels) ?
matchParams[0].split(':')[0] : 'attr',
property: matchParams.shift().replace(validLabels, '')
},
regexFlags = 'ig',
regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
return regex.test(jQuery(elem)[attr.method](attr.property));
}
});
These can be helpful.
If you're finding by Contains then it'll be like this
$("input[id*='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Starts With then it'll be like this
$("input[id^='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Ends With then it'll be like this
$("input[id$='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is not a given string
$("input[id!='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which name contains a given word, delimited by spaces
$("input[name~='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen
$("input[id|='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^ JQuery selector.
For example if your want to only select div with id starting with "abc", you can use:
$("div[id^='abc']")
A lot of very useful selectors to avoid use of regex can be find here: http://api.jquery.com/category/selectors/attribute-selectors/
var test = $('#id').attr('value').match(/[^a-z0-9 ]+/);
Here you go!
Add a jQuery function,
(function($){
$.fn.regex = function(pattern, fn, fn_a){
var fn = fn || $.fn.text;
return this.filter(function() {
return pattern.test(fn.apply($(this), fn_a));
});
};
})(jQuery);
Then,
$('span').regex(/Sent/)
will select all span elements with text matches /Sent/.
$('span').regex(/tooltip.year/, $.fn.attr, ['class'])
will select all span elements with their classes match /tooltip.year/.
ids and classes are still attributes, so you can apply a regexp attribute filter to them if you select accordingly. Read more here:
http://rosshawkins.net/archive/2011/10/14/jquery-wildcard-selectors-some-simple-examples.aspx
$("input[name='option[colour]'] :checked ")
I'm just giving my real time example:
In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".
document.querySelectorAll("[id^='select2-qownerName_select-result']");
When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.
$("[id^='select2-qownerName_select-result']")
If you just want to select elements that contain given string then you can use following selector:
$(':contains("search string")')

JavaScript - Find ID that matches data attribute value

I have a variable that finds the data attribute of an element that is clicked on in a callback function:
var dropdown = document.getElementsByClassName('js-dropdown');
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", callBack (dropdown[i]));
}
function callBack (i) {
return function () {
var thisDropdown = i.getAttribute('data-dropdown');
//rest of the code here
}
}
I am basically trying to do this
$('#' + thisDropdown ).toggleClass('is-active');
...but in vanilla JS.
This works fine using jQuery however I would like a vanilla version.
So when a user clicks on an element that activates a drop down, I want it to dynamically find its relevant ID matching value within the document so it can toggle a show/hide class.
I've searched through a lot of SO questions and everyone replies with a jQuery answer which is not what I am looking for.
I've been trying to do something along the lines of
var idValue = document.getElementById(thisDropdown);
Then
var findId= idValue + thisDropdown;
findId.toggleClass('is-active');
Obviously that does not work the same way the jQuery statement works... any ideas?
Ignore the toggleClass method! Some of you may find this contradictory as I want vanilla JS.
To replace $('#' + thisDropdown ).toggleClass('is-active'); with plain js, use Element.classList. Like this:
const someElement = document.querySelector('#' + thisDropdown);
someElement.classList.toggle("is-active");
I like #kamyl's answer, but you might need backward compatibility. For that, see if you can find a polyfill.
If you have to write it yourself, use string.split(" ") to get your list of active attributes and iterate to find if it exists; add if not, remove if so...then array.join(" ") and replace the class attribute with it.

Siblings give Object #<HTMLSelectElement> has no method 'each'

What am I missing here?
As part of an answer to How can i change options in dropdowns if it is generated dynamically?
I have an issue inside an onchange. I want to set all the siblings values to the value of the changed select
$("select").on("change",function() {
var idx=$(this).val();
console.log($(this).attr("id"),$(this).val())
$(this).siblings("select").each(function() {
$(this).val(idx);
});
});
Here is the generated code in a JSFIDDLE
I have seen
How do i get the value of all other dropdowns when one of them is changed
but I prefer to find the reason for my error
You are using the val method as a property.
var idx=$(this).val;
// ----^
http://jsfiddle.net/Vr5Je/
You can also use the val method instead of each:
$("select").on("change", function() {
$(this).siblings("select").val(this.value);
});
http://jsfiddle.net/Pq2vq/

Call a function on regex match

Is there a way to call a function when an id matches a regex?
I have an app where I have about 20 or so divs calling the same function by onclick and I'm trying to get rid of the onclicks and just find those divs by id. The divs id's start the same way for instance: sameId_xxx
This is what I have working but I was wondering if I could put the condition in the function call so it's not being called for every div on the page.
$("div").click(function () {
var id = this.id;
if (id.match(/sameId_/)) {
}
}
$('div[id^="sameId_"]').click(...)
Demo: http://jsfiddle.net/kpcxu/
For more info, see Attribute Starts With selector.
Try the jQuery 'attribute contains selector':
$('div[id*="sameId_"]').click(function() {
// Do stuff
});
I think better filter all div with using necessary condition and next add handler.
For example:
$('div')
.filter(function() { return $(this).attr('id') % 2 })
.click(function(){alert($(this).attr('id'))});​
Live demo on JSFiddle
Or you can use var id = $(this).attr('id') in your code.
I think the other answers (with filtering on the id up front) are better, but for posterity, here is what you actually asked for:
$("div").click(function () {
var id = this.id;
if (id.match(/(sameId_)(.)+/)) {
console.log("matched");
}
}​);​
where "sameId_" is a case sensitive representation of what you want to match.

How do I concatenate a string with a variable?

So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!

Categories