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.
Related
Just beginning learning JavaScript; writing some calculators with relatively basic functions. I found the need to put multiple variable values in an option tag of a drop-down menu, and after researching I figured it would be easiest to put them in one string, then split them with the split() function, but regardless of the delimiter I specify, it acts as if there is none, and splits each character individually. Why?
<select name="fuel" onChange="document.scalc.fuel.value=document.scalc.fuel.value.split(',')">
<option value="199x1,50">cu/ft Natural Gas(Via Storage Tank Burner, 65% Efficient)</option>
</select>
Cᴏʀʏ has made some good points. Additionally, you will find it helpful to have your browser's JavaScript console open while you are testing your JavaScript so that it can show you any errors it encounters.
I could not get your example code to do anything at all - perhaps you have shortened it a little bit too much.
Your page could perhaps look something along the lines of
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Example</title>
<script>
/* TODO: Give this function a meaningful name. */
function x(srcId, targetId) {
// Get reference to the source element
var src = document.getElementById(srcId);
// Make sure it is a select element
if (src.nodeName.toLowerCase() === "select") {
var target = document.getElementById(targetId);
// Put the first part of the source's value in the target
target.value = src.value.split(",")[0];
}
}
</script>
</head>
<body>
<form id="scalc">
<select id="fuel" onChange="x('fuel', 'result')">
<option value="199x1,50">cu/ft Natural Gas(Via Storage Tank Burner, 65% Efficient)</option>
<option value="50x2,60">cu/ft Natural Gas(Via Super Burner, 70% Efficient)</option>
</select>
<input id="result" type="text" readonly="readonly" />
</form>
</body>
</html>
References:
<meta charset='utf-8'> vs <meta http-equiv='Content-Type'>
Best Practice: Access form elements by HTML id or name attribute?
How can javascript determine the type of an html element?
Also useful: W3C Markup Validation Service
I want to fill and submit a form like below:
<form action="http://www.test.com/school" method="post">
<select name="days">
<option value="2">Monday</option>
<option value="1">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<input type="submit" value="submit" id="submitday">
I don't want to select from option so I have to create another form.
<form action="http://www.test.com/school" method="post">
<input type="text" name="days">
<input type="submit" value="submit" id="submitday">
When I want to choose Wednesday, I need to type the value 3 in a text box then click submit. It works.
But I want to know if any method that can make me just type Wednesday in text box and not the value and post it without any problem?
Your question isn't well defined enough and having an explicit goal always helps.
1.) Even though we're pretty much if not outright beyond the point where it's important to use id="same_as" name="same_as" having the same values I still highly recommend this practice (old Internet Explorer bug). You'll want to make good use of the label element (clicky clicky) as it gives users more area to click to give focus (element, checkbox, text, etc).
2.) You'll want to use the in operator to discover what tools you have available...
XHTML
<textarea id="dom_methods"></textarea>
JavaScript
for (i in document.getElementById('select_element_id')
{
document.getElementById('methods').value = document.getElementById('methods').value+'\n'+i;
}
This will let you discover different methods/functions/objects/etc that are associated with in example the select element. Keep in mind that each object may have it's own children. You can do...
for (i in window) {}
for (i in window.document) {}
for (i in document.getElementById('select_element_id')) {}
Good resources including Mozilla Developer Network here...
https://developer.mozilla.org/en/
My absolute biggest piece of advice is do not use frameworks as you will quickly veer off from learning the actual language and immediately inherit some high level issues you will not become aware of. People posting dollar signs ($) in JavaScript posts are usually good give-aways that they have not answered your question unless you have explicitly asked for a framework related answer.
If you revise your question and reply to my answer I'll be happy to append my answer to apply more directly to what you're trying to accomplish.
PART TWO
If you want to create an element you should use the createElement method...
Create the element and give it the value you want...
var d = document.getElementById('days');
var input_day = document.createElement('input');
input_day.setAttribute('id','days');
input_day.setAttribute('name','days');
input_day.setAttribute('type','text');
input_day.setAttribute('value',d.options[d.selectedIndex].text);
IMPORTANT! JavaScript has QUIET errors that you will battle for days before posting about them and someone casually pointing them out. So be exceptionally wary of using short names for variables (e.g. do not use var in = ''; as "in" is an operator and will cause a silent error) where your code simply won't execute or do odd stuff.
Now you have some VALID choices for putting this new element in to the page...
1.) Using appendChild will put the element at the end of the parent container...
document.getElementById('form_id').appendChild(d);
You should use fieldsets (usually one is fine) as a direct child to a form element...
<form action="" method="post">
<fieldset>
<!--everything form related goes here -->
</fieldset>
</form>
...in which case you could do the following (to help you get comfortable with examples and see them actually work before you)...
document.getElementById('form_id').getElementsByTagName('fieldset')[0].appendChild(d);
Notice the [0], it refers to the first fieldset element, if there were two and you wanted to append the new element in to the second you would use [1] (and [2] for the third and so forth). Also if the page only includes a single form and a single fieldset you could drop the first part (just so you can see how things are constructed)...
document.getElementsByTagName('fieldset')[0].appendChild(d);
2.) You'll usually want to use insertBefore...
var f = document.getElementById('form_id');
var element_parent = f.getElementsByTagName('fieldset')[0];
var element_before = f.getElementsByTagName('select')[0];
parent_element.insertBefore(d,element_before);
A little more information here...
https://developer.mozilla.org/en/insertBefore
NEVER EVER FOR ANY REASON USE INNERHTML!!! Lazy programmers use it all the time and fail to realize that it does NOT correctly register the DOM so elements associated with that proprietary Microsoft JScript method will NOT be seen when you try to work with them. For this reason alone you should avoid using frameworks such as jQuery as they jump to use the easiest things. Easy doesn't get the job done, easy makes the job look done long enough to make a single paycheck and then if you don't one day end up rewriting ALL of your code in that given area (long after you remember working with it and what you were trying to do) you'll be in a world of hurt.
PART THREE
JavaScript is an EVENT driven language, events are DOM based. The DOM and JavaScript are different things very closely tied together.
You can read more about DOM events here...
https://developer.mozilla.org/en/DOM/event
...and there is a good list of DOM events here...
http://en.wikipedia.org/wiki/DOM_events#HTML_events
In order to take advantage of the code you need to determine the event that best fits with your goal. Are you trying to do this when the form is submitted? That would be onsubmit. Are you trying to do this when the page loads? That would be onload.
Generally you can reuse events endlessly though you can only execute the onload event once.
If you visit my site and look at the JavaScript code you'll notice THREE things...
1.) An index.js file that is nothing but functions.
2.) An onload.js file with limited number of global variables (variables defined outside of a function) and the anonymous onload function.
Since you can only execute the onload event once if you want to do multiple things (e.g. execute multiple unrelated functions) you can use an anonymous function which is simply a function without a name...
window.onload = function()
{
my_func1();
my_func2();
my_func3();
}
Keep in mind that you should always keep script elements inside of the <head> element and not the <body> element otherwise it will lead you down a path of poor coding practices.
So if you create a standalone test file it may look something like this...
example.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test Page</title>
<script type="application/javascript">
//<![CDATA[
function form_days()
{
var d = document.getElementById('days');
var input_day = document.createElement('input');
input_day.setAttribute('id','days');
input_day.setAttribute('name','days');
input_day.setAttribute('type','text');
input_day.setAttribute('value',d.options[d.selectedIndex].text);
d.parentNode.insertBefore(input_day,d.nextSibling);
}
function get_methods(o)
{
var m = document.getElementById('dom_methods');
var dom_list = new Array();
for (i in o)
{
dom_list.push(i);
}
dom_list.sort();
for (var i=0; i<dom_list.length; i++)
{
m.value = m.value+dom_list[i]+'\n';
}
}
window.onload = function()
{
form_days();
get_methods(document.getElementById('days').options[document.getElementById('days').selectedIndex]);
}
//]]>
</script>
<style type="text/css">
label {border: #000 dotted 1px; padding: 0px 2px 0px 2px;}
label:hover {border: #000 solid 1px;}
textarea {height: 500px; width: 400px;}
</style>
</head>
<body>
<form action="http://www.test.com/school" method="post">
<fieldset>
<label for="days">Day:</label>
<select id="days" name="days">
<option value="2">Monday</option>
<option value="1">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<div><textarea id="dom_methods"></textarea></div>
<div><input type="submit" value="submit" id="submitday" /></div>
</fieldset>
</form>
</body>
</html>
You should be able to copy-and-paste this to a file, name it example.xhtml. It's all functional, tested and working at the highest standards. Keep in mind that Internet Explorer 8 and older is not capable of XHTML (application/xhtml+xml) or comprehending the CORRECT media type/mime for JavaScript which is application/javascript so if you require backwards compatibility using text/javascript on script elements is not valid though will work.
well, you could change the values of the options, for example using jquery like this:
$('select[name=days] option').each(function(){
$(this).val($(this).html());
});
http://jsfiddle.net/RCevC/
I think you're trying to update a text input when a user picks a selection from the dropdown? Try this:
html:
<select name="days">
<option value="2">Monday</option>
<option value="1">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<input type="text" id="your_input" /> <!-- I added this field to your code -->
<input type="submit" value="submit" id="submitday">
javascript (jquery)
$('select[name=days]').change(function(){
$('#your_input').val($(this).val());
});
http://jsfiddle.net/z3peu/2/
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.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Custom alert using Javascript
I want to create a confirmation message-"Do you want to proceed deleting? [Yes] or [No]".
I have a table with many data rows where the delete link is clicked in a particular row, the data in the row is deleted in the database. When the user clicks the delete option, i want to show the confirmation message first, so that user can validate his actions before deleting.
How can i do that dynamically using java script and css? I don't want to use alerBox() as it is ugly and is so unprofessional.
I am currently working for my school project-jsp and Java Servlet.
Hope any experts will help me. I love this forum as people here are very helpful. Advance thanks!
Actually you could do
window.alert = function(text) { /* some code to show a fancy dialog */};
window.confirm = function(question) { /* some code to show a fancy dialog and return the result */}
Problem is you're messing around where ought not mess around but the advantage is that even in 3rd party code any alerts() or confirms() will come up as your custom dialogs and the code will be simple to read (instead of $.dialog({options}) you just use a normal alert() or confirm call)
Because of the way JavaScript event handling works, there cannot exist any "drop-in" replacement for confirm, but popular JavaScript libraries such as jQuery UI include "modal dialog" features that can be used to achieve a similar effect.
http://www.jensbits.com/2009/08/10/modal-confirmation-dialog-on-form-submit-javascript-jquery-ui-and-thickbox-varieties/ is an example of how this works. Your "delete" button would not be set up to submit the form but rather open the modal dialog, which would submit the form if the user clicks OK.
If you want really to look good try this approach:Use for example jQuery and jQueryUI.
In your page put this:
<head>
<link rel="stylesheet" type="text/css" media="all" href="pathtoyourappfolder/jquery/css/black-tie/jquery-ui-1.8.4.custom.css" />
<script type="text/javascript" src="pathtoyourappfolder/jquery/js/jquery-1.4.2.min.js'" ></script>
<script type="text/javascript" src="pathtoyourappfolder/jquery/js/jquery-ui-1.8.4.custom.min.js'" ></script>
</head>
<body>
<div id="dialog-confirm" title="DELETE">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
Are you sure you want to delete this record?</p>
</div>
<table id="TblName">
<tr>
<td class="actions">
del
</td>
<td>...</td>
</tr>
<tr>
<td class="actions">
del
</td>
<td></td>
</tr>
</table>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#TblName td.actions a.del').click(function(event){
$("#dialog-confirm").dialog('open');
});
}
</script>
</body>
You can add onclick="deleteRow(row_id, this)" to each delete link. Usage of row_id assumes the table is being generated dynamically from a given set and you have an identifier to provide and pick the data to delete. The this is useful to remove the <tr> using Javascript.
Oh and of course the function would make a dialog popup. Use jQuery for that.
You can try FaceBox and FacyBox
http://chriswanstrath.com/facebox/
http://www.bitbonsai.com/facybox/
You can rewrite the functionality. I am intending you wanna know what's happening and how to achieve effects, instead of using a library like jQuery. jQuery and derived solutions can make your life easier, but if you want to know HOW to make it, continue reading.
First, you should make your own "alertBox", with your preferred CSS styling (including it's position) [I suggest position absolute, z-index:2], then in the CSS let its display property as hidden.
OK, now when user clicks your delete link/button you trigger a native javascript confirm dialog. Replace this confirm call, to a function that will display your own styled menu. changing its CSS display property from hidden to "block".
On your own styled menu buttons Yes/No, attach events, one for each button, with respective action (hide menu, or deleting row, removing current line from table...).
Well, that's the idea. Hope you enjoy.
I have a firm grasp on XHTML & CSS, but PHP & Javascript look like magic to me.
I'm building a discussion site using the PHP-based Textpattern CMS. When users are logged in, they can use a public-side form to add a new discussion topic. There are a lot of input fields, grouped by the HTML fieldset element within a single form element that adds a new row to a specific database table. What I want to do is show only one fieldset at a time, inserting previous and next links that will allow people to navigate between fieldsets.
Textpattern comes bundled with jquery, and I found a jquery plugin that describes this functionality. But I can't get it to work.
Here's what I have in my document head:
<style type="text/css" media="screen">
fieldset {display: none;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<script type="text/javascript" src="http://site.url/scripts/jquery.babysteps-0.2.1.js"></script>
<script type="text/javascript" language="javascript">
$('#step1').bindStep('#step2');
$('#step2').bindStep('#step3');
$('#step1').show();
</script>
My form is something like this:
<fieldset id="step1">
<legend>Step 1 Fields</legend>
<!-- fields -->
</fieldset>
<fieldset id="step2">
<legend>Step 2 Fields</legend>
<!-- fields -->
</fieldset>
<fieldset id="step3">
<legend>Step 3 Fields</legend>
<!-- fields -->
</fieldset>
<input type="submit" value="Post this Article!" />
The results are that the style declaration hides every fieldset, but the script doesn't show step1 at all. I've double-checked all the file paths, and I've tried this using a link to my local jquery bundle instead of the Google version, but I get the same results.
I would be happy if I could get this working, but if there is another way to achieve this without the babysteps plugin, I'd be happy with that outcome as well.
Any guidance or concrete advice you can offer would be greatly appreciated! Step-by-step instructions or practical troubleshooting questions (Do you have your computer plugged in?) might also be helpful.
Thanks in advance!
Im not sure on that particular plugin, but with just jquery:
$(function(){
$('#gotoStep2').click(function(){
$('#step1').hide();
$('#step2').show();
return false;
});
});
where you have
<input type="button" id="gotoStep2" value="next »"/>
inside step1
and your css:
#step2, #step3 //etc
{
display: none;
}
im sure you can work out how to repeat this for all your steps :)
<script type="text/javascript" language="javascript">
$(function(){
$("#step1").bindStep("#step2");
$("#step2").bindStep("#step3");
$("#step1").show();
});
</script>
If that doesn't work, ditch the plugin. (Seriously, not even the demo on that page works.)