Say I have something like this setup.
<div id="error">
<p style="color:green">Success.</p>
<p style="color:red">Failure.</p>
<p style="color:green">Success.</p>
</div>
and in my javascript I run something like this.
var response = $('#error').html();
if (response.indexOf('red') === -1) {
/*do stuff if #error has no style tags that have the color:red*/
}
Will that work or do I need to go about doing this a different way? I'd like some insight, thanks.
So how should I go about this if thats not the best way?
The best way (or a better way) would be to give a failure class to p elements rather than trying to check against styles. But if you have no choice...
DEMO
There are various ways, the first one is closer to your initial line of thoughts:
if ($('#error > p[style*="color:red"]').length) {
console.log('red');
}
A different approach which is slightly better in my opinion:
var redPs = $('#error > p').filter(function () {
return this.style.color === 'red';
});
if (redPs.length) console.log('red again');
Yes it will take inline CSS. If you have tried opening up a console, you have known that.
However seeing your need. I recommend using Jquery data attribute. Passing jQuery data attribute you can find whether the message is an error or success.
Related
I want to make Textarea Disable (Grayed out) in my JS Method
function myfun(status){
if(status=='Yes'){
$('input[id$="txtareaID"]').attr('disabled','disabled');
}
The above code is not working for this.
You should use prop instead of attr:
$('input[id$="txtareaID"]').prop('disabled', true);
jQuery docs
If your selector is correct, than you need only to change attr to prop:
function myfun(status){
if(status === 'Yes'){ // more suitable for comparing
$('input[id$="txtareaID"]').prop('disabled',true);
}
}
Related post:
Disable/enable an input with jQuery?
Considering textarea as
<textarea id='txt'>Something</textarea>
Using jQuery, you can achieve like this
$("#txt").attr('disabled', true);
Using plain javascript
document.getElementById("txt").disabled=true;
Your problem is with CSS not JS. As far I can tell your code is working, but there's no way of changing this specific style. You could try workarounds: Change Font Color For Disabled Input
<textarea> is what you should be looking for not the <input> tag with id = textareaid.
$('input[id$="txtareaID"]').attr('disabled','disabled');
change the above code to the below one and see the magic by clicking the link at the bottom.
$('textarea[id$="txtareaID"]').attr('disabled','disabled');
http://jsfiddle.net/5s9ge7d6/1/
none of the below answers worked.
Then I found something amazing trick which solved my problem ---
Here it is --- JUST REMOVE "input" word from that line in if block -
WORKED CODE :
function myfun(status){
if(status=='Yes'){
$('[id$="txtareaID"]').attr('disabled','disabled');
}
Previous CODE :
function myfun(status){
if(status=='Yes'){
$('input[id$="txtareaID"]').attr('disabled','disabled');
$('input[id$="txtareaID"]').prop('disabled',true); //Didn't worked either
}
I've recently been learning JavaScript by creating a little to do list web app here.
So far almost everything's working, but I have an issue if you try to check and uncheck an item more than once. If you keep checking/unchecking you'll see the delete button disappear and --> appear after the urgency icon.
The change of icon is done by a Regex changing code from commented to un-commented. I just don't understand why if it works once, it doesn't work every time?
if (tr.outerHTML.indexOf("checked=\"\"") >= 0) {
// replace checked with unchecked
var cookieHTML = tr.outerHTML.replace(/checked=\"\" class=\"list-checkbox\"/, 'class=\"list-checkbox\"')
.replace(/<tr class=\"list-row done\"/, '<tr class=\"list-row\"')
// change delete button to urgency.
.replace(/<!--<span aria-hidden=\"true\" data-icon=\"c\"/, '<span aria-hidden="true" data-icon="c"')
.replace(/alt=\"Neutral\"><\/span>-->/, 'alt="Neutral"></span>')
.replace(/<!--<span aria-hidden=\"true\" data-icon=\"f\"/, '<span aria-hidden="true" data-icon="f"')
.replace(/alt=\"Urgent\"><\/span>-->/, 'alt="Urgent"></span>')
.replace(/<span aria-hidden=\"true\" data-icon=\"e\"/, '<!--<span aria-hidden="true" data-icon="e"')
.replace(/onclick=\"deletetodo\(this\)\"><\/span>/, 'onclick="deletetodo(this)"></span>-->');
} else {
// else add checked to the input.
var cookieHTML = tr.outerHTML.replace(/class=\"list-checkbox\"/, 'checked class=\"list-checkbox\"')
.replace(/<tr class=\"list-row\"/, '<tr class=\"list-row done\"')
// change urgency to delete button.
.replace(/<span aria-hidden=\"true\" data-icon=\"c\"/, '<!--<span aria-hidden="true" data-icon="c"')
.replace(/alt=\"Neutral\"><\/span>/, 'alt="Neutral"></span>-->')
.replace(/<span aria-hidden=\"true\" data-icon=\"f\"/, '<!--<span aria-hidden="true" data-icon="f"')
.replace(/alt=\"Urgent\"><\/span>/, 'alt="Urgent"></span>-->')
.replace(/<!--<span aria-hidden='true' data-icon='e'/, '<span aria-hidden="true" data-icon="e"')
.replace(/onclick='deletetodo\(this\)'><\/span>-->/, 'onclick="deletetodo(this)"></span>');
}
This is the (rather large!) chunk of JS that controls this. Any ideas what's wrong? Or maybe a better way of changing these icons around?
Thanks!
I would say: you're are doing it wrong. Using a string / regex replacement method is not the right way to go imho.
Instead of doing those replacement use DOM methods, i.e.:
someElement.setAttribute('data-icon', 'f');
someElement.setAttribute('alt', 'Urgent');
A simple example can be found here: http://jsbin.com/iwakof/1/edit
I know this isn't a direct answer to your question, but trust me this is the way to go
That's awesome that you are learning JavaScript. Nice job. But, I'm quite glad that you posted this question as it looks like you could use a couple of pointers.
The answer to your question is - yes there is a much simpler way to achive this effect - which I will get to shortly. But first - I notice that at the bottom of your todo app you include a library called JQuery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
This library will be of huge help to you, not only in the function you describe above, but to the majority of the code you have written. You will end up with much cleaner and self explanatory code.
http://jquery.com/
Basically what JQuery allows you to do, is to manipulate the state of the DOM. You definatly want to begin here.
Here is small sample which shows a check box who can be checked or unchecked, and on change, have an element shown' or hidden as desired.
http://jsfiddle.net/m4vGE/5/
Please - do take the time to have a look into JQuery - its a great first step you can take to increase your produtivity and reduce complexity in your JavaScript
Also - as a side note, if you find yourself using js to build HTML with strings, the answer is invariably "there is a better way"
If all you are trying to do is change icons based on a checkbox being checked or no, you could do something like this.
function getVisibility()
{
var temp = document.getElementById("iconName").style.visibility;
return temp;
}
function switchIfChecked()
{
var current = getStyle();
if( current == "visible" )
{
document.getElementById("iconName").style.visibility = "hidden";
}
else
{
document.getElementById("iconName").style.visibility = "visible";
}
}
<div id="iconName" style="visibility: visible">INSERT ICON IMG here</div>
What the above does is that it makes the div of the icon visible or hidden. Ofcourse you will need to have two divs and then set either or to hidden or visible.
With what you are doing currently, you are not really making the browser do anything.
Try to use the global option of Regex (have a look at the g after the second slash):
// ...
.replace(/<tr class=\"list-row done\"/g, '<tr class=\"list-row\"')
// ...
Here is an example.
From developer.mozilla.org:
global: Whether to test the regular expression against all possible
matches in a string, or only against the first.
Ok so I finally figured out which part of my code is causing the exception. You can read the initial post here. The code in the initial post is missing the part which is actually causing the exception (the manual subscription to the viewPortData observable). Apparently, I'm doing it wrong somehow... Here's the code:
self.viewPortData = ko.observable();
self.viewPortData.subscribe(function (newValue) {
var viewPort = $('#metro-view-port');
if (viewPort && newValue) {
self.fadeInOut(viewPort, newValue);
}
});
self.fadeInOut = function (domObject, newContent) {
if (newContent) {
var currentContent = domObject.html();
if (currentContent) {
var wrappedContent = $(currentContent);
wrappedContent.fadeOut(400, function () {
wrappedContent.empty();
domObject.html(newContent).hide().fadeIn(400);
});
} else {
domObject.html(newContent).hide().fadeIn(400);
}
}
};
So where did I go wrong?
The same error occurred to me. The problem was caused because the HTML had comments on it. Something like:
<!-- Some Comment goes here -->
<div>
...
</div>
To fix that, without changing the HTML, you need to wrap the HTML with something else, so you pass only one element to jQuery:
var div = document.createElement( 'div' );
div.innerHTML = nativeHtml;
var $html = $( div );
I created a fiddle using your code from this post and the previous post, and it works as it should.
However, I'm only returning a simple <div> tag to populate the HTML of the metro-view-port <div>.
My best guess is that the HTML that you're returning is the problem.
My advice to you is to first confirm this by reducing the HTML returned to something very simple, and then gradually reintroduce the intended code until you find the problem.
Flip your fadeIn(400) to a show().
It is simpler for jQuery to do the math for.... I think that it can't get computed style of the elements due to some floats inside it or something.
I had the same problem..... but after some research I got to here (DAMMET I LOST THE TAB - it was a jQuery bug report anyway ) and realised what needed to be fiddeled with to fix it.
In my code I swapped out fadeIn() to show() so it isn't to do with the animation
you would have thought that without the animation the problem wouldn't be prevalent either - but it is.
try slideDown(0 if your still after an animation, it might not work but its worth a pop.
This bug was in old versions of jQuery. Try to change .hide() to .css('display', 'none')
According to this jQuery bug, the problem may have to do with newline characters and whitespace text nodes in your HTML. In my case, I was taking a template like this one:
<script id="myTemplate" type="text/template">
<div>
<h2>Important stuff</h2>
</div>
</script>
And parsing it like this:
var currentContent = $.parseHTML($('#myTemplate').html());
So I ended up with a bunch of text nodes representing the newline and whitespace characters in the original HTML template. Probably something similar has happened to you.
To fix this, I stripped out the newlines and whitespaces like so:
$('#myTemplate').html().replace(/\n/g, '').replace(/>\s+</g, '><').trim();
Hope that helps someone!
I'm currently working on my Stretchbox Plugin and trying to optimize and shorten the code.
I've used the jquery data method to attach data to certain divs.
For instance:
$('#thumbs div:last-child').data('active', true)
which sets a certain div to the active state.
If i know want to find this div, i have to check each .thumb class
in order to find it:
$('.thumb').each(function() {
if($(this).data('active')){
//Do Stuff
}
}
This works fine, but I'm quite sure there should be a much easier way, since checking up every single .thumb div(out of 10-30) will take some performance too.
$(".thumb[data-active='true']");
As far as I know there is no other way to do it. You could, however, create a new jQuery selector. I was going to give it a shot, but it looks like someone has already thought of it (scroll down to "Querying element data").
It will allow you to do things like this:
$(':data(active)'); //Selects all elements with "active" data
It probably won't be faster, but it might make your code neater!
Am I missing something? Just save it in a variable:
jQuery(function($){
var activeDiv = [];
$('#selector').click(function(){
activeDiv = $('#thumbs div:last-child')
...
});
$('#executor').click(function() {
activeDiv.each(function() {
...
});
}
});
I'm having an impossibly hard time finding out to get the actual DOMElement from a jQuery selector.
Sample Code:
<input type="checkbox" id="bob" />
var checkbox = $("#bob").click(function() { //some code } )
and in another piece of code I'm trying to determine the checked value of the checkbox.
if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
//do something.
And please, I do not want to do:
if ( checkbox.eq(0).is(":checked"))
//do something
That gets me around the checkbox, but other times I've needed the real DOMElement.
You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.
Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:
$('#element').get(0);
I have verified this actually returns the DOM element that was matched.
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment:
Here is a post with a nice explanation: http://www.mail-archive.com/jquery-en#googlegroups.com/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.