I need help with DOM in javascript - javascript

I am suppose to Create a form that gives the user 3 different options to change the background color of the page. When the user clicks one of the options, the background color changes to match.And also create a div with some basic text to start out. Create a form that has a textarea. Use document.getElementById('yourelementid') to both find the value of the textarea and to change the basic text created in the div. (Hint: user innerHTML) Now I know how to do the form but i dont know how to get it to change the background when the user clicks that button.I am not really understanding how to use the innerHTML at all. If someone could explain or give me some website on how to understand this. Thank you.
OK this is what I have so far and I am not still yet understanding it...
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http:www.w3.org/1999/xhtml">
<head>
<title>background-color</title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
<script language="javascript" type="text/javascript">
function changeBackgroundColor(objDivID)
{
var backColor = new String();
backColor = document.getElementById(objDivID).style.backgroundColor;
if(backColor.toLowerCase()=='#A20000C')
{
document.getElementById(objDivID).style.backgroundColor = '#DF64BD';
}
else
{
document.getElementById(objDivID).style.backgroundColor = '#FFDD73';
}
}
</script>
</head>
<body>
<h3>Change background color to:</h3>
<div id="div1" style="background-color : #A2000C">
<p><input type="radio" name="color" value="red" />Red<br />
<input type="radio" name="color" value="pink" />Pink<br />
<input type="radio" name="color" value="yellow" />Yellow<br />
</div>
<input type="button" value="click here"onclick="changeBackgroundColor('div1')" />
</body>
</html>
i am still not sure why my box aint that big and is not chaning colors right i still have to have a box on there too. To ask to change the text of the color.

You should add an event handler on the color-change options, like this (assuming it's an select box):
<select id="colorSelect">
<option value="red">red</option>
<option value="green">green></option>
</select>
document.colorSelect.onchange = function(){
document.elementToChangeColor.style.backgroundColor= this.value;
}

here is how you would set the background color of the page to the value of the text area:
document.bgColor=document.getElementById('yourelementid').value;

InnerHTML is basically everything between two tags (hence inner HTML):
<div>
Now to change the background, you would get the value from the form element and then write something like this to change a background color.
document.getElementById('your_element_id').style.backgroundColor = formElementValue

The Mozilla documentation describes innerHTML fairly well. You may want to read through that page.
The innerHTML property of a DOM object provides as text the HTML contents of that object. So if you have the HTML:
<div id="myID"><span>Some text here!</span></div>
And the javascript:
var theHTML = document.getElementById('myID').innerHTML;
alert(theHTML);
Then you will see <span>Some text here!</span>.
If you set the innerHTML property to an HTML string, it will change the contents of the value. Given the HTML above if you have the following javascript:
var myDiv = document.getElementById('myID');
myDiv.innerHTML = '<span>Now this is some other text</span>';
Your div with the ID myID will change to show a span containing "Now this is some other text".
For changing the background color, look into changing the CSS attribute on the body. This question will help you see how this can be done. You will want to investigate document.body.style.

I would use jQuery:
function selectionMade(color) {
var body = $('body');
body.css('background-color', color)
var divWithSomeText = $('<div/>').Text = 'Some Text';
body.Add(divWithSomeText);
}
jQuery makes the things you are trying to do really easy. If I were you I would pick up use of the library now so you can use it again in the future.

Related

Create/update variable from text input box

After trying multiple ways of what I want to do, which all failed, I'm asking here. This is probably pretty basic, but I just can't do it.
What I essentially want to do:
Create a variable
"Assign" a text box (value) to it
Automatically have the variable's content change to whatever is put into the text box
Potentially have the variable's value used somewhere else immediately
If the user had to press a button to update the element using the variable's value, that'd be OK, too, I just want to have this done.
Alright, I have to correct myself. Another try worked, with the result of 'undefined'.
<head>
<meta id="test3" charset="utf-8">
<link rel="stylesheet" href=".\css\Starter.css">
<title id="test1">TITEL</title>
<script>
function txtSet(txtInp) {
var txt = txtInp.value
document.getElementById('txtP').innerHTML = txt
}
</script>
</head>
<body>
<input type="text" id="txtInp" onkeyup="txtSet(txtInp.value)"></input>
<p id="txtP"></p>
</body>
Try this one:
<body>
<script>
var a = "";
function changeVariable(){
document.getElementById('demo2').value=document.getElementById('demo').value;
}
</script>
<input type="text" id="demo" onkeyup="changeVariable()"></input>
<input type="text" id="demo2"></input>
</body>
I think that you're searching for onkeyup if it's so: you can use as it follows:
In your html
<input type="text" name="name" id="id" onkeyup="yourFunction(this.value);">
and in your js file
var theVariable;
function yourFunction(theTextInTheTextBox){
theVariable = theTextInTheTextBox;
}
It could also be onkeypress or onkeydown events, just try the three to see which is the one that you're actually searching for. To see the difference between the three I advise you to take a look at this link

Why does my div disappear after some AJAX calls?

I have problem I am suffering from for 4 days now. I am making a movie registry webpage. I made a smaller test project to reconstruct the error I get.
divpingpong.php: I have 3 divs (A, B and C) and a pencil button outside of them. I include an uploader in div B first inside a #placeholder div (when the page loads). I want to use this #placeholder multiple times. For example if the user switches to div B, I want to make the uploader visible with javascript. I use the jQuery .appendTo function to move the #placeholder to the place I wish, then .show() it. Div A won't need the uploader. When user clicks on the pencil icon I want to display div C with a content loaded by AJAX and moving the uploader into it. On switching back to div B I want #placeholder to move back into div B.
div_ccontent.php: This is the file, which is called by AJAX and has the content of div C. It also contains some sort of JS code, which helps (or at least intented to) to move the uploader into the right place.
The problem: After a few (more than 1) AJAX calls my entire #placeholder div seems to disappear completely. It mustn't disappear, because I want use it to upload pictures at data input (represented by div B) and data manipulation (represented by div C). I know it's not the best method of programming, but I'm not good at writing nice codes. This program is only made for home usage.
My researches: I tried every possible solutions and every relevant google search terms (including Stackoverflow), but with no success. I have found a useful link at technify.me about using the eval() function to run JS came from AJAX request, but it didn't help me either. I was trying possible soultions and searching for about 7-8 hours all together and it is very annoying.
Here is my code:
divpingpong.php:
<?php
#session_start();
include_once("initial.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Div ping-pong</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script language="javascript" src="easytooltip/js/easyTooltip.js"></script>
<script language="javascript" src="jsfv.js"></script>
<script language="javascript">
$(document).ready(function(){
var ajaxfile="div_ccontent.php";
function switchpage(){
//$("#div_a").toggle(0); //if we want to make sure the display is the opposite (show->hide, hide->show)
var val=$(this).val();
$("#div_"+val).show();
if(val=="a")
$("#div_b, #div_c").hide();
else if(val=="b"){
$("#div_a, #div_c").hide();
var parentid=$("#placeholder").parent().attr("id");
var exists=$("#placeholder").length;
if(parentid!="div_b"){
$("#placeholder").appendTo($("#div_b")).show();
//$("#upload_frame").attr("src", "").hide();
}
}
}
function domod(){
$("#div_a").hide();
$("#div_b").hide();
$("#div_c").show();
$.post(ajaxfile, {sid: Math.random}, function(valasz){
$("#div_c").html(valasz);
$("#div_c").find("script").each(function(i){
eval($(this).text());
});
});
}
$("#div_b").hide();
$("#div_c").hide();
$("#selectpanel").change(switchpage);
$("img.pencil").live("click",domod);
});
</script>
<style type="text/css">
img.pencil:hover{
cursor: pointer;
}
</style>
</head>
<body>
<h3>Div ping-pong, that is replace a div with AJAX calls</h3>
<select id="selectpanel">
<option value="a">Div A</option>
<option value="b">Div B</option>
</select>
<div id="div_a">
<b>Div A</b>
<p>
This is the place for quick search. There is some amount of text in a table with a few rows, which is in a fieldset.<br />
This will never contain the certain #placeholder div.
</p>
</div>
<div id="div_b">
<b>Div B</b>
<p>
This is the place for data input. There is some amount of text in a table with a few rows, which is in a fieldset.<br />
Then, comes the uploader in #placeholder:
<div id="placeholder"><?php include_once("upload.php"); ?></div>
</p>
</div>
<div id="div_c">
</div>
Modify <img class="pencil" src="img/modositas.png" alt="módosítás" />
</body>
</html>
div_ccontent.php:
<?php
session_start();
$included=strtolower(realpath(__FILE__))!=strtolower(realpath($_SERVER["SCRIPT_FILENAME"]));
if(!$included && !isset($_POST["sid"])) header("Content-type: text/html; charset=utf-8");
if(isset($_POST["sid"])) include_once("initial.php");
?>
<b>Div C</b>
<p>
This is the place for data manipulation. There is a little amount of text in a table with a few rows, which is in a fieldset.<br />
Then, comes the uploader in #placeholder:
</p>
<p id="additionalinfo">Does the #placeholder exist? (1-yes, 0-no) </p>
<script language="javascript">
var parentid=$("#placeholder").parent().attr("id");
var exists=$("#placeholder").length;
if(parentid!="div_c"){
$("#placeholder").appendTo($("#div_c")).show();
//$("#upload_frame").attr("src", "").hide();
}
$("#additionalinfo").append(exists);
</script>
I can't figure out, what can be the problem. Why does that div disappear? Please answer if you can. Any helps will be appreciated.

Call javascript from XForms action

I am experimenting with XForms and trying to dynamically load javascript, but cannot figure it out.
I am presenting a simple example - that is just an input field and button that loads the javascript:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xf="http://www.w3.org/2002/xforms"
xmlns:ev="http://www.w3.org/2001/xml-events" >
<head>
<title>Hello World in XForms</title>
<xf:model>
<xf:instance xmlns="">
<data>
<firstName/>
</data>
</xf:instance>
</xf:model>
<script type="text/javascript">
var myFunction = function(){
var name = document.getElementById("firstName").value;
alert("Hello " + name + "!");
}
</script>
</head>
<body>
<xf:label>Please enter your first name: </xf:label>
<xf:input ref="firstName" id="firstName">
</xf:input>
<br />
<xf:trigger>
<xf:label>Click me!</xf:label>
<xf:action ev:event="DOMActivate">
<xf:load resource="javascript:myFunction()" />
</xf:action>
</xf:trigger>
</body>
</html>
So in my script I am trying to get the value from the input box and then show an alert box with concatenated string. Currently, I get "Hello undefined!"
Do you have an idea how to get the value from the firstName xf:input with Javascript?
I know how to do it with XForms only, but this is sort of a proof of concept.
On a side note - I am using XSLTForms, so the XForms runs on the client.
Another hint might be in the fact that XSLTForms transforms the xf:input into several nested span elements with a <input type="text"> element, but that input element does not have a name or id.
With XSLTForms, there are different possibilities...
If you want to access the value of the corresponding HTML input, I would suggest document.getElementById("firstName").xfElement.input.value.
You could also use the node property to get the value stored in the bound node.
Don't hesitate to browse DOM with a debugger to find how to get things from XSLTForms!
--Alain

Change color of font after specific code

When a code is typed in like ^1 in a textarea i want the font color of any text after that code to be changed to whatever color the ^1 is assigned to,
As of now i have the following:
<form method="post" action="index.php">
<textarea id="text" onkeypressed="changecolor()"></textarea>
<input type="submit" value="Add">
</form>
javascript:
function changecolor() { //code here }
so basically when i type in ^1 and the color blue is assigned to that code, the text after that code will be in the color blue, but when a second code is typed in; example ^2 the text after that will be the color that is assigned to that code,
I know very well how to insert data into a database, but i need to beable to find a way of getting the raw data; i.e the data that was orginally typed into the textarea with the codes like ^1 and ^2
Help is really appreciated!
You cant target specific fragments of text in a textarea. What you want to do can't be done of my knowing, unless you monitor its content and add an abstract div layer to output styled html from it.
Many wysiwyg text editors do it like this, or use the 'contenteditable' attribute to allow html editing in modern browsers...
You can start like this:
<script type="text/javascript">
var display, input, displayHtml;
function init(){
display = document.getElementById('display');
input = document.getElementById('input');
}
function onContentChange(){
displayHtml = parseContent(this.value);
display.innerHtml = displayHtml;
}
function parseContent(text){
var html = ... // Generate html according to content
return html;
}
document.onload=init;
</script>
html:
<textarea id='input' onkeypress="javascript:onContentChange" />
<div id='display'></div>

Javascript form innerHTML

i have an issue with innerHTML and getElementsById(); method but I am not sure if these two methods are the root of the issues i have.
here goes my code :
<script type="text/javascript">
function clearTextField(){
document.getElementsById("commentText").value = "";
};
function sendComment(){
var commentaire = document.getElementById("commentText").value;
var htmlPresent = document.getElementById("posted");
htmlPresent.innerHTML = commentaire;
clearTextField();
};
</script>
and my HTML code goes like this:
<!doctype html>
<html>
<head></head>
<body>
<p id="posted">
Text to replaced when user click Send a comment button
</p>
<form>
<textarea id="commentText" type="text" name="comment" rows="10" cols="40"></textarea>
<button id="send" onclick="sendComment()">Send a comment</button>
</form>
</body>
</html>
So theorically, this code would get the user input from the textarea and replace the text in between the <p> markups. It actually works for half a second : I see the text rapidly change to what user have put in the textarea, the text between the <p> markup is replaced by user input from <textarea> and it goes immediately back to the original text.
Afterward, when I check the source code, html code hasn't changed one bit, given the html should have been replaced by whatever user input from the textarea.
I have tried three different broswer, I also have tried with getElementByTagName(); method without success.
Do I miss something ? My code seems legit and clean, but something is escaping my grasp.
What I wanted out of this code is to replace HTML code between a given markup (like <p>) by the user input in the textarea, but it only replace it for a few milliseconds and return to original html.
Any help would be appreciated.
EDIT : I want to add text to the html page. changing the text visible on the page. not necessarily in the source. . .
There is no document.getElementsById, however there is a document.getElementById. This is probably the source of your problem.
I don't think there is any document.getElementsById function. It should be document.getElementById.
"To set or get the text value of input or textarea elements, use the .val() method."
Check out the jquery site... http://api.jquery.com/val/

Categories

Resources