text replace "false" to "true"
ori from html (dont change) :
<td align="center">false</td>
to
<td align="center">true</td>
my js code error :
document.body.innerHTML = document.body.innerHTML.replace(/<td align=\"center\">false<\/td>/g,"<td align=\"center\">true<\/td>");
http://jsfiddle.net/PKM6U/
Since you are new to this I would recommend you use a framework/library to make thing easier for you
jQuery have a nice selector that will help you with this
http://jquery.com/
http://jquery.com/download/
http://api.jquery.com/contains-selector/
This code will do what you want
function swapTrueFalse(){
if($("td[align=center]:contains('true')"){
$("td[align=center]:contains('true')").text('false')
}else if($("td[align=center]:contains('false')"){
$("td[align=center]:contains('false')").text('true')
}
}
I would suggest you add a class to the element however as this will make it more efficient:
<td align="center" class='true-false'>true</td>
Change the code to match:
function swapTrueFalse(){
var t = $(".true-false").text()
if(t === "true"){
$(".true-false").text("false");
}else{
$(".true-false").text("true");
}
}
Using regex to parse HTML in the way you are is extremely inefficient so I do advise against it.
<td align="center" id="changeme">false</td>
in js
document.getElementById("changeme").text="true"
Works just fine if you replace your all "td" with "span". Having td nodes by themselves doesn't really make sense and it appears as though they disappear completely after the fiddle is ran.
Related
I am new to javascript.. I want to know if there is any simple way to toggle background color in javascript..
here is the html code
<td style="width:70px;height:70px;background-color:white;" class="white" onclick="place(this,2,1)"></td>
<td style="width:70px;height:70px;background-color:black;" class="black" onclick="place(this,2,2)"></td>
here is the javascript code
function place(domObj,row,col){
var placeQueen=false;
if(domObj.style.backgroundColor=="black"||domObj.style.backgroundColor=="white")
domObj.style.backgroundColor="red";
if(domObj.style.backgroundColor=="red")
domObj.style.backgroundColor=domObj.className;
}
But it seems to be not working..
In fact the second if should be else if:
if(domObj.style.backgroundColor=="black"||domObj.style.backgroundColor=="white")
domObj.style.backgroundColor="red";
else if(domObj.style.backgroundColor=="red")
domObj.style.backgroundColor=domObj.className;
Demo.
NOTE: You should not use inline-style, just use class, you can toggle the class using the pure javascript classList.toggle() (element.classList), if that feature is not supported, you can even try modifying the className using some algorithm. And the last, you should use jQuery. Search for it and get started now, it's not time to use pure Javascript today although it's better to learn it first before digging into some framework like jQuery.
You seems to be mixing inline styles and CSS classes, which seems to be unnecessary here...
I'd suggest removing the inline styles and using css classes. Inline styles add duplicate code and makes code unreadable and hard to work with.
here's an article from MDN on Why Use CSS.
For the task at hand, You can make use of the classList API for CSS class manipulations.
HTML
<td class="white" onclick="place(this)"></td>
<td class="black" onclick="place(this)"></td>
CSS
.black{
background:black;
}
.white{
background:white;
}
.red{
background:red !important;
}
JS
function place(domObj) {
domObj.classList.toggle("red");
}
JSFiddle
The HTML, CSS and JS is much simpler, readable and easily scalable if you ask me…
You need to add an else. As it is, you're changing the background to red, and then immediately back to black or white (since the second if statement will now be satisfied):
function place(domObj,row,col){
var placeQueen=false;
if(domObj.style.backgroundColor=="black" || domObj.style.backgroundColor=="white")
domObj.style.backgroundColor="red";
else if(domObj.style.backgroundColor=="red")
domObj.style.backgroundColor=domObj.className;
}
Your solution is pretty interesting. You might want to check out a library like jQuery. It'll make a lot of stuff like this much easier.
If you don't mind a jQuery solution, you could do something like this:
CSS
.red{ background-color:red;}
.black{ background-color:#000;}
HTML
<td style="width:70px;height:70px;" class="red"></td>
<td style="width:70px;height:70px;" class="black"></td>
jQuery
$(function(){
$('td.red, td.black').on('click', function(){
var this_class = $(this).attr('class');
if(this_class == 'red')
{
$(this).removeClass('red');
$(this).addClass('black');
}
else
{
$(this).removeClass('black');
$(this).addClass('red');
}
});
});
The jQuery code can be reduced more, but I've kept it simple so that it is understandable and readable.
Note: This would also require that you include the jQuery library on your page before using it.
DEMO
I've got a webpage which uses the JQuery ToolTips plugin for popup boxes with extra information. That's all working fine with no issues.
However in order for the popup boxes to work perfectly I need to give the elements in question titles detailing out what I want the popups to say. This would be simple if I could change the HTML directly but I can only do it through JS. More to bother me, the tooltip changes depending on the content of what's in the elements innerHTML, but the element itself doesn't have an ID. It's parent however does have an ID.
so I've been trying to access the child node through the parent, reads it's innerHTML, compare it to a few if statements and then apply a title to the parent based on this innerHTML.
Here is my code:
for(var i = 1; i<5; i++){
var q = document.getElementById("cell.0."+i);
console.log(i+" "+q);
if(q.children[0].innerHtml === "some text1"){
q.setAttribute('title', 'Other text1');
}
else if(q.children[0].innerHtml === "some text2"){
q.setAttribute('title', 'Other text2');
}
else if(q.children[0].innerHtml === "some text3"){
q.setAttribute('title', 'Other text3');
}
else if(q.children[0].innerHtml === "some text4"){
q.setAttribute('title', 'Other text4');
}
}
And an accompanying JSFiddle to make it a bit clearer: http://jsfiddle.net/qxb58/7/
Note: the JSFiddle uses a button, but the actual function I'm using will be on page load.
I've been testing each line in the console. From what I can tell all of the statements which are immediately testable in the console work (e.g. q.children[0].innerHtml === "some text4" and q.setAttribute('title', 'Other text4');). But when put into a for loop it doesn't seem to work.
Note it's unlikely to be a HTML error as my HTML is autogenerated and works. If there is an error with the HTML in the fiddle, it's me being crap at HTML. Thanks for pointing it out though!
EDIT: Solution: innerHTML not innerHtml. Sorry for the stupid mistake. And thanks for the help!
You were executing javascript onload which meant that when the DOM was created with the function changer(), it was undfined at that time. Also you were looking for property innerHtml instead of innerHTML. Properties are case senstive. With these two changes, it works fine:
JSFiddle
Aside from your case problem, you also have the problem of your HTML being invalid. Enclose your <tr>s in a and it works:
http://jsfiddle.net/qxb58/7/
<table>
<tr>
<td id="cell.0.1"> <span>some text1</span>
</td>
</tr>doc
<br/>
<tr>
<td id="cell.0.2"> <span>some text2</span>
</td>
</tr>
<br/>
<tr>
<td id="cell.0.3"> <span>some text3</span>
</td>
</tr>
<br/>
<tr>
<td id="cell.0.4"> <span>some text4</span>
</td>
</tr>
</table>
<br/>
<br/>
<button onClick="changer()">Changing</button>
Still not 100% correct, but working.
Oh, also, you need to set your fiddle to put your script in the head. You had it in the onload which won't work because the handler won't be defined.
Edit: Sorry, missed the part of actually setting the title. Your problem there is that you need innerText not innerHTML. See here: http://jsfiddle.net/qxb58/15/
Finally: if you are using a jQuery plugin for your tooltips, why not use jQuery throughout instead of getElementById
In HTML ids are case sensitive.
You set them in lower case and query them in JS with an upper case C.
Correct it this way:
q = document.getElementById("cell.0."+i);
^ lower case now
This will not solve the problem but is just one of a multi-step debug. Below is a further answer solving the problem.
EDIT: this works now. I corrected the upper case C and replaced innerHtml with innerText.
And BTW, innerHtml is written this way:
innerHTML
^^^^ all upper case
Copy & paste solution:
function changer()
{
for (var i = 1; i < 5; i++)
{
var q = document.getElementById("cell.0." + i);
if (q.children[0].innerText === "some text1") {
q.setAttribute('title', 'Other text1');
} else if (q.children[0].innerText === "some text2") {
q.setAttribute('title', 'Other text2');
} else if (q.children[0].innerText === "some text3") {
q.setAttribute('title', 'Other text3');
} else if (q.children[0].innerText === "some text4") {
q.setAttribute('title', 'Other text4');
}
}
}
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.
This is what I try to do, and I know this will take many hours to get the good looking UI.
$("input[type=text],textarea").bind("focus", function()![enter image description here][1] {
var $th = $(this).before("<div class='css-editor'><select class='font-family-select'> <option></option></select><select class='font-style-select'><option>italic</option></select><select class='font-size-select'></select></div>");
}).bind("blur", function() {
$('.css-editor').remove();
});
Above code is just a prototype. Redactor air mode http://imperavi.com/redactor/examples/air/ is the closest thing I can find on the net.
I wonder if there are currently any jQuery plugins or Javascript to do this?
<table style="width:100%" class="remark" cellspacing="0" cellpadding="0">
<tr class="invoice-cell-section">
<th colspan="6" class="invoice-cell-top">
**<input type="text" value="{_ Remark}"/>**
</th>
</tr>
<tr>
<td colspan="6" class="invoice-footer invoice-cell-bottom">
**<textarea class="invoice-remark static"></textarea>**
</td>
</tr>
</table>
You see input box with value Remark and empty Textarea up here.. I want when people click on it.. there is a stylesheet editor to edit only that textarea/input element...
For anyone just reading this question.. I know there is several way to add/enable this .css-editor to the DOM.... I see right to it now how to implement it if I need to code myself.. + better UI than select dropdown + hours of debugging... It like a small version of TinyMCE or CLEditor that works for single HTML element not the whole HTML in textarea.
I just want to know if there are any plugin/snippet that I can instantly use..
why not just:
$(document).on('focus', 'input[type=text],textarea', function(){
$(this).addClass('focused');
});
$(document).on('blur', 'input[type=text],textarea', function(){
$(this).removeClass('focused');
});
define a css class called focused and apply the style there.
hope that helps.
EDIT:
after better understanding of what you need, think about something like this.
create an invisible, floating (absolute positioned) panel- it will be the "css editor".
now, on every focus on an input, get to know it's location on document, and display the invisible floating css editor relatively. look at this idea:
$(document).on('focus', 'input[type=text],textarea', function(){
$('.css-editor').css({left: $(this).offset().left+'px', top: $(this).offset().top+'px'}).show();
});
$(document).on('blur', 'input[type=text],textarea', function(){
$('.css-editor').hide();
});
note that there's no need to remove and re-create this hidden element. you can create it once on DOM and manipulate it's position & visibility.
hope it's better :-)
No need to bind focus event on the textbox, it itself have the focus,focusin and focusout events attached in it. So you can simply use either .onfocus or you can also use .live function.
Using onfocus handler directly:
$("input[type=text],textarea").focus(function() {
var $th = $(this).before("<div class='css-editor'><select class='font-family-select'> <option></option></select><select class='font-style-select'><option>italic</option></select><select class='font-size-select'></select></div>");
});
Using Live event handler:
$("input[type=text],textarea").live("focus",function() {
var $th = $(this).before("<div class='css-editor'><select class='font-family-select'> <option></option></select><select class='font-style-select'><option>italic</option></select><select class='font-size-select'></select></div>");
});
You need to add function() {}
$("input[type=text],textarea").click(function(){
$(this).removeClass("your_old_class").addClass("your_new_class")
});
so i'm calling a function in jquery that's looping over a table and determining whether to hide a row based on a hidden form element within each row.
when i run this script, toggling the rows either way, the browser hangs for at least 5 seconds even though there are fewer than 100 rows.
the js looks like this:
$('input.vv').each(function(index) {
var chk = $(this).val();
if (chk == "0") $(this).parents("tr").slideToggle(function() {
tableRows();
});
});
and a sample row from the html looks like this:
<tr class="sortable part item" id="row803">
<td class="col-check">Interior Fixed Dome Camera Surface Mounted<br />(Panasonic Part No. WV-CW484AS/29)
<input type="hidden" class="vv" value="50" id="v803" /></td>
<td class="col-equip cen" id="q803">70</td>
<td class="col-equip cen" id="s803">50</td>
<td class="col-equip cen"><div id="bom803|092311-001|15" />50</div></td>
<td class="col-equip cen" id="b803"><span class="shipped">20</span></td>
</tr>
the line of jquery.js that firebug refers to is 8449
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
i'm stuck (can't link to the live site sorry). firebug may give me a way out of this but i'm unsure how to use it well enough. thoughts anyone? thanks!
$('input.vv') creates a loop which goes through all input elements, and checks whether they're a part of the vv class.
.parents("tr") loops through all parent nodes, and selects only the <tr> elements.
Then, you call .slideToggle, which creates an effect which requires a significant amount of computing power (at small intervals, CSS style adjustments through JQuery, CSS style parsing by browser). likely to be the main cause
Finally, you're calling tableRows();, which you haven't defined yet.
These operations, on "fewer than 100 rows" requires much computing power.
Try being a little more specific:
$('input.vv').each(function(index) {
if ($(this).value == "0") $(this).parent().parent().slideToggle(function() {
tableRows();
});
});