I had to edit existing HTML (change title and variables) and run it through Firebug. My radio buttons are boxes (or not showing at all) and I don't know why. I've attached a screenshot of both the HTML code and the Firebug output. I used an online converter to convert the HTML to JavaScript. I am new to JavaScript and am having a hard time getting a handle on this. Any help would be appreciated!
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Radio Buttons</TITLE>
<META content=3D"text/html; charset=3Dwindows-1252" =
http-equiv=3DContent-Type>
<SCRIPT type=3Dtext/javascript>
function pick_a_business_card(){
var base_cost =3D get_business_card_value();
alert(base_cost);
}
function get_business_card_value(){
var radio_buttons =3D document.getElementsByName('business card');
for (var i =3D 0, length =3D radio_buttons.length; i < length; i++) {
=09
if (radio_buttons[i].checked) {
return radio_buttons[i].value;
}
}
}
</SCRIPT>
<META name=3DGENERATOR content=3D"MSHTML 8.00.7601.18129"></HEAD>
<BODY>
<FORM id=3Dbusiness_card_addons_calculation_form method=3Dpost action=3D#>
<H2>Radio Buttons</H2>
<P><STRONG>Pick a Business Card:</STRONG><BR><BR><INPUT id=3Dvertical value=3Dvertical
=
type=3Dradio=20
name=3Dcolor> <LABEL for=3Dvertical>Vertical</LABEL> <BR><INPUT id=3Dhorizontal =
value=3Dhorizontal=20
type=3Dradio name=3Dcolor> <LABEL for=3Dhorizontal>Horizontal</LABEL> <BR><INPUT =
id=3DFoldover=20
value=3Dfoldover type=3Dradio name=3Dcolor> <LABEL for=3DFoldover>Foldover</LABEL> =
</P>
<P><INPUT onclick=3Dpick_a_business_card() value=3D" Submit " =
type=3Dbutton></P>
</FORM>
</BODY>
</HTML>
It appears some things were encoded improperly in your conversion.
I cleaned up your code a bit here which should help get you started
Here is the full HTML:
<html>
<head>
<script>
function pick_a_business_card(){
var base_cost = get_business_card_value();
alert(base_cost);
}
function get_business_card_value(){
var radio_buttons = document.getElementsByName('color');
for (var i = 0, length = radio_buttons.length; i < length; i++) {
if (radio_buttons[i].checked) {
return radio_buttons[i].value;
}
}
}
</script>
</head>
<body>
<FORM id=business_card_addons_calculation_form method=post action=#>
<H2>Radio Buttons</H2>
<P><STRONG>Pick a Business Card:</STRONG><BR><BR><INPUT id=vertical value=vertical
type=radio
name=color> <LABEL for=vertical>Vertical</LABEL> <BR><INPUT id=horizontal
value=horizontal
type=radio name=color> <LABEL for=horizontal>Horizontal</LABEL> <BR><INPUT
id=Foldover
value=foldover type=radio name=color> <LABEL for=Foldover>Foldover</LABEL>
</P>
<P><INPUT onclick=pick_a_business_card() value=" Submit "
type=button></P></FORM>
</body>
</html>
Additionally, I'd recommend putting quotes around your HTML attributes.
Related
I have these below codes which give user option to reserve a seat according to their choice. These 3 mentioned below are difficulties that I am facing I need help.
To send the total value of a variable named total from Javascript to PHP
To send the total number of selected seats which are being hold by a variable called results from Javascript to PHP
How to make a Reserve Now button inactive if a user did not select any seat from checkbox.
These below are my codes.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Seat(s)</title>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['submit'])) { //Seat Reserve
require 'action_page.php';
}
elseif (isset($_POST[''])) { //Cancel
require 'mypage.php';
}
}
//
$parameter = "this is a php variable";
echo "var myval = foo(" . parameter . ");";
?>
?>
<h2>Please choose a seat to book</h2>
<form action="index.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="50"> $50<br>
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span> <!-- container for selected seats -->
<br>
Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit">Reserve Now</button>
</p>
</form>
<script>
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join(",");
//window.alert(result); //Hold Number of Seats Selected.
//window.alert(total); //Hold Total Cost of Selected Seats.
}
var myval = foo("this is a php variable"); // I tried to take this value and output it but it didn't work out.
$.ajax({
type: 'POST',
url: 'action_page.php',
data: {'variable': total},
});
</script>
</body>
</html>
action_page.php
<html>
<head>
<title>Seats Feedback</title>
</head>
<body>
<?php
echo "<br>";
$myval = $_POST['variable'];
print_r($myval);
?>
Looking forward to hear from you guys.
When you're not doing AJAX, posting data to a PHP script the old fashioned way is a matter of:
setting the action attribute on a <form> element to point to the destination PHP script URL
ensuring your form's <input> elements contain all of the data you want to post
adding a submit button to the form
For step 1, currently, your form says to send the post request to itself. This is totally fine (you can use a <?php block ?> like you're doing to determine whether to show a success confirmation or a blank form depending on the contents of $_POST, but I'm guessing your intention is to ultimately send the data over to action_page.php. I made that the action target and removed all of the PHP from your index.
As for step 2, your total isn't currently in an <input> element and won't be posted. I created an invisible total element for this purpose: <input type="hidden" name="total" id="hidden-total" value="0"> and added a couple lines to the script to retrieve this element and set its value whenever your total is recalculated. You could combine the two total elements and style one to look and be non-editable (exercise for the reader).
Another problem relating to step 2 is that you have four different elements with the name vehicle. Only one of these name/value pairs will be posted, so I updated these elements to use unique names so they'll all be sent.
Step 3, making sure you have a submit button, you've already done successfully.
To verify it's working, you can var_dump($_POST) on the receiving PHP script to see the results of the post request or retrieve a specific value by name with e.g. $_POST['total']. At this point, your PHP script can go ahead and parse/validate/sanitize the post data, render proper response output, do a redirect, and/or do whatever else needs to be done, such as writing to a database.
Here's the full code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Seat(s)</title>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="action_page.php" method="post">
<input type="checkbox" name="vehicle-a1" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle-a2" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle-a3" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle-a4" id="A4" value="50"> $50<br>
<input type="hidden" name="total" id="hidden-total" value="0">
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span> <!-- container for selected seats -->
<br>
Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit">Reserve Now</button>
</p>
</form>
<script>
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const hiddenTotalElem = document.getElementById("hidden-total");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
hiddenTotalElem.value = total;
seatsElem.innerHTML = result.join(",");
}
</script>
</body>
</html>
action_page.php
<!DCOTYPE html>
<html lang="en">
<head>
<title>Seats Feedback</title>
</head>
<body>
<?php
echo "<pre style='font-size: 1.5em;'>"; // format debug post dump
var_dump($_POST);
?>
</body>
</html>
Sample output
array(5) {
["vehicle-a1"]=>
string(3) "100"
["vehicle-a3"]=>
string(2) "55"
["vehicle-a4"]=>
string(2) "50"
["total"]=>
string(3) "205"
["submit"]=>
string(0) ""
}
As before, this isn't an industrial strength example and there is plenty of room for improvement, but hopefully it does communicate the basic idea.
Disclaimer: I am not looking for someone to code this for me just some pointers to help me fix this problem :)
I have the following web page that allows me to add fields dynamically to a form. The current page works. What I want to do is figure out how to make the javascript at the bottom of the page more generic. example I want to pass the templet id and the target id to the function without hard coding the templet id and the target id into the script. Here is the code that I have and works just fine.
I want to make the morefields function so that I can reuse. I want to pass to the function the template and the target. example function moreFields ( templete, target). this way I can use the same function without editing over and over in different web pages. if you look in to the moreFields function you will see that it is hard coded for "readroot" and "writeroot" I want to change the function so it will take parameters and do the same thing it is doing now.
<HTML>
<HEAD>
<META NAME="generator" CONTENT=
"HTML Tidy for Linux/x86 (vers 25 March 2009), see www.w3.org">
<TITLE></TITLE>
<STYLE TYPE="text/css">
div.c1 {display: none}
</STYLE>
</HEAD>
<BODY >
<DIV ID="readroot" CLASS="c1">
Variable Name <INPUT NAME="VarName"><BR>
</DIV>
<FORM METHOD="post" ACTION="/cgi-bin/show_params.cgi">
Function Name: <INPUT NAME="CFunction"> <BR>
Function Alias: <INPUT NAME="AFunction"><BR>
<BR>
<SPAN ID="writeroot"></SPAN>
Function return: <INPUT NAME="AFunction"><BR>
<INPUT TYPE="button" ID="AddMoreFields" VALUE="Give me more fields!" ONCLICK= "moreFields()"> <INPUT TYPE="submit" VALUE="Send form">
</FORM>
<SCRIPT >
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById("readroot").cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById("writeroot");
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields()
</SCRIPT>
</BODY>
</HTML>
I can not get the values from the javascript add row to go dynamically as a row into MySql only the form values show up as the form below as one row. I made it as an array, but no such luck, I have tried this code around a multitude of ways. I don't know what I am doing wrong, kindly write out the correct way.
My code for example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Fields js/php to MySql need to submit dynamically to the database</title>
<?php
require ('database.php');
?>
<script type="text/javascript">
var counter = 1;
var collector = "";
function addfields(indx)
{
var tbl = document.getElementById('table_id');
var newtr = document.createElement('tr');
counter = counter + indx;
newtr.setAttribute('id','tr'+counter);
newtr.innerHTML = '<td><input type="checkbox" name="checkb'+counter+'" id="checkb'+counter+'" value="'+counter+'" onclick="checkme('+counter+')"></td><td><input type="text" name="text1[]"></td><td><textarea name="textarea1[]"></textarea></td>';
tbl.appendChild(newtr);
}
function checkme(dx)
{
collector += dx+",";
}
function deletetherow(indx)
{
var col = collector.split(",");
for (var i = 0; i < col.length; i++)
{
var remvelem = document.getElementById('tr'+col[i]);
var chckbx = document.getElementById("checkb"+col[i]);
if(remvelem && chckbx.checked)
{
var tbl = document.getElementById('table_id');
tbl.removeChild(remvelem);
}
}
}
</script>
</head>
<body>
<form enctype="multipart/form-data" id="1" style="background-color:#ffffff;" action="<?php echo $_SERVER['PHP_SELF']; ?>"></form>
<table id="table_id" >
<tr id="tr1" class="trmain">
<td>
</td>
<td>
<input type="text" name="text1[]">
</td>
<td>
<textarea name="textarea1[]"></textarea>
</td>
</tr>
</table>
<input type="button" value="Add" onClick="addfields(1);" />
<input type="button" value="Delete" onClick="deletetherow()" />
<input type="submit" value="Send" id="submit" name="submit"/>
<?php
if(isset($_POST['submit'])) {
for ($i=0; $i < count($_POST['text1']); $i++ )
{
$ced = stripslashes($_POST['text1'][$i]);
$erg = stripslashes($_POST['textarea1'][$i]);
$bnt = mysql_query("INSERT INTO tablename (first, second) VALUES ('$ced', '$erg')")or
die ('Error: '. mysql_error() );
}
}
?>
</body>
</html>
Here is a perma link for anyone: Dynamic Fields js/php to MySql need to submit dynamically to the database
If you are seeking answer to this subject, then Sean was right, it actually never overwrote the other as just first inputs submitted to MySQL as others ignored as wasn't part of loop. His innerhtml dynamic with loop is working.
If you want the code, its' above-edited or take from perma. There are not a whole lot of these working examples on the web, now you can go further with jQuery with this and getting more popular.
I´ve read a lot of post about jQuery serialize() but I cant get it to work with my form!
I works when I print out the form using html+php but not when I use javascript to print out the form. What am I missing?
I know there is a bunch of post about this but every one I´ve found is about ppl forgetting name="" or disabled the ( Try my code here: http://jsfiddle.net/ZBxkz/1/ )
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>MerBeer</title>
<!-- //jquery -->
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<!-- //Ajaxscript: -->
<script type="text/javascript">
$(document).ready(function () {
$("#knappen")
.delegate('button[name="minKnapp"]', "click", beer_insert);
$("#theForm")
.delegate('button[name="beer_form_submit"]', "click", serial);
function serial(){
var f = $('#beer_form'); // CHANGE THIS VALUE TO CHANGE FORM!! #beer_form and #testForm
var beerContainer = f.serialize();
alert (beerContainer);
}
function beer_insert() {
//hide first button
$('#dold').hide();
//Dynamically added form
$('#theForm').html('Test :<br><form name="beer_form" id="beer_form"><table id="beers">');
for (var i = 0; i < 1; i++){
$('#theForm').append('<tr><td><input type="text" name="beerCountry" id="beerNo_'+i+'_country" /></td></tr>');
}
$('#theForm').append('</table></form><br>');
$('#theForm').append('<button name="beer_form_submit">Second button</button><br>')
}
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- Form that works-->
<form id="testForm" name="testForm">
<table>
<?php
for($i = 0; $i < 3; $i++){
echo('<tr><td><input type="text" name="test" id="inget'.$i.'"/></td></tr>');
}
?>
<tr><td><input type="text" name="test" id="ingetA"/></td></tr>
<tr><td><input type="text" name="test" id="ingetB"/></td></tr>
</table>
</form>
<div id="theForm"></div>
<div id="knappen"><button id="dold" name="minKnapp">The Button</button></div>
</body>
I hope I got your question right, but probably you want this?: http://jsfiddle.net/jyM5Z/
Don't put your html together with many appends. Instead first build a complete html string and then add it to your container. This will not only make it much faster but will also protect you from unexpected behaviour because the browser parses your HTML fragment and changes it in order to make sense (like automatically close open tags).
You're not appending into your form, but rather you're appending after it. So when you call serialize, there's literally nothing to serialize.
// this creates the form
$('#theForm').html('Test :<br><form name="beer_form" id="beer_form"><table id="beers">');
// but these don't append INTO it
for (var i = 0; i < 1; i++){
$('#theForm')
.append('<tr><td><input type="text" name="beerCountry" id="beerNo_'+i+'_country" /></td></tr>');
}
$('#theForm').append('<button name="beer_form_submit">Second button</button><br>')
This is pretty much what you want your workflow to be:
// create my form
var my_dynamic_form = $('<form></form>');
// append to it
for (;;) {
my_dynamic_form.append('<input/>');
}
// append your form to the DOM
$('#my_form').append(my_dynamic_form);
I am beginner to html. I have two text boxes say t1 and t2 If t1 is filled with some data then then other text box t2 should be disable. Please let me know hot to do it. Thanks in advance
Based on your simple scenario description, here's an implementation that works cross-browser and without any third-party javascript library:
<html>
<head>
<script type="text/javascript">
window.onload = function(){
var t1 = document.getElementById("t1");
var t2 = document.getElementById("t2");
t1.onchange = function(){
t2.disabled = t1.value.length > 0;
}
}
</script>
</head>
<body>
<form>
t1:<input type="text" id="t1" name="t1" /><br/>
t2:<input type="text" id="t2" name="t2" />
</form>
</body>
</html>
<head>
<script type="text/javascript">
function verify(){
var t1 = document.getElementById ('first');
var t2 = document.getElementById ('second');
if (t1.value != '') {
t2.setAttribute('disabled','disabled');
return true;
}
if (t2.value != '') {
t1.setAttribute('disabled','disabled');
return true;
}
}
</script>
</head>
<body>
...
<input type="text" id="first" onblur="verify()">
<input type="text" id="second" onblur="verify()">
...
</body>
You can't achieve this with plain HTML.
Following the guidelines of progressive enhancement, you should first implement a server side check in whatever form handler you are using to process the submitted data.
Then you can consider adding JavaScript for a client side check. Something along the lines of:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Disabling form controls</title>
</head>
<body>
<form id="myForm" action="http://example.com/">
<div>
<input name="t1">
<input name="t2">
</div>
</form>
<script type="text/javascript">
(function () {
var t1 = document.forms.myForm.elements.t1;
var t2 = document.forms.myForm.elements.t2;
var handler = function handler() {
t2.disabled = (t1.value !== "");
};
t1.onchange = handler;
}());
</script>
</body>
</html>
(Although I would use a library such as YUI or jQuery to add event handlers in a fashion that is better protected from overwriting in a crossbrowser compatible way).
You might want some tutorials on JavaScript and the DOM so that this makes sense.