how to update several span elements based on user input HTML - javascript

I have a huge form with at least 200 input fields- text/radio/checkboxes.
I have divided this into several sections to structure it well and there is an update button for each section which takes the user input and persists it to the db. This is done by Ajax so I don't have to reload the page.
How can I easily update the <span>s corresponding to the input fields with whatever the user inputs without reloading the page? DO I have to do a $("#spanid").html($("#input1").val()) on each <span> item or is there an easy way to do this?
Here's the code for a fraction of the form.
HTML
<form id="history" name="history" action="" method="post">
<table class="normal">
<tr><th colspan="8">HISTORY</th>
</tr>
<tr><td style="width:200px"><b>Chief Complaint Location</b></td>
<td style="width:450px"><b>Comment</b></td>
<td><b> Previous</b> </td>
</tr>
<tr><td>Head</td>
<td ><input type="text" maxlength="100" name="headH" id="headH" ></td>
<td class="data2"><span id="headSpan"><%=msmtCommentHead%></span></td>
</tr>
<tr><td>Neck</td>
<td><input type="text" maxlength="100" name="neckH" id="neckH" ></td>
<td class="data2"><span id="neckSpan"><%=msmtCommentNeck%></span></td>
</tr>
<tr><td>Upper Extremeties</td>
<td><input type="text" maxlength="100" name="upperExtremetiesH" id="upperExtremetiesH"></td>
<td class="data2"><span id="ueSpan"><%=msmtCommentUpperExtremeties%></span></td>
</tr>
<tr><td>Thoracic Spine</td>
<td><input type="text" maxlength="100" name="thoracicSpineH" id="thoracicSpineH"></td>
<td class="data2"><span id="tsSpan"><%=msmtCommentThoracicSpine%></span></td>
</tr>
<tr><td><input type="button" id="submitHistory" value="Update"/></td></tr>
</table>
</form>
Javascript:
$(function(){
$("#submitHistory").click(function() {
var query = $("#history").serialize();
$.ajax( {
type: "POST",
url: "/oscar/cmcc/History.do",
dataType: "json",
data: query
});
document.getElementById('history_cmcc').reset();
var date = new String("<%=date%>");
$("#headSpan").innerHTML = $("#headH").val()+ "," + date;
$("#neckSpan").innerHTML = $("#neckH").val() + ","+ date;
$("#tsSpan").innerHTML = $("#thoracicSpineH").val() + ","+ date;
$("#lsSpan").innerHTML = $("#lumbarSpineH").val() + ","+ date;
$("#leSpan").innerHTML = $("#lowerExtremetiesH").val() + ","+ date;
$("#chSpan").innerHTML = $("#chestHeartH").val() + ","+ date;
}
Thanks!

In general you can do this:
$('input[type=text]').each(function() {
$(this).closest('tr').find('span').html($(this).val());
});
$('input:checked').each(function() {
$(this).closest('tr').find('span').html($(this).val());
});
Update per OP comment:
In your example if you wanted to put the label that is to the left of a radio button inside the span you could do this. This depends on your specific requirements.
$('input[type=radio]:checked').each(function() {
$(this).closest('tr').find('span').html($(this).closest('tr').find('td:eq(0)').text());
});

$(':input').each(function() {
$(this).closest('tr').find('span').html(this.value);
});
:input applied for all inputs. Also can use input.

Related

Issue with the way data is displayed in confirm box

I have a form with multiple text boxes where I can type a material name and in another box I can type the material price.
When the user clicks submit I am displaying a confirm box with the entered material(s) and price(s). In this confirm box I want to show all entered matr_name with the associated matr_price (one per line). I just can not seem to make it display as I want, the below script outputs like this:
matr_name
matr_price
matr_name
matr_price
etc.
I want it to display like this:
matr_name: matr_price
matr_name: matr_price
matr_name: matr_price
etc.
All I got is the below script which gives me the correct output, just not displayed as I want it in the confirm box.
Script
var matr_name = $("input[name*='matr']").map(function() {
return $(this).val()}).get().join('\n');
var confirm_form = confirm("Rep:\n" + matr_name);
console.log("Mart.: " + matr_name);
if(confirm_form == true)
{
return true;
}
else {
return false;
}
}
Part of the form:
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<input type="submit" name="submit_name" id="submit_id" class="submit" value="Done" onclick="javascript:return show_confirm();"/>
You can put different strings after the value depending on the name:
var matr_name = $("input[name*='matr']").map(function() {
return $(this).val() + ($(this).attr('name') == 'matr_name[]' ? ': ' : '\n');
}).get().join('');
or:
var matr_name = $("input[name*='matr']").map(function() {
if ($(this).attr('name') == 'matr_name[]') {
return $(this).val() + ': ';
} else {
return $(this).val() + '\n';
}
}).get().join('');

How do I get text from input boxes to appear in a popup window?

How would I go about extracting the info from the input boxes and display it in a separate popup window at the click of a button?
Example below:
HTML coding:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<table style="width: 50%" cellspacing="0" cellpadding="0">
<tr>
<td>Firstname</td>
<td><input type="text" id="firstname"></td>
</tr>
<tr>
<td>Lastname</td>
<td><input type="text" id="lastname"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" id="address"></td>
</tr>
<tr>
<td>Telephone</td>
<td><input type="text" id="telephone"></td>
</tr>
</table>
<input type="button" value="show details">
</body>
</html>
I guess, the simplest way to send data from one web page to another is using the GET method of HTML's forms.
Let's say, your input boxes are implemented in file form.html:
<html>
<body>
<form action="./display.html" method="GET">
<table>
<tr><td>First Name:</td><td><input type="text" name="firstname"></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lastname"></td></tr>
<tr><td>Phone number:</td><td><input type="tel" name="phonenumber"></td></tr>
</table>
<input type="submit" value="submit">
</form>
</body>
</html>
If you type in your first and last name as well as your phonenumber and press the submit button, you will be redirected to the file display.html. Furthermore, your browser appends the data of the form to the url in the following way:
display.html?firstname=Albert&lastname=Einstein&phonenumber=555-12345
(if you are Albert Einstein ;) )
More precisely, it takes the name information of each form element adds an = and then the information given by the user. If more than one form element is inside the <form></form> tags, each of that key-value pair is separated by a &.
In order to retrieve the data in the file display.html, you have to use a bit of javascript:
<html>
<body>
<table>
<tr>
<td>First name: </td><td><span id="firstname"></span></td></tr>
<td>Last name: </td><td><span id="lastname"></span></td></tr>
<td>Phone number: </td><td><span id="phonenumber"></span></td>
</tr>
</table>
<script>
var queryvars={};
function getQueryVariables() {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
queryvars[pair[0]]=pair[1];
}
}
getQueryVariables();
document.getElementById("firstname").innerHTML=queryvars['firstname'];
document.getElementById("lastname").innerHTML=queryvars['lastname'];
document.getElementById("phonenumber").innerHTML=queryvars['phonenumber'];
</script>
</body>
</html>
It takes everything after the ? of the current url, namely, firstname=Albert&lastname=Einstein&phonenumber=555-12345, splits it at every &, such that you end up with a list of key-value pairs. After that, it splits each of these key-value pairs at the = and stores the information in the queryvars variable. Finally, the information is inserted into the corresponding <span></span> of the table displayed to the user.
I hope, this answers your question.
I was thinking something along the lines of this concept:
function show_mailing_address() {
var width = 200
var height = 150
var left = parseInt((screen.availWidth/2) - (width/2))
var top = parseInt((screen.availHeight/2) - (height/2))
var windowFeatures = "scrollbars=no, toolbar=no,menubar=no,location=no, width=" + width + ",height=" + height + ",status=no,resizable=yes,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
win = window.open('', '_blank', windowFeatures)
var html = '<p style="text-align: center;">' +
document.getElementById('firstname').value + ' ' +
document.getElementById('lastname').value + '<br>' +
document.getElementById('address').value + '<br>' +
document.getElementById('telephone').value + '</p>'
if (win) {
win.document.write(html)
win.document.title = 'Mailing Address'
win.document.close()
win.focus()
}
return false;
}

How to add and remove lines from a html table

I have the table:
<table id="form_Dependentes" width="100%" cellpadding="0" cellspacing="0" class="form">
<tr>
<th colspan="4" valign="middle" scope="col">Dependentes</th>
</tr>
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_01" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_01" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_01" maxlength="10" /></td>
</tr>
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_02" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_02" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_02" maxlength="10" /></td>
</tr>
... etc.
</table>
This table is formatted to be printed and used online. Online, I wish to put buttons to add and remove those lines with input tags above the header. Is not complicate to format the html, but I was thinking about removing and adding tr lines using xml javascript capabilities, but don't know exactly how...
Edit: I don't get what so wrong with this question that is getting negative. Whatever... I'm working in this code:
var cadFormTableRow;
var cadFormTable;
function cadFormAtivar(){
document.getElementById("form_FotoUpload").innerHTML = 'Foto (máximo 1MB): <input name="foto" type="file" accept="image/*;capture=camera">';
document.getElementById("form_Assinatura").innerHTML = '';
document.getElementById("form_Dados").innerHTML = 'Dependentes: <button type="button" onclick="cadFormDep(1);"> + </button> <button type="button" onclick="cadFormDep(-1);"> - </button><br /><button type="button" onclick="cadFormTestar();">Enviar</button>';
cadFormTable = document.getElementById("form_Dependentes");
var nr = cadFormTable.rows.length;
cadFormTableRow = cadFormTable.rows[1];
console.log("Rows: "+nr);
//console.log("Row: "+cadFormTableRow.outerHTML);
for(i=0; i<nr-1; i++){
cadFormTable.deleteRow(1);
}
}
function cadFormDep(a){
if(a>0){
cadFormTable.appendChild(cadFormTableRow);
} else {
var nr = cadFormTable.rows.length;
cadFormTable.deleteRow(nr-1);
}
}
The problem seams to be appendChild is not good, I should go deep in HTMLTableElement, I guess, that's what I like to choose the better approach first... If I could make it work, I'll answer myself, I don't mind you don't like it, it's a free world, right?
It seams HTMLTableElement is the best approach for inserting and deleting rows. HTMLTableElement.insertRow creates a row linked with the original object. Here is the same code with HTMLTableElement corrections needed:
var cadFormTableRow;
var cadFormTable;
function cadFormAtivar(){
document.getElementById("form_FotoUpload").innerHTML = 'Foto (máximo 1MB): <input name="foto" type="file" accept="image/*;capture=camera">';
document.getElementById("form_Assinatura").innerHTML = '';
document.getElementById("form_Dados").innerHTML = 'Dependentes: <button type="button" onclick="cadFormDep(1);"> + </button> <button type="button" onclick="cadFormDep(-1);"> - </button><br /><button type="button" onclick="cadFormTestar();">Enviar</button>';
cadFormTable = document.getElementById("form_Dependentes");
var nr = cadFormTable.rows.length;
cadFormTableRow = cadFormTable.rows[1];
for(i=0; i<nr-1; i++){
cadFormTable.deleteRow(1);
}
}
function cadFormDep(a){
if(a>0){
var row = cadFormTable.insertRow(-1);
var html = cadFormTableRow.innerHTML.replace(/{n}/g, String(cadFormTable.rows.length-1));
row.innerHTML = html;
console.log("Row: "+html);
} else {
var nr = cadFormTable.rows.length;
cadFormTable.deleteRow(nr-1);
}
}
I think working with the cells and inputs as string were easier in this case - I'd pick a sample (as below) and add a number replacing {n} by a numbering:
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_{n}" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_{n}" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_{n}" maxlength="10" /></td>
</tr>
This way, every the information will have an unique name.

How Can I Insert Multiple Rows Into a DB from my HTML Form with Multiple Rows Dynamically?

so here's my situation. I have a form that gives the user the ability to add any number of rows to the form and input more data into those newly created rows (using javascript). I HAVE THIS ALREADY set up in the following code (I am using index.html, js/scripts.js and a php/upload.php files, all are externally linked, including an external CSS):
INDEX.HTML
<html>
<header>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" language="javascript" src="/jquery/js/jquery-1.9.1.js">
</script>
<script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?
key=Gmjtd%7Cluua2q6bn9%2C8g%3Do5-lzbsh"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<title>Central Office Company Survey</title>
</header>
<body onload="get_company_name();">
<h1>Central Office Company Survey</h1>
<div id='map' style='width:0px; height:0px; position:absolute'></div>
<input type="hidden" id="co_city">
<input type="hidden" id="co_state">
<input type="hidden" id="co_zipcode">
<table>
<th>Company</th>
<th>CO Name</th>
<th>Get Current Location</th>
<th>Lat</th>
<th>Long</th>
<th>Address</th>
<tr>
<td><select id="company_name"></select></td>
<td><input id="co_name" type="text"></td>
<td><input type="submit" value="Get GPS" onclick="gpslookup()"></td>
<td><input id="co_lat" type="text"></td>
<td><input id="co_long" type="text"></td>
<td><input id="co_address" type="text"></td>
</tr>
</table>
<table id="tabledata">
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
<!--Begin Rows-->
<tr>
<td><input type="checkbox"></td>
<td><input id="border_location" type="text" name="txt[]"></td>
<td><input id="cable_location" type="text" name="txt[]"></td>
<td><input id="vault_direction" type="text" name="txt[]"></td>
<td><input id="cable_type" type="text" name="txt[]"></td>
<td><input id="cable_size" type="text" name="txt[]"></td>
<td><input id="cable_gauge" type="text" name="txt[]"></td>
<td><input id="vertical" type="text" name="txt[]"></td>
<td><input id="jumpers" type="text" name="txt[]"></td>
<td><input id="protectors" type="text" name="txt[]"></td>
<td><input id="metered_dist" type="text" name="txt[]"></td>
<td><input id="comments" type="text" name="txt[]"></td>
</tr>
</table>
<input id="addrow_btn" type="submit" value="Add New Row" onclick="addRow(); return false;" />
<input id="delrow_btn" type="submit" value="Delete Row" onclick="deleteRow(); return false;" />
<input id="submit" type="submit" value="Submit" onclick="uploaddata(); return false;" />
</body>
</html>
As for the backend, I ONLY have the PHP and server side scripts able to submit information for that first row using the below code:
JAVASCRIPT FILE
function addRow() {
var table = document.getElementById("tabledata");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
//UPLOAD DATA
//Global variables
var survey = {
'co_name' : "",
'co_lat' : "",
'co_long' : "",
'co_address' : "",
'border_location' : "",
'cable_location' : "",
'vault_direction' : "",
'cable_type' : "",
'cable_size' : "",
'cable_gauge' : "",
'vertical' : "",
'jumpers' : "",
'protectors' : "",
'metered_dist' : "",
'comments' : "",
'company_name' : "",
'co_city' : "",
'co_state' : "",
'co_zipcode' : ""
}
function uploaddata() {
//Read all of the data from the page
for (eID in survey) {
survey[eID] = document.getElementById(eID).value;
}
//Insert data into database
$.ajax({
type: 'POST',
url: './php/upload_survey.php',
data: survey,
async: false,
dataType: 'text',
success: function() {
alert("Thank you. Your survey has been submitted.");
window.location.reload();
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error... " + textStatus + "\n" + errorThrown);
}
});
}
PHP FILE
//Assign passed parameters
$co_name = $_POST['co_name'];
$co_lat = $_POST['co_lat'];
$co_long = $_POST['co_long'];
$co_address = $_POST['co_address'];
$border_location = $_POST['border_location'];
$cable_location = $_POST['cable_location'];
$vault_direction = $_POST['vault_direction'];
$cable_type = $_POST['cable_type'];
$cable_size = $_POST['cable_size'];
$cable_gauge = $_POST['cable_gauge'];
$vertical = $_POST['vertical'];
$jumpers = $_POST['jumpers'];
$protectors = $_POST['protectors'];
$metered_dist = $_POST['metered_dist'];
$comments = $_POST['comments'];
$txt = $_POST['txt'];
$stringLogInfo = "INFO: Location: $co_address CO Name = $co_name !!!\n\n";
log_audit($logAuditFile, $logModule, $stringLogInfo);
//Parse and store the ini file, this will return an associative array
ini_set("display_errors", "1");
error_reporting(E_ALL);
//Insert Survey Form Information into the database
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.$value.'\',';
}
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$sql='INSERT INTO table_name ('.$fieldlist.') VALUES ('.$vallist.')';
mysql_query($sql) or die ("Unable to Make Query:" . mysql_error());
My objective up to this point, having already everything else sort of ready, is to be able to loop through all the data in the form, according to however many rows they create and submit all those new row values into the SQL Database into SEPARATE rows. Please Advise!
Focusing on the HTML part of this question here is an approach to grow a form dynamically:
First the HTML:
<table id="tabledata">
<thead>
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
</thead>
<tbody id="input"></tbody>
<tbody id="template">
<tr>
<td><input name="selected" type="checkbox" /></td>
<td><input name="border_location" type="text" /></td>
<td><input name="cable_location" type="text" /></td>
<td><input name="vault_direction" type="text" /></td>
<td><input name="cable_type" type="text" /></td>
<td><input name="cable_size" type="text" /></td>
<td><input name="cable_gauge" type="text" /></td>
<td><input name="vertical" type="text" /></td>
<td><input name="jumpers" type="text" /></td>
<td><input name="protectors" type="text" /></td>
<td><input name="metered_dist" type="text" /></td>
<td><input name="comments" type="text" /></td>
</tr>
</tbody>
</table>
<button id="ActionAddRow">Add Row</button>
<button id="ActionSubmit">Submit</button>
And This JavaScript:
$(function () {
var addInputRow = function () {
$('#input').append($('#template').html());
};
addInputRow();
$('#ActionAddRow').on('click', addInputRow);
$('#ActionSubmit').on('click', function () {
var data = $('#input tr').map(function () {
var values = {};
$('input', $(this)).each(function () {
if (this.type === 'checkbox') {
values[this.name] = this.checked;
} else {
values[this.name] = this.value;
}
});
return values;
}).get();
$.post('/echo/json/', {
json: JSON.stringify(data),
delay: 1
}).done(function (response) {
alert("POST success");
console.log(response);
});
});
});
And then this CSS:
tbody#template {
display: none;
}
Produces this demo
Here is a breakdown of what is happening. First the table element can define mutiple bodies, so I've added the HTML of an empty row of inputs and hidden (with CSS) it in a tbody with the ID of template. Using JavaScript, I then define a simple function that just appends the contents of that row to the tbody with the ID of inputs and I bind that function to the click event of a button. Then because the inputs tbody is starts out as empty I call that function once. Then for submitting the form, I select all rows of the inputs tbody and iterate over the inputs found inside them. Next, I am combining them into one large array of JavaScript objects with each element representing a row, and finally I'm posting this showing a round trip with this data from the client to the server (I'm using JSON2.js to serialize the data). Your PHP page would pick up from here to check them on the server, and (using a prepared statement) insert valid rows into the database.
Your PHP would take the POSTed values like this:
$value = json_decode($_POST['json']);
And treat the submitted data as an associative array. This approach uses an AJAX Form Post, so the response of the PHP page should be a valid JSON with a structure something like this:
{Success: true}

dojo framework - event doesn't work

I have a trouble in my code,
I want to send an ajax request by clicking a button,
but the request is automatically run, even when I don't click the button,
here is my code:
<script type="text/javascript">
function set(mode) {
var nomor_awal = dojo.query("input[name=nomor_awal]");
var nomor_akhir = dojo.query("input[name=nomor_akhir]");
var validGetUrl = "";
validGetUrl += "nomor_awal="+objNomorAwal.attr("value")+"&";
validGetUrl += "nomor_akhir="+objNomorAkhir.attr("value");
dojo.xhrPost({
url:"<?php echo base_url(); ?>register_perkara/pidana_biasa/"+mode+"/",
content:{
filter:validGetUrl
},
load:function(response){
(response!="1")? document.location = window.location: null;
}
});
}
dojo.ready(function(){
dojo.connect(dojo.query("input[name=filter]"), "onclick", set("set_filter"));
}
</script>
<table>
<tr>
<td><label for="nomor_awal">Nomor awal</label></td>
<td><input type="text" name="nomor_awal" size="8" value="" /></td>
</tr>
<tr>
<td><label for="nomor_akhir">Nomor akhir</label></td>
<td><input type="text" name="nomor_akhir" size="8" value="" /></td>
</tr>
<tr>
<td colspan="2"><input type="button" name="filter" /></td>
</tr>
</table>
I don't click the filter button but the function are automatically executed, why?
I don't know dojo, but this line
dojo.connect(dojo.query("input[name=filter]"), "onclick", set("set_filter"));
executes the set function and passes the return value to dojo.connect.
You have to pass the function, not call it. So I'm quite sure you want:
dojo.connect(dojo.query("input[name=filter]"), "onclick", function() {
set("set_filter");
});

Categories