I have the following function:
<script type="text/javascript">
function changeText(elem){
var oldHTML = document.getElementById(elem).innerHTML;
var newHTML = "<span style='color:red'>" + oldHTML + "</span>";
document.getElementById(elem).innerHTML = newHTML;
}
</script>
And the following HTML:
<table>
<tr>
<td id = "foo">bar</td>
</tr>
</table>
This throws a "unknown runtime error" (just in IE) which googling has since taught me that table elements are read-only in IE with innerHTML.
I've tried finding workarounds but they don't target my specific problem, which is just that I want to make the word "bar" red. I don't want to change the word "bar" to something else. Purely a color change.
Is there any way to do this without a complex and slow DOM function and without having to change any of the other HTML markup on the page? This is a table with a form in it, and if the surfer submits the form with an error, the "errored" fields should turn red. It has to be able to execute multiple times because it's possible for a surfer to mess up more than one field.
Thanks for any advice.
Why not just change the cell to have color:'red' :
var td = document.getElementById(elem);
td.style.color = 'red';
Couple ways to go about it. Here are some quick ones to get you going -- or until someone else comes with a cleaner/better method.
I prefer the following: define an error class in css:
.errorHighlight { color:red;}
Then for the javascript:
function changeText(elem){
document.getElementById(elem).className="errorHighlight";
}
function changeTextBack(elem){
document.getElementById(elem).className="";
}
This assumes that you don't have any classes set already. If you do you may need to read the name, and append the error class with a space.
Again, there are a lot of ways to approach this and you want to pick the one best suited for your application.
Related
So, this could be a simple question, but my jQuery skills are just not quite up there (yet). I'm trying to target a specific word on a web page and add a style to it. The word I'm trying to target appears multiple times on the page. I googled around some and found this:
<script>
var divContent = document.getElementById("styled").innerHTML;
divContent = divContent.replace("Bevestigd","<span class='styled'>Bevestigd</span>");
divContent = divContent.replace("Geannuleerd","<span class='styled-r'>Geannuleerd</span>");
divContent = divContent.replace("Pending","<span class='styled-p'>Pending</span>");
document.getElementById("styled").innerHTML = divContent;
</script>
This works, kind of... It only targets the first time it encounters the word and doesn't repeat it self. I found numerous pieces of code to target a word on a page but this one seems to work the best... Is there any one that could help me out?
Is there a foreach function I'm missing?
I also tried this code:
$('body').html(
function(i,h){
return h.replace(/(Nike)/g,'<span class="nike tm">$1</span>');
});
which seems a bit simpler but that didn't work... Maybe someone has a snippet for this or something?
This is your js code done on jquery. Check out this jsfiddle
$('#styled').html(function(i,v){
v=v.replace(/Bevestigd/g,'<span class="styled">Bevestigd</span>');
v=v.replace(/Geannuleerd/g,'<span class="styled-r">Geannuleerd</span>');
v=v.replace(/Pending/g,'<span class="styled-p">Pending</span>');
return v;
});
This is done with regex.
We can extend it further.
eg. To make the search case insensitive use /Bevestigd/gi instead of /Bevestigd/g.
I am in the process of learning JavaScript and jQuery, so apologies if any of this sounds naive or obvious. I started what I thought was a fairly simple project to practice and hopefully learn something in the process.
What I want to do is this: the user inputs a sentence and hits a submit button. The sentence gets added to a list of other sentences submitted by people (preferably on a separate file, preferably encrypted, but not necessary). Then, the website grabs a random sentence from the list and displays it.
I am not asking on how to build all of this. I have already put most of it together, but I am including it here for reference.
I have a separate javascript file with the array of quotes.
var quotes=new Array();
quotes[0]="<p>Quote 1</p>";
quotes[1]="<p>Quote 2</p>";
quotes[2]="<p>Quote 3</p>";
quotes[3]="<p>Quote 4</p>";
quotes[4]="<p>Quote 5</p>";
quotes[5]="<p>Quote 6</p>";
quotes[6]="<p>Quote 7</p>";
Then I randomly display one using this:
function getQuote(){
var thisquote=Math.floor(Math.random()*(quotes.length));
document.write(quotes[thisquote]);
}
And adding <script> getQuote(); </script> to the html.
This all works fine.
The part I cannot seem to figure out is taking user input and adding it to the jQuery array. I am using a contenteditable div instead of an <input> because I want it to have multiple lines of text and have a character limit, which as far as I know can only be done with a contenteditable div (according to the research I did at the time, I may be wrong).
I have looked around and tried many if not all the examples I found of how to do this, and none of them worked. This is the last method I tried, if it helps:
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
So, to reiterate, I want to take user input and add it to a JavaScript array. I have scoured stackoverflow and the interet but nothing has worked. Please help!
UPDATE: Arvind got it right. I still have a lot to learn, and it seems I need to read up on localstorage and cookies. I will also need to use PHP to save the sentences on the server. Thank you to all who answered!
Problem is document.getElementsByClassName("input") gives you a NodeList and not just a single html element. So if you do this document.getElementsByClassName("input").value, you will end up quotes as [undefined, undefined ... undefined]. Assuming you have single element with the class name input, go with index 0. Also as you stated that you are using div with attribute contenteditable, you may try this instead. document.getElementsByClassName("input")[0].innerHTML
Try this example.
var quotes = localStorage.getItem('quotes'); //get old, if any, gives you string
quotes = quotes ? [quotes] : []; // if got quotes then make it as array else make new array
$(function() {
var quote = $('#quote'); //get the quote div
quote.html(quotes.join('') || quote.html()); //set the default text
$('#btn').on('click', function(e) {
quotes.push(quote.html());
localStorage.setItem('quotes', quotes.join('')); //save the quotes
alert(quotes.join(''));
});
});
#quote {
border: 1px solid grey;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div contenteditable='' id='quote'>
<ol>
<li>Quote 1</li>
<li>Quote 2</li>
</ol>
</div>
<input type='button' id='btn' value='Submit' />
P.S.
In order to preserve the old quotes you may possibly use cookie, localStorage, etc.
Are these "quotes" being saved locally?
Yes, to share it among several users visiting by different browsers, you have to save it with the server script like PHP, Java, ASP, etc. Here you can either use ajax, if you wana avoid page reload on submit, else you can go for form submit.
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
should be
$(".submit").click(function() {
quotes.push(document.getElementsByClassName("input").text());
});
EDIT: With a content editable div you need to use text() instead. Here is an example fiddle. https://jsfiddle.net/
var quotes=[];// better
// function to add to array
function addQuote(myquote){
quotes.push('<p>'+myquote+'</p>');
}
addQuote("Quote 1");
addQuote("Quote 2");
addQuote("Quote 3");
addQuote("Quote 4");
addQuote("Quote 5");
addQuote("Quote 6");
addQuote("Quote 7");
addQuote("Quote 8");
$(".submit").on('click',function() {
addQuote(document.getElementsByClassName("input")[0].value);
});
NOTE: suggest NOT using the "input" class name and use some other one as that might be confusing to others at some point later (confused by element named input)
I also added the paragraph tags as that would provide a consistent pattern for your input text. Assumption on my part however.
NOTE I also assume that the element IS an input type with the .value since that is NOT provided (the markup)
Hello I have a function that loops around and then eventually a string gets sent to a DIV tag class...
$(document).ready(function addcopy() {
/* global */
$(".Bands").append('<div style="display: inline-block;">[EDIT] <h7 style="color:#7A0029;line-height: 110%;text-transform: uppercase;">[Custom:Name]</h7> </div>');
});
It works fine... however the token [Custom:Name] may contain special characters such as single or double quotes etc...
I've looked around these forums and tried to adapt my code to various solutions offered and it never seems to work, could somebody help me?
Thanks for your help!
Alex
EDIT(1):
Getting somewhere, from Ockert's and LeFex's answer I've adapted it below but it still does not work (replace speech marks and special characters from token which html can't handle)...
function htmlEncode(value){
return $('<div/>').text(value).html();
}
$(document).ready(function (){
/* global */
var band = $("<div style='display: inline-block;'>[EDIT] <a href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.appendTo(htmlEncode('.Bands'))
});
You can change your script too
$(document).ready(function (){
var band = $("<div style='display: inline-block;'>[EDIT] <a class='link' href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.find('.name').html("some weird name !##$%^&*");
band.find('.link').attr("href","http://www.google.com");
band.appendTo('.Bands');
});
By splitting it up like that, enables you to set the name to anything you want. You can easily select the name element
Have a look at this jsfiddle http://jsfiddle.net/fL3gn056/2/
You could use document.createElement instead of just appending a string.
http://www.w3schools.com/jsref/met_document_createelement.asp
If you just create your div, a and h7-elements, use the appendChild function, and add style and attributes and content by setting element properties, you should end up with a sollution that allows any special characters.
Edit:
I could'nt get it working using that method; however, with the approach I suggested above, i got some working code:
var element = document.createElement("div");
element.style.display = "inline-block";
var link = document.createElement("a");
link.setAttribute('href', "[LINK]");
var text = document.createElement("h7");
text.style.color = "#7A0029";
text.style.lineHeight = "110%";
text.style.textTransform = "uppercase";
text.innerHTML = "[CUSTOM:NAME]";
//not sure what you're appending it all to, but do it here
document.getElementsByClassName("Bands")[0].appendChild(element);
element.appendChild(link);
link.appendChild(text);
With this snippet, all input special characters are interpreted as a string, not as code. Some calls I could have put in the same line, but this way you get an easy to read overview.
Here's an earlier thread on the subject, and the top answer brings the issue of performance of different approaches to discussion.
jQuery document.createElement equivalent?
attempting to have my webpage be a bit more dynamic by having the background change on some elements when a checkbox is clicked. I am trying to do this via class change and a CSS sheet. I have the following which is kicking out an error that my onclick function ins not defined (in IE9). More importantly will the webpage update if I only change the class of the object which would have a different class in the CSS file. Whats a better alternative if this does not work?
my elemenet and function
UPDATE
I made updates to both my HTML and CSS file as suggested by many. I am still getting no change in my webpage but the console is claiming that my function called from the onclick event is not defined which is a bit odd since it is. Also does this type for scripting belong in the HTML or should I pull it out and put in a seperate file. I figured since it was creating elements it belongs in the main html. Is there a cleaner more compact way of accomplishing this and not making my home screen html huge?
<tr class= 'tr.notchosen'><td><input type='checkbox' onclick='handleClick(this.id)'/></td></tr>
function handleClick(cb) {
var currentColumn = cb.parentNode
var currentRow = currentColumn.parentNode
if (currentRow.className === "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}
}
and my css file is the following
tr.chosen
{
background-color:rgba(255,223,0,0.75);
}
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
There are a couple of things going on here. First, your css selector is not quite right. In fact, I would suggest making the class name just "chosen" or "not chosen" and then selecting tr elements with that class.
<tr class='notchosen'>
And then you can target it from css (which was probably the original intention)
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
Further, although I would not suggest using inline javascript, using your example, you should pass this if you want to work with the element and not this.id which would pass a string.
onclick='handleClick(this)'
The last part would be to sync up your javascript with the class name change
if (currentRow.className == "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}
I'm trying to convert a table I've written in HTML into Javascript because I want the table to be dynamically generated (# of rows). The main issue I'm having is that the individual cells in the table are clickable and open up another html page. Unfortunately, the html "onclick" parameter doesn't work with document.write statements Here is an examples of a table cell in HTML:
<td id="r1c1" align="center" onclick="getTicket(1,'plan',1);"><script language="JavaScript">document.write(getDate(1,"plan", "r1c1")); </script></td>
The functions in this line are predefined and work so I'm not going to post those, but the idea is that the function getTicket(..) is suppose to open up another html page.
My issues is how to get the onclick to work in JavaScript. I can create the cells in Javascript using document.write commands but don't really know how to make those cells clickable to run the function getTicket(..).
Your style of Javascript programming is ancient, to say the least. document.write is a function developed mainly when there were almost no common methods to generate dynamic content.
So, you should generate your elements dynamically with methods like document.createElement, append your content there, then attach the elements to the DOM with modern methods like appendChild.
Then, you can attach event listeners using something more modern than the traditional way like onclick, like addEventListener. Here's a snippet:
var td = document.createElement("td");
td.innerHTML = getDate(1, "plan", "r1c1");
td.addEventListener("click", function() {
getTicket(1, 'plan', 1);
});
row.appendChild(td);
I supposed that row is the row of the table that you're generating.
Unfortunately, IE<9 uses a different method called attachEvent, so it'd become:
td.attachEvent("onclick", function() { ...
You can modify attributes in HTML using function setAttribute(Attribute, Value).
With this function you can generate the cell code and define dinamically the attribute.
You should not use document.write to add elements to your page, there are javascript functions for this:
var myCell = document.createElement('td');
myCell.setAttribute('id', 'r1c1');
myCell.setAttribute('align', 'center');
myCell.onclick = function () {
getTicket(1, 'plan', 1);
};
// myRow is the 'tr' you want this 'td' to be a child of.
myRow.appendChild(myCell);
See it in action: http://jsfiddle.net/teH7X/1/
Can you please try below code, if that is working then let me know I will give you some better option:-
<script>
document.onload = function()
{
document.getElementById('r1c1').onclick = function()
{
getTicket(1,'plan',1);
}
}
</script>
Please check and let me know.