Can't get elements with specific id as attribute 'data-parent' - javascript

I have a element like this
<input type="checkbox" data-parent="0" value="1229">
and I want to get all the checkboxes with data-parent that have a value of N.
Here is what I tried in my click event handler method.
checkChildren = function (id) {
var cbs = $(input[type="checkbox"][data-parent=id]);
}
but there is some syntax error near 'data-parent=id'

Your CSS selector is wrong. Change it to:
var cbs = $('input[type="checkbox"][data-parent="' + id + '"]');

you need to pass a string selector to jquery, first building it with a javascript expression
additionally, the html tag attribute values ("checkbox" and "0") need to both be quoted
var selector = 'input[type="checkbox"][data-parent="' + id + '"]';
var cbs = $(selector);
edit, details why:
input[type="checkbox"][data-parent=id]
when the javascript parser hits this, it tries to execute it as javascript code, and give the result to $().
Here's what it (javascript parsing engine) tries:
looks for a variable named input
Finds an opening bracket [ after the input object and evaluates the contents, type="checkbox"
(this operation sets the variable type to the string "checkbox" and returns the string "checkbox")
substitutes the returned value into the first brackets, input["checkbox"]
(the bracket operator looks up the checkbox property of the input object, like input.checkbox, and returns the value of the property or undefined)
Similarly evaluates for the second set of brackets value[data-parent=id]
(but this time runs into an error because data-parent=id is ambiguous, it's trying to set the result of subtract parent from data to the variable id)

Related

Can I use the % symbol in javascript or it is considered aspecial character?

I need some help.
I need to know if it is possible to use the % symbol in javascript.
I ask this question because I have an html table with the following ID= MRRMFBSY_%_CEC.
When I try to keep the TD of the second TR of this table the results is undefined, so it seems that it doesnt find the Table with this ID and also when it is defined well.
See my code below:
function getColumnsVal(id) {
var header = $("table#" + id + " thead tr:eq(1)");
var header_fields = $("td", header);
// If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD,
// example the firstone it returns undefined
alert(header_fields[0]);
}
The question if you think that the problem is the % symbol or not, because when I have the other ID it works perfectly.
Thanks in advance
% is a reserved character, since its an operator (see).
It's not recommended, but you can use it as ID in an HTML element.
See this example:
const element = document.getElementById('MRRMFBSY_%_CEC');
console.log(element); // returns the div element
<div id="MRRMFBSY_%_CEC">
My div with a specific ID
</div>
ISSUE:
There is a problem when using certain special symbols %, ^, +, #, and so on, inside a jquery selector. They should be escaped with a backslash(\) when used because they are also used in forming the queries for the selector.
For instance '#divid' is a valid string in JavaScript but would be confusing to use in jQuery if the string was an actual id of an element. To get this element you have to use
$('#\#divid').
So, in your case to get your target element, $('#MRRMFBSY_\%_CEC') will get the element easily. However, you can either insert the escape character(\) manually or programmatically as done in this post with regular expression. Therefore, using the square brackets or the native getElementById in this answer, is just another way out of this problem.
You can definitely use % symbol in an id attribute (or in any string) as you would use the dash symbol -. However, you cannot use either of both for JavaScript variable names as they are reserved symbols.
SOLUTION:
Though this question has its own intricacies, #misorude has pointed out a solution here. So there lies your answer. use the square brackets [] or document.getElementById like this.
function getColumnsVal(id) {
// var element = $('[id="' + id + '"]'); // this line is equivalent to the next line.
var element = $(document.getElementById(id));
var header = element.find($("thead tr:eq(1)"));
var header_fields = $("td", header);
// If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD,
// example the firstone it returns undefined
alert(header_fields[0]);
}

I am getting empty values for sports-title and third

i am new to js.
can you tell me why I am getting empty values for sports-title and third.
since we have one div with content in it.
sports-title---->{"0":{}}
third---->{}
providing my code below.
findStringInsideDiv() {
/*
var str = document.getElementsByClassName("sports-title").innerHTML;
*/
var sportsTitle = document.getElementsByClassName("sports-title");
var third = sportsTitle[0];
var thirdHTML = third.innerHTML
//str = str.split(" ")[4];
console.log("sports-title---->" + JSON.stringify(sportsTitle));
console.log("third---->" + JSON.stringify(third));
console.log("thirdHTML---->" + JSON.stringify(thirdHTML));
if ( thirdHTML === " basketball football swimming " ) {
console.log("matching basketball---->");
var menu = document.querySelector('.sports');
menu.classList.add('sports-with-basketball');
// how to add this class name directly to the first div after body.
// but we are not rendering that div in accordion
//is it possible
}
else{
console.log("not matching");
}
}
When you call an object in the Document Object Model (DOM) using any of the GetElement selectors, it returns an object that can be considered that HTML element. This object includes much more than just the text included in the HTML element. In order to access the text of that element, you want to use the .textContent property.
In addition, an HTML class can potentially be assigned to several elements and therefore GetElementsByClassName returns an array so you would have to do the following, for example:
console.log("sports-title---->" + JSON.stringify(sportsTitle[0].textContent));
You can find a brief introduction to the DOM on the W3Schools Website. https://www.w3schools.com/js/js_htmldom.asp If you follow along it gives an overview of different aspects of the DOM including elements.
Maybe this would be helpful
As you see sportsTitle[0].textContent returns full heading and 0 is the index thus you get "0" when you stringify (serialize) sportsTitle. Why 0? Because you have one <h1> element . See this fiddle http://jsfiddle.net/cqj6g7f0/3/
I added second h1 and see the console.log and you get two indexes 0 and 1
if you want to get a word from element so get substring use substr() method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
One way is to change <h1> class attr to id and do sportsTitle.textContent;
and use substr() on this string
or
2nd way is to remain class attr and do sportsTitle[0].textContent;
and substr() on this string
The 2nd is the better way

Retrieve value from HTML Object

I have the following div (this was already given to me, I did not create it):
<div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1500, "pause": 5000}'>
as far as my understanding goes (please correct me if I am wrong), we are saying here, that I want to assing the following values (such as slideCount, moveCount, customLink, etc...) to the object named data-sudo-slider.
What I am trying to do in my underlying JavaScript, is to retrieve the value of pause from this object. Here is what I am doing:
var sudoEl = jQuery('[data-sudo-slider]');
var pause = sudoEl.pause;
Even though it recognized the slider object, it did not retrieve the value for pause I have passed in (returned value is undefined.
How can I retrieve this value?
You can use data() like this:
The .data() method allows us to attach data of any type to DOM
elements in a way that is safe from circular references and therefore
from memory leaks. We can retrieve several distinct values for a
single element one at a time, or as a set:
$('[data-sudo-slider]').data('sudoSlider').pause;
why did you have to specify 'sudoSlider'?
You can also use sudo-slider.
It worked as the property name is derived as following:
The attribute name is converted to all lowercase letters.
The data- prefix is stripped from the attribute name.
Any hyphen characters are also removed from the attribute name.
The remaining characters are converted to CamelCase. The characters immediately following the hyphens removed in Step 3 become uppercase.
You can get this property by:
$(function () {
var pause = $('[data-sudo-slider]').data('sudoSlider').pause;
});
$('[data-sudo-slider]') is the div element, where data-sudo-slider is defined. .data('sudoSlider') is the data property value. data is working with - signs a littlebit different, you can read about it in jQuery data documentation.
.pause is the property of JSON object.
You should use .data() to fetch data-sudo-slider value.
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
var sudoEl = jQuery('[data-sudo-slider]').data('sudo-slider');
alert(sudoEl.pause);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1500, "pause": 5000}'>
To retrieve the correct element use
var element = $("div[data-sudo-slider]");
You can either get the data-sudo-slider attribute via
var sudoSlider = element.attr("data-sudo-slider");
In which case you will have to convert the string to JSON to access the pause property:
var pause = JSON.parse(sudoSlider).pause;
or better yet, use the .data() method
var sudoSlider = element.data("sudoSlider");
var pause = sudoSlider.pause;

What is the best way to access an element through a data-attribute whose value is an object (JSON)?

Say I have the following element:
<div class='selector' data-object='{"primary_key":123, "foreign_key":456}'></div>
If I run the following, I can see the object in the console.
console.log($('.selector').data('object'));
I can even access data like any other object.
console.log($('selector').data('object').primary_key); //returns 123
Is there a way to select this element based on data in this attribute? The following does not work.
$('.selector[data-object.foreign_key=456]');
I can loop over all instances of the selector
var foreign_key = 456;
$('.selector').each(function () {
if ($(this).data('object').foreign_key == foreign_key) {
// do something
}
});
but this seems inefficient. Is there a better way to do this? Is this loop actually slower than using a selector?
You can try the contains selector:
var key_var = 456;
$(".selector[data-object*='foreign_key:" + key_var + "']");
I think that you may gain a little speed here over the loop in your example because in your example jQuery is JSON parsing the value of the attribute. In this case it's most likely using the JS native string.indexOf(). The potential downside here would be that formatting will be very important. If you end up with an extra space character between the colon and the key value, the *= will break.
Another potential downside is that the above will also match the following:
<div class='selector' data-object="{primary_key:123, foreign_key:4562}"></div>
The key is clearly different but will still match the pattern. You can include the closing bracket } in the matching string:
$(".selector[data-object*='foreign_key:" + key_var + "}']");
But then again, formatting becomes a key issue. A hybrid approach could be taken:
var results = $(".selector[data-object*='" + foreign_key + "']").filter(function () {
return ($(this).data('object').foreign_key == foreign_key)
});
This will narrow the result to only elements that have the number sequence then make sure it is the exact value with the filter.
With a "contains" attribute selector.
$('selector[data-object*="foreign_key:456"]')

jQuery form.id vs form.id.value

I'm working on dokuwiki plugin and I've found interesting think about how js stores element id. I'm not sure what is going on... So I have a code from dokuwiki linkwiz.js file which is using to determine if ':' char is in the part of the id string:
dw_linkwiz.textArea = $editor[0];
//some code between
// prepend colon inside namespaces for non namespace pages
if(dw_linkwiz.textArea.form.id.value.indexOf(':') != -1 &&
link.indexOf(':') == -1){
link = ':' + link;
}
the $editor is the jQuery object. As you can see to get id of the element they uses form.id.value but in some cases when I setting id of the element dynamicly using jQuery .attr method, the form.id.value is undefined and the id string is simply kept in form.id . Do you know why it happes? Which is more standard compilant?
Normally a DOM elements id will be a string and not an object, so form.id will be a string with the id value. It shouldn't be an object with a value. This plugin may have defined another object with an id property that contains a value property, but thats not a standard DOM element.
id in this case is not the id attribute of an element, but a field named "id" in the form.
Simplified it looks like this:
<form>
<input name="id" value="some:page">
<textarea>the editor</textarea>
</form>
dw_linkwiz.textArea is the DOM object of the textarea. dw_linkwiz.textArea.form.id.value is "some:page".

Categories

Resources