Adding data dynamically to a HTML page - javascript

In a htmlpage using jQuery or JavaScript how can the following be achieved?
User types in a question in a textarea and press on enter button, then the same question should be displayed dynamically in the page below the textarea and the user can enter as many questions.
And when the user is done the page is submitted through a submit button.
Can you give a small hint of how this can be done?

Try this to get started :
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#textareabutton').click(function(){
var q = $('#textarea').val(),
$p = $('<p>').html( q );
$('#questions').append( $p );
});
$('#submit').click(function(){
var tab;
tab = $('#questions p').serializeArray();
// now do something with $.ajax to submit the questions
$.post("myphp.php",tab,function(resp){
// what do I do with the server's reply ???
});
});
});
</script>
<style type="text/css">
</style>
</head>
<body>
<textarea id='textarea'></textarea>
<button type='button' id='textareabutton'>Add question</button>
<div id='questions'></div>
<button type='button' id='submit'>Submit questions</button>
</body>
</html>

Use the innerHTML property of a div to add the questions to.

Related

Activating popup (HTML,PHP,Javascript/Jquery)

I have a simple request for you brainies today. What i am trying to do is to activate a pop-up inside PHP tags. I have tested to see if the pop-up works by itself, and it does. My problem is the button, i have used the same setup elsewhere, but this time no cigar. I have also tried echoing the button inside the PHP tags but nothing happens.
My code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="Lib\JqueryUIcss.css">
<script src="Lib\Jquerylib.js"></script>
<script src="Lib\JqueryUI.js"></script>
</head>
<body>
<button type=" button" class="LeButton"> Clicky Clicky!</button>
<?php
if(isset($_POST['LeButton'])){
echo'<script> $(function() { $( "#dialog" ).dialog(); }); </script>';
echo'<div id="dialog" title="Basic dialog">';
echo'<p>Image:</p>'; </div>';}
?>
</body>
</html>
I tried specifying it as a function aswell and added onclick() to the button to call that function, nothing happend either. Mind that this is the first time i am ever using Javascript/jQuery.
I (kindly) lauched a bit about the echo <script> part.
Allow me to write you a piece of code, with explanation and documentation:
HTML button:
<button type="button" id="LeButton" class="LeButton"> Clicky Clicky! </button>
&
<div id="dialog" title="Basic dialog" style="visibility:hidden"><p>Image:</p> <img src="http://placehold.it/50x50" alt="Placeholder Image" /></div>
Explanation:
Your button needs an id value. Which is called 'LeButton' in this example.
Documentation:
https://www.w3schools.com/tags/att_id.asp
jQuery part:
<script>
jQuery(document).ready(function() {
/**
* #version 1.0.0.
*
* Do magic on button click 'LeButton'
*/
$("#LeButton").click(function() {
$("#dialog").css("visibility", 'visible'); // make the div visible.
$("#dialog").dialog(); // Post here your code on forexample poping up your modal.
});
});
</script>
Explanation:
Your tag can be placed on the bottom of your page. Your browser will 'read' the whole page. By saying '(document).ready', your script will be executed once the page has been red by your browser.
For the '.click' part it's a jQuery function you can use. So which
means: once id attribute 'LeButton' (#) is clicked, jQuery will
execute a function, which will alert text in this case.
Documentation:
https://api.jquery.com/click/
Note: Make sure you have jQuery included/enabled.
Link:
https://jquery.com/download/
Note from Simon Jensen:
You should elaborate that the Class-attribute is for styling and the
Id-attribute can be for whatever code or identifying purposes and are
unique. Therefore should people be careful with styling with the
Id-attribute as things might conflict at some point. The ID-attribute
is used to interact with the "#LeButton" attribute.
The PHP can't be run from the client. If you want the dialog to be shown onclick of the button, you must send the element before it's clicked, at the moment when it is sent to the client. You should have the dialog element hidden until the user clicks the button. It could be something like:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="Lib\JqueryUIcss.css">
<script src="Lib\Jquerylib.js"></script>
<script src="Lib\JqueryUI.js"></script>
</head>
<body>
<button type=" button" class="LeButton" onclick="$('#dialog').dialog()"> Clicky Clicky!</button>
<div id="dialog" title="Basic dialog" style="display:none">
<p>Image:</p>
</div>
</body>
</html>
You could also change the onclick attribute to a script in the head like this:
<script>
$(function() {
$(".LeButton").click(function() {
$('#dialog').dialog();
});
});
</script>
I recommend you to change the class of the button for an id, and then using #LeButton instead of .LeButton
You can handle this on the client-side without the need to use PHP to do so you need to give your button a unique identifier so whenever the button is clicked you can open the dialog using a simple evenlisener like so:
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
close: function() {
// do stuff here whenever you close your dialog
}
});
document.getElementById('my-button').addEventListener('click', function () {
dialog.dialog('open');
});
#dialog-form {
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<button type=" button" id="my-button" class="LeButton"> Clicky Clicky!</button>
<div id="dialog-form">
Name: <input><br/>
Password: <input type="passowrd">
</div>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="Lib\JqueryUIcss.css">
<script src="Lib\Jquerylib.js"></script>
<script src="Lib\JqueryUI.js"></script>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="LeButton" value="an_arbitraty_value">
<input type="submit" class="LeButton">
</form>
<?php
if(isset($_POST['LeButton'])){
echo'<div id="dialog" title="Basic dialog">';
echo'<p>Image:</p></div>';
}
?>
</body>
</html>
When you load the html page $_POST['LeButton'] is not set. Therefore the intended dialog box wil not be generated in the page. In order to have $_POST['LeButton'] set, you should pass it to the html page first, hence the form I added.
Alternatively you could go for a full javascript solution like so:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style>
.hidden { display: none }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<button type=" button" class="LeButton" onclick="showDialog();">
Clicky Clicky!
</button>
<div id="dialog" title="Basic dialog" class="hidden">
<p>
This is the default dialog which is useful for displaying information.
The dialog window can be moved, resized and closed with the 'x' icon.
</p>
</div>
<script>
function showDialog() {
$( "#dialog" ).dialog();
};
</script>
</body>
</html>

Javascript variable, set to HTML object, always returns null

I need to display a dialog box based on user input, and I'm implementing the Zebra dialog plug-in to help with this.
I can get a generic dialog to show up when the user clicks a button, but no matter what I do, I can't get the Javascript to see the HTML text box, let alone the data inside it.
I have created a test page for this. See below.
Here is the HTML/PHP code (index.php):
<head>
<!-- Style for Zebra Dialog boxes -->
<link rel="stylesheet" href="zebra/zebra_dialog.css" type="text/css">
</head>
<header>
<h1>Testing My Dialogs and Alerts</h1>
</header>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$myTyping = trim($_POST["myTyping"]);
// Display what the user typed in a dialog. Is there some code that needs to go here?
}
?>
<form id="form_to_submit" action="index.php" method="POST">
<fieldset>
<label>Type anything you want:</label>
<input type="text" name="myTyping" id="myTyping">
<button type="submit" id="click">Click Here to show alert and see what you typed.</button>
</fieldset>
</form>
<!-- Link to jQuery file so any plug-ins can work
Including the production version here. Can also download one for better debugging. -->
<script type="text/javascript" src="jquery-1.12.0.min.js"></script>
<!-- Link to Zebra Dialog box code -->
<script type="text/javascript" src="zebra_dialog.js"></script>
<!-- Link to My Javascript code -->
<script type="text/javascript" src="myTestScripts.js"></script>
</body>
And here is the Javascript code (myTestScripts.js). I have tried 3 different ways to get the user's input and display it, but "getElementById" never works. Is it not rendered yet? I tried putting in prevent default code, but that makes no difference.
/* javascripts */
// FIRST TRY
$(document).ready(function() {
// show a dialog box when clicking on a button
$("#click").bind('click', function(e) {
//e.preventDefault();
$.Zebra_Dialog('The link was clicked!');
**var myInputElement = document.getElementById("myTyping"), // This doesn't get the element, always is null**
myInput = myInputElement.innerText;
console.log("myInputElement: " + myInputElement);
console.log("myInput: " + myInput);
$.Zebra_Dialog('Here is what you typed:', myInput);
});
});
// SECOND TRY
$('#form_to_submit').submit(function(e) {
console.log("inside form_to_submit");
**var myInputElement = document.getElementById("myTyping"), // also returns null**
myInput = myInputElement.innerText;
console.log("myInputElement: " + myInputElement);
console.log("myInput: " + myInput);
$.Zebra_Dialog('Here is what you typed:', myInput);
console.log("leaving form_to_submit");
});
// THIRD TRY
window.onsubmit = function (e) {
console.log("inside window.onsubmit, preventing default");
//e.preventDefault();
**var myInputElement = document.getElementById("myTyping"), // also returns null**
myInput = myInputElement.innerText;
console.log("myInputElement: " + myInputElement);
console.log("myInput: " + myInput);
$.Zebra_Dialog('Here is what you typed:', myInput);
console.log("leaving window.onsubmit");
}
You element is a input so innerText will not work.
Instead of
var myInputElement = document.getElementById("myTyping"),
myInput = myInputElement.innerText;
try
var myInputElement = document.getElementById("myTyping"),
myInput = myInputElement.value;
or simply
var myInput = document.getElementById("myTyping").value;
Take a look at input text object properties here
Use jQuery:
$(document).ready(function() {
// show a dialog box when clicking on a button
$("#click").bind('click', function(e) {
e.preventDefault();
$.Zebra_Dialog('Here is what you typed: '+$("#myTyping").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<!-- Style for Zebra Dialog boxes -->
<link rel="stylesheet" href="http://dynabitlab.it/extensions/demo_virtuemart/modules/mod_vavmm/admin/zebra/css/flat/zebra_dialog.css" type="text/css">
</head>
<header>
<h1>Testing My Dialogs and Alerts</h1>
</header>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$myTyping = trim($_POST["myTyping"]);
// Display what the user typed in a dialog. Is there some code that needs to go here?
}
?>
<form id="form_to_submit" action="index.php" method="POST">
<fieldset>
<label>Type anything you want:</label>
<input type="text" name="myTyping" id="myTyping">
<button type="submit" id="click">Click Here to show alert and see what you typed.</button>
</fieldset>
</form>
<!-- Link to jQuery file so any plug-ins can work
Including the production version here. Can also download one for better debugging. -->
<script type="text/javascript" src="jquery-1.12.0.min.js"></script>
<!-- Link to Zebra Dialog box code -->
<script type="text/javascript" src="zebra_dialog.js"></script>
<!-- Link to My Javascript code -->
<script type="text/javascript" src="http://dynabitlab.it/extensions/demo_virtuemart/modules/mod_vavmm/admin/zebra/javascript/zebra_dialog.js"></script>
</body>

display a save bottom edit text in editable button

here is my code. i have a text. and a button for editing the text.i want to click the edit button then that time display a btn as name save . for saving the change that i have. what should i do? help me friends
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../../../Editable/css/minified-std-acount.css">
<title>Untitled Document</title>
<script src="../../../eanjoman/js/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(e) {
$('button').click(function(){
var $div=$('div'),
isEditable=$div.is('.editable');
$('div').prop('contenteditable',!isEditable).toggleClass('editable')
})
});
</script>
<style>
.editable{ background:#EAEAEA}
</style>
</head>
<body>
<div>Some text</div><br><br><button>Toggle editable</button>
</body>
</html>
Well you can just add one line code here:
DEMO
$('button').click(function(){
var $div=$('div'),
isEditable=$div.is('.editable');
$('div').prop('contenteditable',!isEditable).toggleClass('editable')
$(this).text('Save'); //Add this
})
UPDATE
UPDATED DEMO
To toggle it back just check for its text as below:
$('button').click(function(){
var $div=$('div'),
isEditable=$div.is('.editable');
$('div').prop('contenteditable',!isEditable).toggleClass('editable')
if($(this).text()!="Save") //Add this condition
$(this).text('Save');
else
$(this).text('Toggle editable');
})

Changing element text isn't working

It always seems to be a problem and I fail to see why, I'm trying to change element p text by using his ID, element p id="para1" is inside PostEditor.html:
The elementID I want to change is para1 in the following html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
The following function is issued by a click on a link inside index.html and displaying the page you are seeing above and is then supposed to change its content:
From index.html I issue the function from link:
<a onclick="postEditing()"> Edit</a>
This line issue the following function:
function postEditing()
{
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.document.getElementById("para1").innerHTML = "11111111111";
result.document.getElementById("para1").innerText = "11111111111";
result.document.getElementById("para1").value = "11111111111";
}
As you can see I tried three methods. I'd never understand what is the difference between them, but I tried all three and none worked!
It's because you're searching the document of the window which shows the index.html, not the document of the newly opened window. try following:
...
var editorWindow = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
editorWindow.document.getElementById("para1").innerHTML = "11111111111";
...
EDIT:
NOW i see the problem: in the function you're trying to access a property of the parameter element, but you don't pass a value for it. So this will end in an error because the accessed object is undefinded!
So you have three options to get it working:
test the parameter (always a good idea): var ID = null; if(element) ID = element.id;
pass a value: <a onclick="postEditing(this)"> Edit</a>
remove the line var ID = element.id;
SOLUTION: (TESTED)
I could not really say why, but the index.html found the para1 and can successfully set the new text. But somehow the new window will reinitialize the old value again.
So you have to do the changing in an handler you run at onLoad:
index.html:
<html>
<head>
<script>
function postEditing() {
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.onload = function() {
result.document.getElementById("para1").innerHTML = "11111111111";
}
}
</script>
</head>
<body>
<a onclick="postEditing()"> Edit</a>
</body>
</html>
PostEditor.html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
I'm fairly sure you will need to query the return result of calling window.open like this:
function postEditing(element)
{
var ID = element.id;
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.getElementById("para1").innerHTML = "11111111111";
result.getElementById("para1").innerText = "11111111111";
result.getElementById("para1").value = "11111111111";
}
[Untested though]
Your button type is submit, which is posting the form. The object is changing in the DOM, only after the script runs, the DOM is reloaded back to it's original state. Try changing your button type to "button", and you should see the P element change appropriately.
Edit: Here's the HTML I used to determine the above. Keeping the button as "submit" caused me to see the text change and then swap back. The HTML below should keep the text in place. HTH!
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<script>
function postEditing(element)
{
document.getElementById('para1').innerHTML = "asdafs";
}
</script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="button" onclick="postEditing('caller')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>

Inserting Row in Table inside Form tag autosubmitting in firefox/chrome

I have a form that will have dynamic elements inserted with javascript and am experiencing some strange behavior. When I click the button to add another element to the table in the form, it adds the element but seems to to a form post immediately (without intending to submit the form yet)
I have created a simplified example of the page that has the same behavior. the first table element is created on page load and subsequent elements are added when clicking on the button. this form works successfully in IE. does anyone have an idea of how to prevent this behavior?
here is the code sample.
<!DOCTYPE html>
<html>
<head>
<title>Test Creating Form</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<style type="text/css">
td{font-family:verdana;}
</style>
<script type="text/javascript">
var counter = 0;
function makeTitle(title){
if(counter){
title += " " + counter;
}
counter++;
var tbl = document.getElementById('tbl');
var tr = tbl.insertRow(-1)
var td1 = tr.insertCell(-1);
td1.innerHTML = title;
}
function load1(){
makeTitle('Primary Specimen');
}
</script>
</head>
<body onload="load1();">
<form action="formtest.htm" method="post" name="testForm" id="testForm">
<table id="tbl" border="1"></table>
<button onclick="makeTitle('Alternate Specimen')" id="clone" >Add Another Specimen</button>
</form>
</body>
</html>
Button tags default to type="submit"; add type="button".
Cancel the click event with return false; or add type="button". A <button /> without a type-attribute is per default a submit-button.
<button type="button" onclick="makeTitle('Alternate Specimen')" id="clone" >Add Another Specimen</button>

Categories