Is these some simple JS code that allows me to check whether a cell is empty.
I am trying to code a function that is called using "onmouseover=func()"; I just cant seem to get the JS code right. Any ideas?
What im ideally trying to work toward is a code that can detemine whether a cell is empty and if so, place a simple value in, like "Cell Empty".
I know it probably sounds simple but i could use a little help.
Thanks for any ideas.
It depends a little on what will be in there initially. In my experience, tables behave strangely if a cell contains only whitespace, and so a common workaround is to put a in there to stop it collapsing. Anyway, here's how you'd check:
function elementIsEmpty(el) {
return (/^(\s| )*$/.test(el.innerHTML);
}
function replaceCell(td) {
if (elementIsEmpty(td)) {
td.innerHTML = 'Cell Empty';
}
}
<td onmouseover="replaceCell(this)"></td>
... though a better way would be to apply the behaviours through Javascript event handlers.
If you're using jQuery, use the html() method on the element. Given this markup:
<td id="my_cell"></td>
This code will do it:
if ($('#my_cell').html() == '') {
$('#my_cell').html('Cell Empty');
}
Withouth jQuery (like in the old good times):
function func(e){
var target = window.event ? window.event.srcElement : e ? e.target : null;
if (target.innerHTML === ''){
target.innerHTML = 'Cell Empty!';
}
}
Related
I am trying to create my own custom HTML elements where a user can interact with the text within that element. For Example, I created an element where anything between those tags will have a pointer as a mouse cursor and when double clicked, something happens. EG:
<objdc>Double click me!</objdc>
However, this is my code and it is not working:
$(document).ready(function() {
var ObjDblClk = $('objdc');
ObjDblClk.css({ cursor: 'pointer' });
ObjDblClk.dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var word = $.trim(range.toString());
if(word != '') {
//Do Something
}
range.collapse();
e.stopPropagation();
});
});
}
Any suggestions?
The problem you have is related with the fact you are not using the collapse method right. It expects a node as parameter and an offset.
So... to fix that exact behavior you posted you would need to do something like:
ObjDblClk.dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var word = $.trim(range.toString());
if(word != '') {
//Do Something
}
range.collapse(ObjDblClk[0], 0);
e.stopPropagation();
});
BUT (and this is important): That will do absolutely nothing for your custom selection (especially since is on double click witch affects selection). So you can just remove that line completely and try another solution.
Also: You should read the comments. The guys are right. Unless you are working on some reall strange inhouse thing there may be better aproaches.
Fiddle here (added an alert so you see the function is called - don't forget to select something before double clicking): https://jsfiddle.net/713ndkm0/1/
To create a custom tag like that, you have to be aware of certain things:
Not all browsers will understand your custom tag as a DOM object. IE is a notable example.
Your new custom tag should have a hyphen in it, like obj-dc (more info).
If you want to use it in IE, you have to declare it up-front, as:
document.createElement('obj-dc');
Here is a link to creating new HTML tags for Chrome, in the new way, and here is a link for the older API. As you can see, even the same browser cannot operate with custom tags consistently.
I can't figure this out. I'm trying to create an onclick handler purely in Javascript.
What I plan to do here is inside this DIV, have a collection of items that I can click on. For now, these items will be numbers from 0 to 9 inclusive. When a number is clicked on, a system message consisting solely of that number should pop-up on the screen. I narrowed my problem down to just the onclick handler definition.
If I use this format:
item[n].onclick=function(n){
handler(n);
}
The handler will fire only when click a number which is correct, but the message that appears is something about mouse event.
If I use this format:
item[n].onclick=function(){
handler(n);
}
The handler will pass a value of -1 which in turn is printed as a message. I think it means "false".
How do I modify this:
item[n].onclick=function(){
handler(n);
}
so that 'n' being used as the handler parameter is the same as the number I click on the screen?
My code is the following:
<div ID="Itemset"></div>
function handler(n){
alert(n);
}
collections=document.getElementById('Itemset');
for(n=0;n<10;n++){
item[n]=document.createElement('DIV');
item[n].innerHTML=n;
collections.appendChild(item[n]);
item[n].onclick=function(n){
handler(n);
}
}
What I'm effectively trying to do if you want to understand it HTML wise is this:
<div ID="Itemset">
<div onclick="handler(0);">0</div>
<div onclick="handler(1);">1</div>
<div onclick="handler(2);">2</div>
<div onclick="handler(3);">3</div>
<div onclick="handler(4);">4</div>
<div onclick="handler(5);">5</div>
<div onclick="handler(6);">6</div>
<div onclick="handler(7);">7</div>
<div onclick="handler(8);">8</div>
<div onclick="handler(9);">9</div>
</div>
Except that I don't want to write out onclick="handler(n);" a million times.
Any advice? and feel free to point to another resource that has the answer I need if there is one.
UPDATE
I'm looking for something compatible with older browsers as well. I'm going to have to not go for the bind function because according to mozilla docs, it works for IE 9+. I'm looking for something that works for IE 7+ as well as other browsers. I might have to go for event listeners if there is no other alternative.
You have a closure issue here (see JavaScript closure inside loops – simple practical example), a simple solution is to use bind to use the current value of n to be a parameter of the handler function
item[n].onclick=handler.bind(item[n],n);
U can use addEventListener and ID for find clicked element...
document.getElementById("Itemset").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a list item
var value_data = parseInt(e.target.textContent);
if(e.target && value_data > -1) {
alert("Malai test:: "+value_data);
//handler(value_data);
}
});
https://jsfiddle.net/malai/tydfx0az/
I found my answer here: https://bytes.com/topic/javascript/answers/652914-how-pass-parameter-using-dom-onclick-function-event
Instead of:
item[n].onclick=function(n){
handler(n);
}
I have to do:
item[n].onclick=new Function('handler('+n+')');
Funny thing is, the word function needs to be capitalized when making a new instance. It's awkward I have to go this route but it works in IE 7+
One alternative is :
function handler(){
alert(this.id);
}
function myFunction() {
var item=[];
collections=document.getElementById('Itemset');
for(n=0;n<10;n++){
item[n]=document.createElement('DIV');
item[n].innerHTML=n;
item[n].setAttribute("id","itemset"+n);
collections.appendChild(item[n]);
item[n].onclick=handler;
}
}
Insert dynamic ids to the elements and when you click on any element retrieve its id using this.id and do whatever you want to do with that value.
That's all.
Hope this helps.
I am trying to access html elements that I create in one js function in another function. I have this code
EDIT after comments:
here is a jsfiddle
http://jsfiddle.net/8uTxM/
</button>" +"<button value='1' type='button' class='as' id='c2' onclick='cA(this);'>"
in this function
function cA (element){
var x = element.value;
if (x === allQuestions[questionNumber].correctAnswer) {
element.setAttribute.style.backgroundColor = "green";
++score;
}
}
I am trying to make the button green when it is clicked. However, I get the error:
Cannot set property 'backgroundColor' of undefined
I assume this has something to do with timing, but I cannot figure out why. Especially since the element.value bit works (the++score works fine, every right question adds +1 to the score variable)
One problem that I may guess is you are using "getElementsById"
either go for "getElementById" or "getElementsByTagName"
Why don't you create a <div> in your html/php page which would be empty with the answers class, and then change its id/innerHTML ?
I seem to be doing something wrong in the following code: http://jsfiddle.net/yunowork/qKj6b/1/
When you click next, the text within the span .hiddentext should be displayed in the span .showtext on top and correspond to the right Race (Rn). For example when R3 is highlighted the content of that .hiddentext "Race 3Oregon 14:30" should be displayed within the span .showtext.
This is the line where I make a mistake:
$('.showtext').text($('.hiddentext').first('td:first').text());
What am I doing wrong here?
Let's start simple:
Your problem:
$('.showtext').text($('.hiddentext').first('td:first').text());
you are saing, that, grab all .hiddentext, choose the first that has a td ... witch is not what you have in code, you have, td that contains hiddentext... so, the other way around.
What you want to do is simply get the current NEXT td and grab the hiddentext, so, just change to:
$('.showtext').text($nextCol.find('.hiddentext').text());
Now, can you see that the <br/> is not correctly rendered? That's because you are setting the text property, and you should set the html property.
the final code should be something like:
$('.showtext').html($nextCol.find('.hiddentext').html());
live example: http://jsfiddle.net/qKj6b/8/
Your code:
every time you need to have placeholders to provide some data to a context, please, DO NOT USE HTML TAGS to hold such values and hide them... make the use of the data- attribute, witch is a HTML5 complience, and works very well in any browser even if it does not have not HTML5 support, like IE6.
your table definition (td) that currently is:
<td class="visible" id="r2">
<span class="hiddentext">Race 2<br />Santa Fe 12:00</span>
<strong>R2</strong>
</td>
should be something like:
<td class="visible" id="r2" data-text="Race 2<br />Santa Fe 12:00">
R2
</td>
witch is way easier to read, and from your javascript code, you can easily get this as:
var hiddenText = $nextCol.data("text");
Your code (part 2):
This one is quite simple to know
Every time you are repeating yourself, you're doing it wrong
You have the methods for Next and Prev almost exactly as each other, so, you are repeating everything, for this, you should refactor your code and just use one simple method, this way, any future change only happens in one place, and one place only.
$(".next").click(function(e){
e.preventDefault();
var $nextCol = $('.highlighted').next('td');
MoveCursor($nextCol, 'next');
});
$(".previous").click(function(e){
e.preventDefault();
var $prevCol = $('.highlighted').prev('td');
MoveCursor($prevCol, 'prev');
});
function MoveCursor(col, side) {
var maxCol = 8;
if((side === 'next' && col.length != 0) ||
(side == 'prev' && col.length != 0 && col.index() >= maxCol)) {
$('.highlighted').removeClass("highlighted");
col.addClass("highlighted");
// show current title
$('.showtext').html(col.data('text'));
if (col.hasClass("invisible")) {
col.removeClass("invisible");
col.addClass("visible");
var $toRem;
if(side == 'prev')
$toRem = col.next('td').next('td').next('td').next('td').next('td').next('td');
else
$toRem = $nextCol.prev('td').prev('td').prev('td').prev('td').prev('td').prev('td');
$toRem.removeClass("visible");
$toRem.addClass("invisible");
}
}
}
Live Example: http://jsfiddle.net/qKj6b/22/
It should be
$('.showtext').html($('.highlighted .hiddentext').html());
Similar for the prev link...
or even better, thanks to #balexandre:
$('.showtext').html($nextCol.find('.hiddentext').html());
$('.showtext').html($prevCol.find('.hiddentext').html());
Fiddle
Update to match #balexandre hint: Fiddle 2
Do the following:
var $currCol = $('.highlighted'); //to get the current column
$('.race strong').text($currCol.closest('.highlighted').first('td:first').text());
.hiddentext class selects all the spans and the first() will always return you the first td.
Just make sure you select .hiddentext from the currently highlighted column and you are good to go.
$('.showtext').text($('.highlighted .hiddentext').first('td:first').text());
Try this (Same for both)
$('.showtext').html($currCol.find('span.hiddentext').html());
Working Example.
I am trying to apply a class to a child's parent element if the conditions are true but cannot seem to get it to work. In short, I want to check a table for a cell that is the number "0" and hide its parent row.
I have created a basic jsfiddle of what I have done: http://jsfiddle.net/immbudden/YbZPE/3/
And the snippet of jquery that I have put together:
if ($('#the_table>table>td:contains("0")').length === 1) {
$(this).parent("tr").addClass("hidden");
}
I am still learning jQuery and javascript and this is probably something small, but I can't seem to put my finger on it!
Any help would be much obliged, thanks in advance!
$('td', '#the_table > table').each(function() {
if ($(this).text() === '0') {
$(this).parents("tr").addClass("hidden");
}
});
FIDDLE
Use your browser's developer tools! Or Get Firebug.
With that page loaded, try this in the javscript console:
$('#the_table>table>td:contains("0")')
If that gives you
[ ]
then it's not finding any elements. Then you can try breaking it down, for example, see if this works:
$('#the_table>table>td')
And keep taking out and adding bits of that expression until it produces true or false as you require.
you can do it like this,
$('#the_table table td').filter( function (index) {
return $(this).text() == '0';
}).parent("tr").addClass("hidden");
http://jsfiddle.net/YbZPE/5/
First you have to get teh cell, if you want the first use eq(0):
$cell = jQuery('#the_table tr td:eq(0)');
then you have to put the class on the parent row:
$cell.parent("tr").addClass("hidden");
The following code will do it.
jQuery('#the_table tr td:eq(0)').parent("tr").addClass("hidden");