How to change div id name based on form value? - javascript

I have a couple forms on a page with a single button and a hidden input field with a value already pre-set:
<form action="product.html" method="get">
<fieldset>
<input style="display: none;" type="text" name="RSS" id="RSS" value="RSS" />
<input type="submit" value="Go"/>
</fieldset>
</form>
<form action="product.html" method="get">
<fieldset>
<input style="display: none;" type="text" name="RSS2" id="RSS2" value="RSS2" />
<input type="submit" value="Go"/>
</fieldset>
</form>
Once they hit the Go button on either form, it will redirect to the product.html page where a specific div loads based on the value above.
<div id="ID CHANGE TO OCCUR HERE to either be RSS or RSS2"></div>
My question is, how do I get that id to change on that div?
Thanks
PS: PHP is not enabled on the company servers...so yeah..yeah...

If I understand you correctly, when program control transfers over to product.html, you wish to discover which form value has come across (i.e. which form did the user click).
I cannot think how you would do this solely with HTML. This is a job for a server-side language like PHP or ASP .Net.
It's pretty simple in PHP. Note that you can take all your existing HTML files and simply rename them to .php (eg. product.php) and they will still work the same.
Just put this at the top of the file -- in fact, this is the complete file (just copy/paste to your server to test):
product.php
<?php
/* Below not required, but un-comment to see useful info:
echo '<pre>';
print_r($_REQUEST);
echo '<pre>';
*/
if (isset($_REQUEST['RSS'])) {
echo 'User clicked the RSS form';
} else if (isset($_REQUEST['RSS2'])) {
echo 'Sent here by the RSS2 form';
}
Since the name of the processing file has changed, remember to change the action= line in each of your forms before trying this:
<form action="product.php" method="get">
Explanation:
When a form is submitted, the form elements (input fields, radio buttons, checkboxes) are turned into variables and sent to the processing document (the target document specified in the action= attribute of the form tag).
For each element, the variable name is the name= attribute for that element, and the variable value is either the value= attribute, or, in the case of an input field for example, whatever the user typed into the field before pressing submit.
The is very little difference to the programming/functionality between sending the form as method="Get" or method="POST", but the post method is more secure and can transfer more information, so most of us use that.
Finally, on the other end, there are three ways to get the variable values (PHP Example):
$newvar = $_GET['varname']; //if method="GET" was used
$newvar = $_POST['varname']; //if method="post" was used
$newvar = $_REQUEST['varname']; //works for both
If you need more assistance with PHP, view some of the Alex Garret's free ten-minute videos on the New Boston or on his own site.

Re-reading your question, I put together the completed example. In your target page, you have two DIVs and you wish to display one or the other depending on what form the user clicked.
Here is a working example of the solution. Copy/Paste into two files called:
test.php -- this file can be renamed whatever you want
product.php -- if change this name, must also change name in both action= attributes of forms
test.php
<form action="product.php" method="get"> <!-- product.html -->
<fieldset>
<input type="hidden" name="RSS" id="RSS" value="RSS" />
<input type="submit" value="Go"/>
</fieldset>
</form>
<form action="product.php" method="get">
<fieldset>
<input type="hidden" name="RSS2" id="RSS2" value="RSS2" />
<input type="submit" value="Go"/>
</fieldset>
</form>
product.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var whichone = $('#xfer').val();
//alert( whichone );
$('#' + whichone).show();
});
</script>
</head>
<body>
<input type="hidden" id="xfer" value="<?php echo ( isset($_REQUEST['RSS']) ? 'RSS' : 'RSS2' ) ; ?>">
<div id="RSS" style="display:none;">
<h1>RSS DIV</h1>
Here is some information regarding the RSS div.
</div><!-- #RSS -->
<div id="RSS2" style="display:none;">
<h1>RSS2 DIV</h1>
<i>Here is some <strong>different </strong>information regarding the RSS2 div.</i>
</div><!-- #RSS -->
</body>
</html>

You can test your request with javascript:
if(location.href.indexOf("RSS=RSS") > 0) {
var element = document.getElementById('RSS')
element.id = "RSS2";
element.name = "RSS2";
element.value = "RSS2";
}
this is just an indexOf check, u could also parse the whole query string and associate the key/value pairs into an array. See How can I get query string values in JavaScript?

Related

Why is my search query returning undefined, while my page populates with the term's results? Using business catalyst

I'm trying to get the search term to appear in the URL. What am I doing wrong?
<form name="catsearchform74255" method="post" onsubmit="processSearch(this)" action="/Default.aspx?SiteSearchID=2248&ID=/search-results&keywords=">
<div class="input-field search-box">
<input id="CAT_Search" type="search" name="CAT_Search" placeholder="What are you looking for?" class="white" required="true">
<label class="label-icon" for="CAT_Search"><i class="material-icons">search</i></label>
<i class="material-icons">close</i>
</div>
<script type="text/javascript">
function processSearch(form) {
form.action = form.action + CAT_Search.value;
}
</script>
</form>
Change method="post" to method="get".
Update any server-side code referencing post variables to reference get variables. For example, in PHP code, change $_POST["CAT_Search"] to $_GET["CAT_Search"].
Also, the correct format for the required HTML attribute is either required="" or required="required.
Code
This can be done with JS, you can't edit the method as Business Catalyst expects a post for this form.
If you change the form to the following:
<form name="catsearchform74255" id="searchForm" method="post" action="/Default.aspx?SiteSearchID=2248&ID=/search-results&keywords=">
<div class="search-box">
<input class="cat_textbox_small" type="text" name="CAT_Search" id="CAT_Search">
<input id="submitForm" onclick="submitFormScript()" type="button" class="cat_button" value="Search">
</div>
</form>
and then add the following jQuery:
function submitFormScript() {
var searchAction = $("#searchForm").attr("action");
searchAction = searchAction + $("#CAT_Search").val();
$("#searchForm").attr("action", searchAction);
$("#searchForm").submit();
}
Explanation
By adding the ID's to the fields on the form and then taking type="submit" off the input button we can edit the form action before we submit the form.
In the JS we are getting the form action, adding on the value of the search box (users input) and then setting that back to the form action attribute. After that we have the URL that we want to send to the next page so we can then submit the form.

Send dynamic SPAN value to PHP script using POST

I am trying to send data from to the using PHP script. I use jqCron My problem is that I have dynamic SPAN value, but value of this span is not being sent using post function. I can not get the value
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$TiData = !empty($_POST['BCTiData']) ? $_POST["BCTiData"] : '';
echo $TiData;
}
?>
This is form
<form id="fo1" action="#" method="post">
<div class="timer"> </div>
<input type="text" class="form-control" id="BCTiData" name="BCTiData" value="<span class="timer-span"></span>">
</form>
also I trying this method:
$degerSpan = '<span class="timer-span"></span>'; // Not working
How can I get the data in Span and how can I send with POST?
Thanks
also I put it here Pastebin
You need to use javascript to extract the value from the SPAN element, then put it in a hidden form field, and then submit the data.
This could be done in several ways. Here is some mockup code that should get you started:
<!-- the Span that will contain the data we're interested in -->
<span class="cronMDMtimer-span"></span>
<!-- The HTML Form that will submit the timer value, this is populated using javascript -->
<form onsubmit="myFunction()" id="my-form">
<input type="hidden" name="timerValue" id="timerValue" value="not yet defined">
<input type="submit">
</form>
<script>
// This function gets called once the user submits the form
function myFunction(){
// First get the value from the cronMDMtimer-span
timerValue = $('.cronMDMtimer-span').html();
// Then store the extracted timerValue in a hidden form field
$("#timerValue").val(timerValue);
// submit the form using it's ID "my-form"
$("#my-form").submit();
}
</script>

Passing variables through multiple forms to PHP [duplicate]

Is it valid html to have the following:
<form action="a">
<input.../>
<form action="b">
<input.../>
<input.../>
<input.../>
</form>
<input.../>
</form>
So when you submit "b" you only get the fields within the inner form. When you submit "a" you get all fields minus those within "b".
If it isn't possible, what workarounds for this situation are available?
A. It is not valid HTML nor XHTML
In the official W3C XHTML specification, Section B. "Element Prohibitions", states that:
"form must not contain other form elements."
http://www.w3.org/TR/xhtml1/#prohibitions
As for the older HTML 3.2 spec,
the section on the FORMS element states that:
"Every form must be enclosed within a
FORM element. There can be several
forms in a single document, but the
FORM element can't be nested."
B. The Workaround
There are workarounds using JavaScript without needing to nest form tags.
"How to create a nested form." (despite title this is not nested form tags, but a JavaScript workaround).
Answers to this StackOverflow question
Note: Although one can trick the W3C Validators to pass a page by manipulating the DOM via scripting, it's still not legal HTML. The problem with using such approaches is that the behavior of your code is now not guaranteed across browsers. (since it's not standard)
In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.
<form method="post" action="ServerFileToExecute.php">
<input type="submit" name="save" value="Click here to save" />
<input type="submit" name="delete" value="Click here to delete" />
</form>
The server side could look something like this if you use php:
<?php
if(isset($_POST['save']))
echo "Stored!";
else if(isset($_POST['delete']))
echo "Deleted!";
else
echo "Action is missing!";
?>
HTML 4.x & HTML5 disallow nested forms, but HTML5 allows a workaround with the "form" attribute ("form owner").
As for HTML 4.x you can:
Use an extra form(s) with only hidden fields & JavaScript to set its input's and submit the form.
Use CSS to line up several HTML form to look like a single entity - but it might be complicated to do.
As others have said, it is not valid HTML.
It sounds like your are doing this to position the forms visually within each other. If that is the case, just do two separate forms and use CSS to position them.
No, the HTML specification states that no FORM element should contain another FORM element.
A possibility is to have an iframe inside the outer form. The iframe contains the inner form. Make sure to use the <base target="_parent" /> tag inside the head tag of the iframe to make the form behave as part of the main page.
You can answer your own question very easily by inputting the HTML code into the W3 Validator. (It features a text input field, you won't even have to put your code on a server...)
(And no, it won't validate.)
rather use a custom javascript-method inside the action attribute of the form!
eg
<html>
<head>
<script language="javascript" type="text/javascript">
var input1 = null;
var input2 = null;
function InitInputs() {
if (input1 == null) {
input1 = document.getElementById("input1");
}
if (input2 == null) {
input2 = document.getElementById("input2");
}
if (input1 == null) {
alert("input1 missing");
}
if (input2 == null) {
alert("input2 missing");
}
}
function myMethod1() {
InitInputs();
alert(input1.value + " " + input2.value);
}
function myMethod2() {
InitInputs();
alert(input1.value);
}
</script>
</head>
<body>
<form action="javascript:myMethod1();">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input type="button" onclick="myMethod2()" value="myMethod2"/>
<input type="submit" value="myMethod1" />
</form>
</body>
</html>
As workaround you could use formaction attribute on submit button. And just use different names on your inputs.
<form action="a">
<input.../>
<!-- Form 2 inputs -->
<input.../>
<input.../>
<input.../>
<input type="submit" formaction="b">
</form>
<input.../>
no,
see w3c
No, it is not valid. But a "solution" can be creating a modal window outside of form "a" containing the form "b".
<div id="myModalFormB" class="modal">
<form action="b">
<input.../>
<input.../>
<input.../>
<button type="submit">Save</button>
</form>
</div>
<form action="a">
<input.../>
Open modal b
<input.../>
</form>
It can be easily done if you are using bootstrap or materialize css.
I'm doing this to avoid using iframe.
Fast Solution:
To obtain different validations to different forms and keep their submits in separated functions you can do this:
<form id="form1" onsubmit="alert('form1')"></form>
<form id="form2" onsubmit="alert('form2')"></form>
<div>
<input form="form1" required />
<input form="form1" required />
<div>
<input form="form2" required />
<input form="form2" required />
<button form="form2" type="submit">Send form2</button>
</div>
<input form="form1" required />
<button form="form1" type="submit">Send form1</button>
</div>
A non-JavaScript workaround for nesting form tags:
Because you allow for
all fields minus those within "b".
when submitting "a", the following would work, using regular web-forms without fancy JavaScript tricks:
Step 1. Put each form on its own web page.
Step 2. Insert an iframe wherever you want this sub-form to appear.
Step 3. Profit.
I tried to use a code-playground website to show a demo, but many of them prohibit embedding their websites in iframes, even within their own domain.
You are trying to implement nested form which is not supported in HTML.
Every form must be enclosed within a FORM element. There can be
several forms in a single document, but the FORM element can't be
nested.
Workaround
You can implement this functionality with some change in HTML and JavaScript. (without using html forms)
Steps
1. Create both forms with div tag as follows (do not use form tag)
<div id="form_a">
<input.../>
<div id="form_b">
<input.../>
<input.../>
<button id="submit_b">Submit B</button>
</div>
<input.../>
<button id="submit_a">Submit A</button>
</div >
2. Add JQuery and Ajax to submit each form data
<script>
// Submit form A data
$('#submit_a').click( function() {
$.ajax({
url: 'ajax-url',
type: 'post',
dataType: 'json',
data: $('#form_a input').not( "#form_b input" ).serialize(),
success: function(data) {
// ... do something with the data...
}
});
});
// Submit form B data
$('#submit_b').click( function() {
$.ajax({
url: 'ajax-url',
type: 'post',
dataType: 'json',
data: $('#form_b input').serialize(),
success: function(data) {
// ... do something with the data...
}
});
});
</script>
If you need your form to submit/commit data to a 1:M relational database, I would recommend creating an "after insert" DB trigger on table A that will insert the necessary data for table B.

Dynamically added fields in form not sent to PHP

I have a form that allows users to add more input fields dynamically to upload multiple forms
Form just looks like this
<form enctype="multipart/form-data" action="upload.php" method="post">
<table><tr>
<td>
<span><div id='attach_files'></span>
<input type="button" id="more_fields" onclick="add_fields();" value="Add More" />
<input type="file" name="attach_file_1">
</div>
<input type="submit" value="Upload" align='left'>
</td>
</tr><table></form>
The form tag is around it and the form submits perfectly fine with just the one attach_file_1, but as soon as more fields are added these fields are not recognized by the php file i send them too (while the attach_file_1 still works fine).
For example
echo ($_FILES['attach_file_1']['name']);
returns the proper file name but
echo ($_FILES['attach_file_2']['name']);
doesn't.
I add the fields using the following code:
var files = 1;
function add_fields() {
files++;
var objTo = document.getElementById('attach_files')
var divcreate = document.createElement("div");
divcreate.innerHTML = "<span><input type='file' id='attach"+files+"' name='attach_file_"+files+"'></span>";
objTo.appendChild(divcreate)
}
I've tried moving the form tags everywhere and have used the other post that's similar to this, didn't help.
Any help is appreciated. Thanks.

Post several duplicated forms, with different info to a new page

I need to create a system to print information about items in a database. By now I have an html form with several input fields (types = text and radio), so I can collect all the info of an item.
To make the process faster I introduce a javascript to duplicate the whole empty form 'n' times with a click, so one can print several items information at once. My script looks like this:
<body>
<button id="button" onclick="duplicate()">add form</button><!--this button duplicates the empty form-->
<form action="action.php" method="post" name="formulario">
<div id="duplicater">
<p>Código:<input type="text" name="codigo" /></p>
<p>Nombre del proyecto:<input type="text" name="proyecto" /></p>
<p>
<span>
<input type="radio" name="grupo1" value="SD" />SD
<input type="radio" name="grupo1" value="HD" />HD
</span>
<span>
<input type="radio" name="grupo2" value="4:3"/>4:3
<input type="radio" name="grupo2" value="16:9"/>16:9
</span>
</p>
<p>Fecha:<input type="text" name="fecha" /></p>
<p>Lugar:<input type="text" name="lugar" /></p>
<p>Dueño:<input type="text" name="dueno" /></p>
</div>
<p><input type="submit" name="submit" value="enviar" /></p>
</form>
<script>
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicator" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
</script>
</body>
At this point, this part of the project is working fine, but I have a problem with the action.php file that handle the functionality to send the information from all the forms to a new page to print it.
The action.php collects the information of the form using the name attribute of every input. As every form is just a duplicate of the original one, every new form have the same name attribute, so when I click the send button, the php just echo the information of the last form.
<div><span>Código: </span><?php echo htmlspecialchars($_POST['codigo']); ?></div>
<div><span>Proyecto: </span><?php echo htmlspecialchars($_POST['proyecto']); ?></div>
<div><span>Calidad: </span><?php echo htmlspecialchars($_POST['grupo1']); ?></div>
<div><span>Formato: </span><?php echo htmlspecialchars($_POST['grupo2']); ?></div>
<div><span>Fecha: </span><?php echo htmlspecialchars($_POST['fecha']); ?></div>
<div><span>Lugar: </span><?php echo htmlspecialchars($_POST['lugar']); ?></div>
<div><span>Dueño: </span><?php echo htmlspecialchars($_POST['dueno']); ?></div>
Questions:
I need to update (rename) the name attribute of the input tags in every duplicated form, how can I do that?
It is possible to refer the echo function in the action.php file to a div with an id assigned to post the whole information at once? otherwise, how can I send (post) the information of all the duplicated form to a new page at once?
This have to be a client side process, so there is nothing more behind it, the php is just for echoing the info to the new page. So if there are solutions that can be done with javascript or jQuery is ok as well.
I leave a link to the demo http://www.programaicat.una.ac.cr/ICATsite/demo/
Thanks to all in advance.
The way POST vars are sent to a script, they're named key, value pairs in an array. Any inputs with the same name will be overwritten.
I suggest appending or prepending a number to each additional input as they are created, so instead of a new input called "name", it would be called "name.1" or "1.name". Your first input would be "name.0" and the rest would increment upwards as they are added. When you process the information, you can iterate over the POST array keys using substr and re-shape your information as needed before saving it to the database.

Categories