i have 1 php page containing 2 forms and 1 submit button.i want to submit both forms with this single button.My code works perfectly but there is 1 problem that in each form only 1 field submitted successfully. Below is my html and javascript code, plz tell me where i have error
2 html forms
<form name="form">
<input type="text" name="a" value="a">
<input type="text" name="b" value="b">
</form>
<form name="form">
<input type="text" name="c" value="c">
<input type="text" name="d" value="d">
</form>
<input type="submit" name="Submit" id="button" value="Submit" onClick="submitAllDocumentForms()">
Javascript code
<script language="javascript" type="text/javascript">
/* Collect all forms in document to one and post it */
function submitAllDocumentForms() {
var arrDocForms = document.getElementsByTagName('form');
var formCollector = document.createElement("form");
with(formCollector)
{
method = "post";
action = "test.php";
name = "formCollector";
id = "formCollector";
}
for(var ix=0;ix<arrDocForms.length;ix++) {
appendFormVals2Form(arrDocForms[ix], formCollector);
}
document.body.appendChild(formCollector);
formCollector.submit();
}
/* Function: add all elements from ``frmCollectFrom´´ and append them to ``frmCollector´´ before returning ``frmCollector´´*/
function appendFormVals2Form(frmCollectFrom, frmCollector) {
var frm = frmCollectFrom.elements;
for(var ix = 0 ; ix < frm.length ; ix++)
frmCollector.appendChild(frm[ix]);
return frmCollector;
}
</script>
My php code to echo submitted values
<?php
echo $_POST['a'];
echo $_POST['b'];
echo $_POST['c'];
echo $_POST['d'];
?>
The problem is that appendChild() takes the element away from the form, modifying the elements array as well as its length. To avoid this, you can e.g. store the number of elements in a variable and process the array of elements starting from the last element:
var frm = frmCollectFrom.elements;
var nElems = frm.length;
for(var ix = nElems - 1; ix >= 0 ; ix--)
frmCollector.appendChild(frm[ix]);
Related
I want to use this code for a barcode scanner as follows:
The scanned barcode is entered in the insert_code input and then I want to display "code is ok", when the value in search_code = insert_code.
My code, after validation, clears the input search_code and it is annoying to have to reintroduce the same code in search_code every time again.
What can I do to keep the value in search_code after each validation?
<form action="" method="post">
Cod I:<input type="text" name="search_code" value=""/><br/><br/>
Cod II:<input type="" name="insert_code" value=""/><br/><br/>
<input type="submit" name="button" value="validation" />
</form>
<?php
$search_code = $_POST ["search_code"];
$insert_code = $_POST ["insert_code"];
if ($search_code == $insert_code){
echo "code is ok";
} else {
echo "code is not ok";
}
?>
If you want to keep search_code input filled with the last submitted value, just echo the value of this post into the input if it was set:
<form action="" method="post">
Cod I:<input type="text" name="search_code" value="<?php echo isset($_POST['search_code'])?$_POST['search_code']:'' ?>"/><br/><br/>
Cod II:<input type="" name="insert_code" value=""/><br/><br/>
<input type="submit" name="button" value="validation" />
</form>
Also, to avoid warnings about undefined index, add this condition to your PHP code (check if those posts are set):
<?php
if(isset($_POST ["search_code"]) && isset($_POST ["insert_code"])){
$search_code = $_POST ["search_code"];
$insert_code = $_POST ["insert_code"];
if ($search_code == $insert_code){
echo "code is ok";
}else {
echo "code is not ok";
}
}
?>
You can do this without PHP, which will give a better user-experience. Here is a live example, just run to see it work:
// identify form elements:
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
// respond to button click
button.onclick = function validate() {
// show verification result:
result.textContent = search_code.value == insert_code.value
? 'code is ok'
: 'code is not ok';
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
insert_code.oninput = function () {
result.textContent = ''; // clear result;
};
<form action="" method="post">
Cod I:<input type="text" name="search_code" id="search_code" value=""/><br/><br/>
Cod II:<input type="" name="insert_code" id="insert_code" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="validation" />
</form>
<div id="result"></div>
The test is done in Javascript, which responds to the button click and cancels the form's submission to the server (return false).
As a bonus the "ok/not ok" message is cleared as soon as you type a new value in the second input box.
How to use this code
Here is how the code should look in your document:
<body>
<form action="" method="post">
Cod I:<input type="text" name="search_code" id="search_code" value=""/><br/><br/>
Cod II:<input type="" name="insert_code" id="insert_code" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="validation" />
</form>
<div id="result"></div>
<script>
// identify form elements:
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
// respond to button click
button.onclick = function validate() {
// show verification result:
result.textContent = search_code.value == insert_code.value
? 'code is ok'
: 'code is not ok';
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
insert_code.oninput = function () {
result.textContent = ''; // clear result;
};
</script>
</body>
Note that the content part has some differences to yours: every input has an id attribute, and there is an extra div.
my html page has a number of textboxes (in div tags that show/hide) and I want the data in them to send to a text document once the submit button is clicked at the bottom.
I'm fairly new to html coding and have limited php/jquery experience so if theres an easy way to do this would be appreciated. Heres the current code:
My JS:
function showhide(layer_ref) {
var element = document.getElementById(layer_ref);
var state = element.style.display
if (state == 'block') {
state = 'none';
} else {
state = 'block';
}
if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval( "document.all." + layer_ref + ".style.display = state");
}
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[layer_ref].display = state;
}
if (document.getElementById &&!document.all) {
hza = document.getElementById(layer_ref);
hza.style.display = state;
}
}
The HTML:
<form>
Name: <input type="text" name="name">
Date: <input type="numbers" name="date">
<p>Question 1</p>
<div id="div1" style="display: none;">
<img src="q1.jpg" alt="some_text">
<TEXTAREA Name="q1answer" ROWS=20 COLS=100></TEXTAREA>
</div>
<!-- same code pattern for div2 to div7 -->
<p>Question 8</p>
<div id="div8" style="display: none;">
<img src="q8.jpg" alt="some_text">
<TEXTAREA Name="q8answer" ROWS=20 COLS=100></TEXTAREA>
</div>
</form>
You could use php GET or POST to recive data from the HTML Form.
Here is a tutorial that could help you: http://www.tizag.com/phpT/postget.php
Change your HTML form tag into this:
<form action='page.php' method='post'>
Add a submit button before the end of form tag
<input type=submit name='submit' value='submit'>
Change the name tag of your name input field
<input type="text" name="name">
into (you cant use name as a name of the input)
<input type="text" name="myname">
And add this PHP code:
if(isset($_POST['submit'])){ //if button is clicked do this:
$name = $_GET['myname'];
$date = $_GET['date'];
$answer1 = $_GET['q1answer'];
$answer2 = $_GET['q2answer'];
$answer3 = $_GET['q3answer'];
$answer4 = $_GET['q4answer'];
$answer5 = $_GET['q5answer'];
$answer6 = $_GET['q6answer'];
$answer7 = $_GET['q7answer'];
$answer8 = $_GET['q8answer'];
}
else{
//if button is not clicked do this
}
I have code that will automatically add a new similar row defined in form by clicking add button.
<html>
<body>
<form>
<input type="text" name="quantity[]" class="input_text" id="pro"/>
</form>
</body>
</html>
Now I want to access different values of quantity[] in javascript function .
How to access this different values of quantity[] in javascript using it's ID or Name Attribute.
<script>
function abc() {
var id = document.getElementById("pro").value;
}
</script>
You can do something like this.
html:
<form>
<input name="p_id[]" value="0"/>
<input name="p_id[]" value="1"/>
<input name="p_id[]" value="2"/>
</form>
javascript:
var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
alert(p_ids[i].value);
}
The way to do that with plain JavaScript is to get all the elements with an specific name, as following:
var fields = document.getElementsByName('quantity[]');
Should you want to access an specific value, you could do that as well:
console.log(fields[0].value); // foo
Here's a jsfiddle with a code sample.
HTML:
<form name="order">
<input type="text" name="quantity[]" class="input_text" />
<input type="text" name="quantity[]" class="input_text" />
<input type="text" name="quantity[]" class="input_text" />
</form>
JS:
var elements = document.forms['order'].elements['quantity[]'];
console.log(elements[1].value); // outputs the value of the 2nd element.
demo: http://jsfiddle.net/NDbwt/
$('input[name=quantity]').each(function(){
alert($(this).val())
});
First: id must be unique on page. Otherwise document.getElementById will always return first spotted element with requested id.
In your case, you may do next:
var id = document.getElementsByName("quantity[]")[0].value;
But more safely (I'm not sure if order of items in returned array will always be the same as order in which elements are added) would be to generate ids like pro_0, pro_1, pro_2 etc
You're probably confused by the fact that PHP reads form fields as arrays when you use square brackets on their name. That's only a PHP trick—for JavaScript, [] does not have any special meaning and you can read the items in the usual way:
var values = [];
var fields = document.getElementsByName("quantity[]");
for (var i = 0, len = fields.length; i < len; i++) {
values.push(fields[i].value);
}
alert("Values:\n" + values.join("\n"));
See it in action.
Here is my Javascript:
<script>
function disable()
{
document.getElementById("habits").disabled=true;
document.getElementById("habits2").disabled=true;
document.getElementById("exact").disabled=false;
}
function enable()
{
document.getElementById("habits").disabled=false;
document.getElementById("habits2").disabled=false;
document.getElementById("exact").disabled=true;
}
var counter =0;
var i = 0;
function duplicate() {
var original = document.getElementById('div');
var clone = original.cloneNode(true); // "deep" clone
i+=1;
clone.id = "div" + i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
document.getElementById('div' + i).getElementsByTagName('select').name += '_clone' + i;
counter+=1;
}
</script>
and this is my HTML code:
<button id="button" onclick="duplicate()">Add List</button><br><br>
<form id ="form" name="search" method="post" action="test.php">
<div id="div">
<div id="d">
<select name ="select" >
...options...
</select>
</div>
Value:<input type="text" id ="exact">
From: <input type="text" id="habits">
To: <input type="text" id="habits2">
<br>
<input type="button" name="answer" value="Range" onclick="enable()" >
<input type="button" name="answer" value="Exact" onclick="disable()" >
</div>
<br><br>
<input type="submit" name ="search" value="Submit">
</form>
My issue here is that, when I clone the div id=div, all the buttons work for the original one, even the cloned buttons. Another thing is that, when I click the submit button to get the options from the drop-down list(s), but after submission, only the last drop-list is counted (cloned), but I want the original only.
Here is my page after clicking submit:
<?php
$item = $_POST["select"];
echo $item;
?>
How can I solve this? That is, changing the id's and names, and functions working with the cloned elements?
First of all, don't use id's if you want to duplicate things. Use and select by class (I strongly recommend to use jQuery), and use name="some_name[]"
To solve your problem you can do: onclick="javascript:enable(this)" or, if you decide to use jQuery, use `onclick="javascript:jQuery(this)", and then you search for siblings of the current element (don't know the pure js syntax, just the jquery one, if you need help with jquery let me know).
Hope this helps, good luck.
try this one. i have changed the function by adding a line
function duplicate() {
var original = document.getElementById('div');
var clone = original.cloneNode(true); // "deep" clone
i+=1;
clone.attr("id",replace(clone.attr("id"),"div"+i));// change the id of clone div
// clone.id = "div" + i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
document.getElementById('div' + i).getElementsByTagName('select').name += '_clone' + i;
counter+=1;
}
I'm trying to figure out how to make the logic in the following form work. Basically if either of the first two radio buttons is checked, make the hidden input named categories have a value of vegetables. Else, make the hidden input named categories have a value of fruits.
I'm not sure if this should be done with PHP or JavaScript, but if it is done with PHP I think the form would have to be submitted to itself to be pre-processed and then the collected, pre-processed information would be sent to external_form_processor.php. If this is how you do it, what would be the PHP code that I need to use to make it work?
<?php
if($_POST["food"]=="carrots" || $_POST["food"]=="peas") {
$category = "vegetables";
} else {
$category = "fruits";
}
?>
<form name="food_form" method="post" action="external_form_processor.php" >
<fieldset>
<input type="radio" id="carrots" name="food" value="carrots" />
<input type="radio" id="peas" name="food" value="peas" />
<input type="radio" id="orange" name="food" value="orange" />
<input type="radio" id="apple" name="food" value="apple" />
<input type="radio" id="cherry" name="food" value="cherry" />
</fieldset>
<input type="hidden" name="categories" value="<?php $category ?>" />
</form>
If using jQuery would be easier, how could I call the variable as the value of the hidden input if I use the following in the head of the page?
$(function(){
$('input[name=food]').click(function(){
var selected_id = $('input[name=food]:checked').attr('id');
if (selected_id == 'carrots' || selected_id == 'peas') {
var category = "vegetables";
} else {
var category = "fruits";
}
});
});
Any help with this would be greatly appreciated. Thanks!
I think jQuery would work perfect for you, you just need to pass the category value to the input field:
$(function(){
$('input[name=food]').click(function(){
var selected_id = $('input[name=food]:checked').attr('id');
if (selected_id == 'carrots' || selected_id == 'peas') {
var category = "vegetables";
} else {
var category = "fruits";
}
$('input[name=categories]').val(category);
});
});
I would set the category in PHP when the form is submitted.
//validate inputs... always
$food = "";
if(isset($_GET['food'])){
$food = preg_replace("/[^a-zA-Z]+/", "", $_GET['food']);
}
$category = ($food=="peas"||$food=="carrots")?"vegetables":"fruits";