Disable a text area by it's class (not id) - javascript

I have 2 text area's that are generated automatically, and I need to use JavaScript to disable both when the page has loaded. The catch is because they are generated automatically I can't give them an ID because they would both have the ID - a big no.
Attempted Javascript:
document.getElementByClassName('option_window-size').disabled=true;
I know this works because if I change getElementbyClassName to ID then it will work if I give the text areas the ID as well. But as I say it needs to work off class. Also it can't work of the Name attribute because that is automatically generated per product and per page...
I have tried this but it just doesn't work and I can't figure out why not because it should as the only thing I have changed is from ID to CLASS
Text Areas
<textarea name="willbeautogenerated" class="option_window-size" cols="40" rows="5">willbeautogenerated</textarea>
Additional note: I have tried to count and assign them different IDs using PHP but it gets far to complex. Also it is only these two that need disabling, thus I can't just disable all text area's on the page.

I know this works because if I change getElementByClassName to ID then it will work if I give the text areas the ID as well. But as I say it needs to work off class.
getElementsByClassName returns a NodeList rather than a Node itself. You'll have to loop over the list, or if you expect just 1 item, choose index 0.
var nodes = document.getElementsByClassName("option_window-size"),
i = 0, e;
while (e = nodes[i++]) e.disabled = true;

jQuery makes this pretty simple:
$(".selector").prop("disabled", true);
ALTHOUGH! It should be noted that this note appears on the man pages for $.prop() and $.attr():
Note: Attempting to change the type property (or attribute) of an input element created via HTML or already in an HTML document will result in an error being thrown by Internet Explorer 6, 7, or 8.
This doesn't apply directly to your question, but you are changing prop/attrs on an input element, so be aware.
But it's still possible with plain old JS:
var els = document.getElementsByClassName("selector"); // note: Elements, not Element
for(var e = 0; e < els.length; e++)
{
els[e].disabled = true;
}
getElementsByClassName returns an NodeList, you just have to iterate over each element within.

You can use class selector,
$('.option_window').attr('disabled', true);
OR
$('.option_window')[0].disabled = true;

With Jquery you can do:
//make sure to use .prop() and not .attr() when setting properties of an element
$('.option_window').prop('disabled', true);

Disable textarea using jQuery:
$('.option_window-size').attr('disabled', true);

your missing a s in elements and the index where the element is like [0], for the first element.
document.getElementsByClassName('option_window-size')[0].disabled=true;
or
document.getElementsByName('willbeautogenerated')[0].disabled=true;

Disabel texarea using .prop() methode in jquery...
$('.option_window-size').prop('disabled', true);

You can use CSS:
.option_window-size{display:none;}

Related

Get text value from especific class in web site

I want to know if it is possible to go to a site and retrieve the text of an element
i think something like
a = page("www.site.com")
b = a.getElementByClass("name")
console.log(b.text)
this is possible?
Yes. It's called the innerText property. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
That depends,
If you want to get the innerText of the elements, then
let elements = document.getElementsByClassName("YourClassName");
for(let i=0;i<elements.length; i++){
/*doSOmething*/
console.log(elements[i].innerText);
}
Many elements may have same className. So, if you want to access some specific Element, then you should either know the index of the element or you need to use id for the element.
let element = document.getElementById("YourElementId");
/*doSOmething*/
console.log(element.innerText);

Why does jQuery return more than one element when selecting by type and ID? [duplicate]

I fetch data from Google's AdWords website which has multiple elements with the same id.
Could you please explain why the following 3 queries doesn't result with the same answer (2)?
Live Demo
HTML:
<div>
<span id="a">1</span>
<span id="a">2</span>
<span>3</span>
</div>
JS:
$(function() {
var w = $("div");
console.log($("#a").length); // 1 - Why?
console.log($("body #a").length); // 2
console.log($("#a", w).length); // 2
});
Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.
However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.
However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a type selector, like this:
$('span[id="a"]');
The reason for this is because a type selector is much more efficient than an attribute selector. If you qualify your attribute selector with a type selector, jQuery will first use the type selector to find the elements of that type, and then only run the attribute selector on those elements. This is simply much more efficient.
There should only be one element with a given id. If you're stuck with that situation, see the 2nd half of my answer for options.
How a browser behaves when you have multiple elements with the same id (illegal HTML) is not defined by specification. You could test all the browsers and find out how they behave, but it's unwise to use this configuration or rely on any particular behavior.
Use classes if you want multiple objects to have the same identifier.
<div>
<span class="a">1</span>
<span class="a">2</span>
<span>3</span>
</div>
$(function() {
var w = $("div");
console.log($(".a").length); // 2
console.log($("body .a").length); // 2
console.log($(".a", w).length); // 2
});
If you want to reliably look at elements with IDs that are the same because you can't fix the document, then you will have to do your own iteration as you cannot rely on any of the built in DOM functions.
You could do so like this:
function findMultiID(id) {
var results = [];
var children = $("div").get(0).children;
for (var i = 0; i < children.length; i++) {
if (children[i].id == id) {
results.push(children[i]);
}
}
return(results);
}
Or, using jQuery:
$("div *").filter(function() {return(this.id == "a");});
jQuery working example: http://jsfiddle.net/jfriend00/XY2tX/.
As to Why you get different results, that would have to do with the internal implementation of whatever piece of code was carrying out the actual selector operation. In jQuery, you could study the code to find out what any given version was doing, but since this is illegal HTML, there is no guarantee that it will stay the same over time. From what I've seen in jQuery, it first checks to see if the selector is a simple id like #a and if so, just used document.getElementById("a"). If the selector is more complex than that and querySelectorAll() exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. If querySelectorAll() does not exist, then it will use the Sizzle selector engine to manually find the selector which will have it's own implementation. So, you can have at least three different implementations all in the same browser family depending upon the exact selector and how new the browser is. Then, individual browsers will all have their own querySelectorAll() implementations. If you want to reliably deal with this situation, you will probably have to use your own iteration code as I've illustrated above.
jQuery's id selector only returns one result. The descendant and multiple selectors in the second and third statements are designed to select multiple elements. It's similar to:
Statement 1
var length = document.getElementById('a').length;
...Yields one result.
Statement 2
var length = 0;
for (i=0; i<document.body.childNodes.length; i++) {
if (document.body.childNodes.item(i).id == 'a') {
length++;
}
}
...Yields two results.
Statement 3
var length = document.getElementById('a').length + document.getElementsByTagName('div').length;
...Also yields two results.
What we do to get the elements we need when we have a stupid page that has more than one element with same ID? If we use '#duplicatedId' we get the first element only. To achieve selecting the other elements you can do something like this:
$("[id=duplicatedId]")
You will get a collection with all elements with id=duplicatedId.
From the id Selector jQuery page:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
Naughty Google. But they don't even close their <html> and <body> tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.
If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.
<div>
<span id="a" class="demo">1</span>
<span id="a" class="demo">2</span>
<span>3</span>
</div>
JQ:
$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");
Access individual item
<div id='a' data-options='{"url","www.google.com"}'>Google</div>
<div id='a' data-options='{"url","www.facebook.com"}'>Facebook</div>
<div id='a' data-options='{"url","www.twitter.com"}'>Twitter</div>
$( "div[id='a']" ).on('click', function() {
$(location).attr('href', $(this).data('options').url);
});
you can simply write $('span#a').length to get the length.
Here is the Solution for your code:
console.log($('span#a').length);
try JSfiddle:
https://jsfiddle.net/vickyfor2007/wcc0ab5g/2/

Select all the elements within an element having an attribute set to a specific value

I have the followings defined :
var excludedFiltersPanel = $("#excludedFiltersPanel");
var includedfiltersPanel = $("#includedfiltersPanel");
where *Panel is just a div.
in excludedFiltersPanel there are some div's with attribute data-iscorefilter="true" e.g. :
<div id="filterPanel-LastName" class="filterPanel" data-iscorefilter="true">
<Some Stuff here!>
</div>
I am trying to get them and move them to includedfiltersPanel:
It seems neither of these is a correct syntax:
excludedFiltersPanel.('[data-iscorefilter="true"]')
excludedFiltersPanel.$('[data-iscorefilter="true"]')
1.What is the correct syntax?
2.How do I append them to includedfiltersPanel? (I know how to append a single item, but not sure what is the common good practice here, e.g. using for loop or some JQuery magic)
Since excludedFiltersPanel there are some div's with attribute data-iscorefilter="true"
Use .find()
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
It would look like :
excludedFiltersPanel.find('[data-iscorefilter="true"]')

I want to check if `id` has no content

I want check between id that get in var span, if empty was between it put css for input but it not work. how can fix it?
var span = '#'+$('.valid').closest('.auto_box').find('span').attr('id');
if ($(span+':empty').length != 0) {
//alert('ok')
(this).closest('.auto_box').find('input').css('background-color','#000');
}
See here my full code: http://jsfiddle.net/Pjqv2/2/
You are using (this) instead of $('.valid') or whatever you meant with it. Also, you are doing this the wrong way; .find('span') returns the jQuery objects set for that span.
You don't need to get it's ID and then check on that ID again. More importantly, your code seems the need to run on multiple instances of .auto_box. For that, you need to iterate on the set found by (".valid").closest(".auto_box"), which you can do with the jQuery .each() (.each() in jQuery docs) like this:
var autoBoxes = $(".valid").closest(".auto_box");
autoBoxes.each(function(){
if ($(this).find("span").is(":empty")) {
$(this).find("input").css("background-color", "#000");
}
});
Your updated jsfiddle with this script: http://jsfiddle.net/dvir_azulay/Pjqv2/4/
Change (this) to $(span). I updated your fiddle to reflect this change.

Why are jQuery set attributes not reflected in .html()?

I am trying to set some attributes on HTML snippets. The purpose is to repopulate a form with previous inputed values. I set attributes with .attr() but after I do a .html(), I do not see my changed attributes.
I have done a basic example here http://jsfiddle.net/ejanderson4/CSYnU/
My function looks like this:
function setValue(html,value,name){
var element=$(html);
$(element).find("[name='"+name+"']").attr('value',value)
return element.html();
}
It is setting it, but for reasons unknown to me, you can't directly query the value attribute of an input element. You need to call .val() on that element to get it.
Updated your example here
parse the html string using $.parseXML and then set the attr value
var html="<div><label id='el_c5c0f78656138c39c5eb91a9bf1d3bf6'> table input 1 </label><input type='text' value='' name='table_input_1' class='select-mini' id='table_input_1' /></div>";
var value= 'xxxxxxxxxxxxx';
var name='table_input_1';
function setValue(html,value,name){
var xml = html,
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "[name='"+name+"']" );
$title.attr("value",value);
//var element=$(html);
//element.find("[name='"+name+"']").attr('value',value)
return $title.attr("value");
}
alert(setValue(html,value,name));
here is the working fiddle http://jsfiddle.net/CSYnU/4/
also this solution requires you to use jquery version 1.5.2 and higher
update
sry for overdoing it in your scenario you have to do
function setValue(html,value,name){
var element=$(html);
$(element).find("[name='"+name+"']").attr('value',value);
return $(element).find("[name='"+name+"']").attr('value');
}
here is the fiddle http://jsfiddle.net/CSYnU/5/
you are wrapping the html in $(html) then there is no need to again wrap the cached html in $
var element = $(html);
element.find ...
see here http://jsfiddle.net/CSYnU/6/
I think the short answer here is that setting an attribute on a DOM object does not necessarily change what the browser returns for innerHTML. If you want to retrieve a particular attribute, then you should just retrieve that attribute directly.
You also have an error in your code (which jQuery might be tolerating). You've already turned element into a jQuery object so you don't need to do that again with $(element).find, you can just use element.find.
function setValue(html,value,name){
var element=$(html);
element.find("[name='"+name+"']").attr('value',value)
return element.html();
}
Depend on your code, the first problem is about element variable. It doesn't denote "table_input_1" element. To get this element, you should replace by :
var element=$(html).find("[name='"+name+"']");
The second problem is in the your return statement. Since you changed the value of input element, you have to get this value by method val() or attr('value') rather than html(). The html() method is used to get the content inside tags of a element, but in this case value is a attribute, not content.
return element.attr('value'); // element.val();
Here is the complete code:
function setValue(html,value,name){
var element=$(html).find("[name='"+name+"']");
element.attr('value',value); // element.val(value);
return element.attr('value'); // element.val();
}
One reason is that the jQuery attr method gets confused between HTML attributes and DOM properties. The imlpementation of setAttribute and getAttribute was (probably still is) buggy in IE, so in general forget about HTML attributes and use DOM properties.
In most browsers, modifying the HTML attribute (say using setAttribute) will modify the related DOM property. But in many browsers, changing the DOM property will not modify the HTML attribute.
Further, some browsers will modify an element's innerHTML based on the current DOM property, others will use the HTML attribute (which might have a different value in most browsers). HTML 5 is the first attempt to standardise the behaviour of innerHTML, note that it is not a W3C standard yet and is not consistently implemented.
The best approach is to be consistent and always set DOM properties to the values you want. Expect that an element's innerHTML may be inconsistent across browsers.
Setting the current value of an input element doesn't change the initial value, which is what the value attribute is.
There is no property to change the initial value, so you can't alter the HTML code that way.
Edit:
If you want to use the elements in the page, then just make the function return a jQuery object containing the elements instead of returning HTML code:
function setValue(html, value, name){
var elements = $(html);
elements.find("[name='"+name+"']").val(value)
return elements;
}
Adding the elements to the page works the same as using a string. Example:
var html = '<div><input type="text" name="city" /></div>';
$('#SomeForm').append(setValue(html, 'York', 'city'));

Categories