Create dynamic forms - php

Up to this point I've avoided javascript, mostly because I'm a newbie. But I think I can't avoid it anymore?
I have a simple form in a table that I process with php.
<table id="my-table">
<thead>
<tr>
<td>Name</td>
<td>Quality</td>
<td>Status</td>
<td>User</td>
<td>Password</td>
<td>IP</td>
<td>Port</td>
<td>Options</td>
</tr>
</thead>
<form action="<?php htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
<tbody>
<tr>
<td>
<input type="text" size="18" maxlength="32" name="add_name" value="Enter name" />
</td>
<td>
<select name="add_quality">
<option value='HIGH' selected='selected'>High</option>
<option value='MEDIUM'>Medium</option>
<option value='MOBILE'>Mobile</option>
</select>
</td>
<td>
<select name="add_status">
<option value='ENABLED' selected='selected'>Enabled</option>
<option value='DISABLED'>Disabled</option>
</select>
</td>
<td>
<input type="text" size="14" maxlength="16" name="add_user" value="Enter username" />
</td>
<td>
<input type="password" size="12" maxlength="16" name="add_pass" />
</td>
<td>
<input type="text" size="10" maxlength="16" name="add_ip" value="Enter IP" />
</td>
<td>
<input type="text" size="12" maxlength="6" name="add_port" value="Enter Port #" />
</td>
<td>
<input type="submit" name="add" value="Add" />
</td>
</tr>
</tbody>
</form>
</table>
I'd like to take this table and only keep the first three input types shown (Name, Quality, Status). The rest would open up if you hit a "details" link or button. So the table would expand (or ideally go to the next line as this table is too long). That details button or link would have to toggle on and off. Any ideas would be appreciated.

Basic javascript approach:
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display === 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
Then place a button or link with:
<input type="button" value="Details" onClick="toggle_visibility('detailsWrapper')">
Finally, just make a div or maybe a new tr around the fields you want to hide with the id set to "detailsWrapper" and style it with display:none.
Alternatively you can use this function:
function toggle_visibility(id) {
var control = document.getElementById(controlId);
if(control.style.visibility == "visible" || control.style.visibility == "")
control.style.visibility = "hidden";
else
control.style.visibility = "visible";
}
If I remember correctly this will reserve the needed space to display the element, so it won't mess up your layout.

For animations, jQuery is my favorite JavaScript library. It makes things quite a lot easier.
This code might work for you:
$('#my-table tr td').each(function(i) {
if (i >= 3) {
$(this).hide();
}
});
$('#details').click(function() {
$('#my-table tr td').each(function(i) {
if (i >= 3) {
$(this).slideToggle();
}
});
});

Related

Add another text box when a user select other option

My form is looking like this.
<form action="add_customers.php" method="post" onsubmit="MM_validateForm('name','','R','passport_no','','R','remarks','','R');return document.MM_returnValue">
<tr>
<td>Name of the Applicant:</td>
<td><label for="name"></label>
<input type="text" name="name" id="name" /></td>
</tr>
<tr>
<td>Country applying for :</td>
<td><label for="country"></label>
<select name="country" id="country">
<option>Singapore</option>
<option>Malaysia</option>
<option>Istanbul</option>
<option>Thailand</option>
<option>China</option>
<option>Other</option>
</select></td>
</tr>
<tr>
<td>Visa Categeory :</td>
<td><label for="visa_categeory"></label>
<select name="visa_categeory" id="visa_categeory">
<option>Visit</option>
<option>Business</option>
<option>Other</option>
</select></td>
</tr>
<tr>
<td>Passport No:</td>
<td><input type="text" name="passport_no" id="passport_no" /></td>
</tr>
<tr>
<td>Remarks:</td>
<td><label for="remarks"></label>
<textarea name="remarks" id="remarks" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" id="submit" value="Submit" /></td>
</tr></form>
Now My problem is
1) when a user select other option from Visa Category then automatically display a text box for user and capture that what he enter.
2) save that details into mysql database
Used languages are PHP,MYSQL
Thanks.
You can add a text box in your form and make it hidden first time.
Get the textbox visible on change of the dropdown you have mentioned using javascript.
You can get the value of the textbox in the page where you accepts the data and insert into data database in add_customers.php along with other variables.
<script>
function visacatOnchange(){
var visa_cat = document.getElementById('visa_categeory').value
if(visa_cat == "Visit")
document.getElementById("new_textbox").style.display="block";
else
document.getElementById("new_textbox").style.display="none";
}
</script>
In html form add
<input type="text" name="new_textbox" id="new_textbox" style="display:none;">
and change
<select name="visa_categeory" id="visa_categeory" onChange="visacatOnchange();">
Good luck :-)
Initially you can keep the textbox div hidden and then display it on "onchange" event of select input.
<div id="textboxdiv" style="visibility: hidden">
Visa Option <input type="text" id="someid"/>
</div>
<select name="visa_categeory" id="visa_categeory" onchange="showTextBox()" >
<option>Visit</option>
<option>Business</option>
<option value="99" >Other</option>
</select>
Using Jquery you can display it like this:-
function showTextBox(){
if ($('#visa_categeory').val() == '99') {
$('#textboxdiv').css({'visibility':'visible'});
}
Here's some basic JavaScript/jQuery that should help you solve your first problem: http://jsfiddle.net/j4aXQ/
HTML
<form>
<select name="visa_category">
<option>Visit</option>
<option>Business</option>
<option>Other</option>
</select>
</form>
JS
$('select').change(function() {
var $selected = $('select option:selected');
if ('Other' === $selected.text()) {
$('form').append($('<input>').prop({'type':'text','id':'visa_other','name':'visa_other'}));
$('form').append($('<label>').prop({'for':'visa_other'}).html('Testing'));
} else {
$('input').remove();
$('label').remove();
}
});
The above code will only display a text box (and accompanying label) if the "Other" option is selected, and will then remove that text box if a different option is subsequently picked.
Hope that helps!

PHP jQuery with .change how can i combine both?

I have this codes with select name=client
with the help of jQuery i want to populate my textbox and other field.
this select helps me to change my client option.
so for example i click the select im going to choice the client B.
after that it will populate the text box and other fields. with the information came from database.
is my code correct, i post question here because i dont know why is my code not working.
my jQuery Codes
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
jQuery('select[name=client]').change(function(){
var com_code = jQuery(this).val();
<?
$getClient = "SELECT * FROM jon_com_for";
$getClient .= "WHERE com_code=";
$getClient .= "'com_code'";
$setClient = SET_SQL( $getClient );
?>
jQuery('input[name=com_code]').val( '<?=$setClient['com_code'];?>' );
jQuery('input[name=set]').val( '1' );
jQuery('input[name=company_name_for]').val( '<?=$setClient['company_name_for'];?>' );
jQuery('input[name=street_name]').val( '<?=$setClient['street_name'];?>' );
jQuery('input[name=post_code]').val( '<?=$setClient['post_code'];?>' );
jQuery('input[name=city]').val( '<?=$setClient['city'];?>' );
jQuery('input[name=country]').val( '<?=$setClient['country'];?>' );
});
});
</script>
my html code this html was inside of a dialog.
<div id="dialog" title="Step 1">
<form id="submit_steps" method="POST" action="new-template.php">
<input type="hidden" name="user_code" value="<?=$_SESSION['user_code'];?>" />
<input type="hidden" name="com_code" value="<?=comucode();?>" />
<input type="hidden" name="footnote" value="1" />
<input type="hidden" name="set" value="1" />
<div style="margin:20px auto;">
<label for="client">Selecteer klant : </label>
<select name="client">
<?php
$list_of_client = mysql_query( "SELECT * FROM jon_com_for" ) or die ( mysql_error() );
while( $row = mysql_fetch_array( $list_of_client ) ) {
echo '<option value="'.$row['com_code'].'">'.$row['company_name_for'].'</option>';
}
?>
</select>
</div>
<table cellpadding="3" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="right" valign="middle">BEDRIJFSNAAM :</td>
<td><input name="company_name_for" size="30" id="company_name_for" class="input" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">ONDERWERP VAN OFFERTE :</td>
<td><input class="input" name="sub_quo" id="sub_quo" size="30" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">STRAAT :</td>
<td><input class="input" name="street_name" id="street_name" size="30" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">Postcode :</td>
<td><input class="input" name="post_code" id="post_code" size="30" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">STAD :</td>
<td><input class="input" name="city" id="city" size="30" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">LAND :</td>
<td><input class="input" name="country" id="country" size="30" type="text" /></td>
</tr>
</tbody>
</table>
<div align="center">
<input type="submit" name="save_client_prof" value="Opsslaan" /> or Annuleren</p>
</div>
</form>
</div>
is that correct i put the PHP inside jQuery?
im sorry codes updated
also my dialog is not working anymore.
here are the code that i had changed thank you all...
<script type="text/javascript">
$(function(){
$('select[name=clientx]').change(function(e){
$('<img src="images/ajax-loader.gif" id="loading" style="width:auto;" />').appendTo("#client_details");
//Cancel the link behavior
e.preventDefault();
//Get the A tag
var com_code = $('select[name=clientx]').val();
var dia = jQuery( 'input[name=dia]' ).val();
$.ajax({
type:"GET",
url:"forms/company.php",
data: {dia: dia, com_code: com_code},
dataType: 'html',
target: '#dialog',
success: function(data){
$("#client_details").find('img#loading').remove();
$("#client_details").html(data);
}
})
});
});
</script>
Putting PHP code inside a jQuery change event does not mean that the PHP code is run when the change event happens.
PHP code written this way runs only once, when the page is loaded. This means that it will never know what the com_code JS variable contains after the click.
In order to execute PHP code whenever the JS change event happens, you need to use a technique called Ajax. Your javascript code needs to make a call to an entirely separate PHP program that will query the data and return the results back to the browser for the javascript code to work with.
This technique is well established, and jQuery provides functions that make it very easy to use. Look up some jQuery Ajax examples, and follow them from there.
Hope that helps.

adding input box dynamically when filling the other input box

i have a form like this
<FORM method="post">
<TABLE>
<TR>
<TD>Username</TD>
<TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD>
</TR>
<TR>
<TD>Age</TD>
<TD><INPUT type="text" value="" name="username" title="Enter Age"/><TD>
</TR>
<TR>
<TD>City</TD>
<TD><INPUT type="text" value="" name="username" title="Enter City"/><TD>
</TR>
<TR>
<TD>Comment</TD>
<TD><INPUT type="text" value="" name="username" title="Enter Comment"/><TD>
</TR>
</TABLE>
</FORM>
what i want is when user after filling the comment box ,when they press enter then dynamically another input box has to display with comment label by using javascript.
can anyone help me to write the code...
Try this my friend:
<FORM method="post">
<TABLE>
<TR>
<TD>Username</TD>
<TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD>
</TR>
<TR>
<TD>Age</TD>
<TD><INPUT type="text" value="" name="age" title="Enter Age"/><TD>
</TR>
<TR>
<TD>City</TD>
<TD><INPUT type="text" value="" name="city" title="Enter City"/><TD>
</TR>
<TR>
<TD>Comment</TD>
<TD><INPUT class="comment" type="text" value="" name="comment[]" title="Enter Comment"/><TD>
</TR>
</TABLE>
</FORM>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function(){
$('.comment').live('keydown', function(e){
$field = $(this);
// capture enter key being pressed
if (e.which == 13)
{
$html = $(this).parents('tr').clone();
$html.find('input').val('');
$html.appendTo($field.parents('table'));
}
});
});
</script>
First of all your all the input names in your form are the same (name="username"), you have to give each input a unique name.
so change comment input to
<TR id="comment">
<TD>Comment</TD>
<TD><INPUT type="text" value="" name="comment[]" title="Enter Comment"/><TD>
</TR>
note that i added id to the TR so it'll be easier to latch on to it using jquery and i also changed the input name to be comment[] since if you add a new comment to the dom you'll have a comment array.
if the new comment should have a new name like : 'comment2', you can change it to be just 'comment'
Now, using Jquery do the following:
$(document).keypress(function(e) {
//catch enter event
if(e.which == 13) {
var $comment = $('#comments);
//check that the user entered something in the comment input
if($comment.find('input').val().length > 0)
{
//create new comment element and attach it to DOM
var $newComment = $comment.clone().removeAttr('id');
$('form table').append($newComment);
}
}
});
let me know if that helped or if you need more info.

Need some resoultion. Javascript function not being called in click event in jquery

I am trying to call my function named isUrgencyTypeValid from my javascript code but it is not working. Please check what is the problem in my code.
Alert should get displayed which is not being displayed
My javascript function is not being called.
HTML Code
<td colspan="2" align="center"><input id="btnSubmit" type="submit" value="submit" runat="server"/></td></tr>
jQuery Call function
$("#btnSubmit").bind("click",function(){
alert(); // this is running
isUrgencyTypeValid();
});
javascript implemented function
function isUrgencyTypeValid()
{
alert("asd");
var i=0;
for(i=0;i<$("radio[name='urgencyType']").length;i++)
{
if($("radio[name='urgencyType']")[i].checked)
{
alert($("radio[name='urgencyType']")[i].value);
return true;
}
return false;
}
More description about my form is here
<form runat="server" name="myPage">
<table style="width: 100%;" cellpadding="5" cellspacing="5">
<caption>
Computer Support / Service Request
</caption>
<tr><td>First Name</td>
<td><input id="txtFirstName" type="text" value="First Name" runat="server"/><span class="error"></span></td></tr>
<tr>
<td>Last Name</td>
<td><input id="txtLastName" type="text" value="Last Name" runat="server"/><span class="error"></span></td></tr>
<tr>
<td>Email Address</td>
<td><input id="txtEmailAddress" type="text" value="Email Address" runat="server"/><span class="error"></span></td></tr>
<tr>
<td>Phone No</td>
<td><input id="txtPhoneNo" type="text" value="Phone No" runat="server" /><span class="error"></span></td></tr>
<tr>
<td>Do you have text messaging</td>
<td>
<span>Yes</span><input id="rdoYes" value="Yes" type="radio" runat="server"/>
<span>No</span><input id="rdoNo" value="No" type="radio" runat="server"/><span class="error"></span>
</td></tr>
<tr>
<td>Description of request*: </td>
<td><textarea id="txtDescription" cols="50" rows="10" runat="server"></textarea><span class="error"></span><span id="lengthCount"></span></td></tr>
<tr>
<td>Urgency of this support request:</td>
<td>
<input id="rdoAnyTime" name="urgencyType" value="Anytime" type="radio" runat="server"/><span>Anytime</span><br />
<input id="rdoCplDays" name="urgencyType" value="In the next couple of days" type="radio" runat="server"/><span>In the next couple of days</span><br />
<input id="rdoToday" name="urgencyType" value="Today" type="radio" runat="server"/><span>Today</span><br />
<input id="rdoUrgent" name="urgencyType" value="This is extremely urgent...I cannot wait!" type="radio" runat="server"/><span>This is extremely urgent...I cannot wait!</span><br />
<input id="rdoTalkSometime" name="urgencyType" value="Please contact me and we'll talk about it" type="radio" runat="server"/><span>Please contact me and we'll talk about it</span><br /><span class="error"></span>
</td></tr>
<tr>
<td colspan="2" align="center">Captcha To Be implemented.</td></tr>
<tr>
<td></td>
<td><input id="chkRequestCopy" type="checkbox" runat="server"/>Please send me a copy of this service request</td></tr>
<tr>
<td colspan="2" align="center"><input id="btnSubmit" type="submit" value="submit" runat="server"/></td></tr>
</table>
</form>
I copied your code and ran into the same issue. Then I looked at it closer and noticed you are missing a closing bracket in your isUrgencyTypeValid() function. The closing bracket for your for loop is missing. Firefox Error Console will also show this.
Once I added the bracket the alert worked fine.
function isUrgencyTypeValid()
{
alert("asd");
var i=0;
for(i=0;i<$("radio[name='urgencyType']").length;i++)
{
if($("radio[name='urgencyType']")[i].checked)
{
alert($("radio[name='urgencyType']")[i].value);
return true;
}
} //this was missing
return false;
}
Your radio selector is incorrect.
There's not such thing as a radio element, but there is a :radio pseudo-class selector.
Your code should read:
function isUrgencyTypeValid()
{
alert("asd");
var i=0;
for(i=0;i<$("input[name='urgencyType']:radio").length;i++)
{
if($("input[name='urgencyType']:radio")[i].checked)
{
alert($("input[name='urgencyType']:radio")[i].value);
return true;
}
return false;
}
** EDIT **
In addition to the changes above, since the alert never occurs, this indicates that isUrgencyTypeValid is not being called.
The most likely explanation is that you're not waiting until the DOM is loaded, before you bind the your handler to the click event of the button. You should have some code somewhere that looks like this:
$(function()
{
/*
* ... other code ...
*/
$("#btnSubmit").bind("click",function(){
isUrgencyTypeValid();
});
/*
* ... other code ...
*/
}

How can I dynamically add input fields to a form?

I'm not much of a web programmer, but I'm creating a simple web app that has a form where the user can enter a series of points (x,y,z) but I don't know how many the user is going to enter. I don't want to guess the probable maximum (100 maybe?) and put 100 fields on the form because it would look ugly. What's the easiest way to add more fields (or unhide fields) as the user enters data without contacting the server.
Currently I'm just using html & php, but I assume to do this I'll need javascript?
Currently my code looks like this, as the user enters data, I want another row to appear.
<form action="edit.php" method="post">
<table border=1>
<tr>
<td>
<td>X
<td>Y
<td>Z
</tr>
<tr>
<td>1</td>
<td><input type=text name=x1 size=10 value="0.4318"></td>
<td><input type=text name=y1 size=10 value="0.0000"></td>
<td><input type=text name=z1 size=10 value="0.1842"></td>
</tr>
<tr>
<td>2</td>
<td><input type=text name=x2 size=10 value="0.4318"></td>
<td><input type=text name=y2 size=10 value="0.0000"></td>
<td><input type=text name=z2 size=10 value="-0.1842"></td>
</tr>
<tr>
<td>3</td>
<td><input type=text name=x3 size=10 value="-0.3556"></td>
<td><input type=text name=y3 size=10 value="0.0000"></td>
<td><input type=text name=z3 size=10 value="0.1636"></td>
</tr>
... I want more to appear here...
</table>
<button name="submit" value="submit" type="submit">Save</button>
</form>
Any idea the easiest way? Thanks...
I would use jQuery and append the new inputs.
You will most likely have to use javascript, yes. You can use this or write your own using it as a reference:
http://www.mredkj.com/tutorials/tableaddrow.html
1: HTML :
<div class="form-group app-edu">
<label for="Example Details" class="col-xs-3 col-sm-2 control- label">Example Details</label>
<div class="form-group add-field">
<div class="user">
<select name="xx[]" id="xx" required>
<option value="">Education</option>
<option value="Class 10">Class 10</option>
<option value="Class 12">Class 12</option>
<option value="Diploma">Diploma</option>
<option value="PG Diploma">PG Diploma</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="Masters Degree">Masters Degree</option>
<option value="Other Certifications">Other Certifications</option>
</select>
<input type="text" placeholder="Name of Board" name="xx[]" id="xx" required>
<input type="text" placeholder="Name of Institute" name="xx[]" required id="xx">
<input type="text" placeholder="xx" name="xx[]" required id="xx">
<select name="xx[]" id="xx" required>
<option value="">xx</option>
<option value="xx">xx</option>
<option value="xx">xx</option>
<option value="xx">xx</option>
</select>
<input type="text" placeholder="Year and Month of Exam" name="date[]" required id="date" autocomplete="off">
</div>
<div class="add-more"><span>+</span>Add More</div>
</div>
</div>
2: PHP
if(isset($_POST['submit']))
{
$xx= json_encode($_POST["xx"]);
$xx= json_encode($_POST["xx"]);
$xx= json_encode($_POST["xx"]);
$xx= json_encode($_POST["xx"]);
$xx= json_encode($_POST["xx"]);
$xx= json_encode($_POST["xx"]);
$query=mysql_query("INSERT INTO `xxx` (`xx`, `xxx`, `xxx`) VALUES ('NULL', '$xx','$xx','$xx')");
}
3: JS
var data_fo = $('.add-field').html();
var sd = '<div class="remove-add-more">Remove</div>';
var data_combine = data_fo.concat(sd);
var max_fields = 5; //maximum input boxes allowed
var wrapper = $(".user"); //Fields wrapper
var add_button = $(".add-more"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append(data_combine); //add input box
//$(wrapper).append('<div class="remove-add-more">Remove</div>')
}
// console.log(data_fo);
});
$(wrapper).on("click",".remove-add-more", function(e){ //user click on remove text
e.preventDefault();
$(this).prev('.user').remove();
$(this).remove();
x--;
})
What you're saying is that you're hand writing the input tags? Or are you saying that you want a dynamic action where a user clicks a button and it adds more table rows?
In anycase, for your code, you just need a loop, like so. I assume $data is whatever data you want to set based on an array that is probably from the database or something:
<?php
for($i=0, $iMaxSize=count($data); $i<$iMaxSize; $i++)
{
?>
<tr>
<td><?= $i+1 ?></td>
<td><input type=text name=x1 size=10 value="<?=$data[$i]['something']"></td>
<td><input type=text name=y1 size=10 value="<?=$data[$i]['somethingelse']"></td>
<td><input type=text name=z1 size=10 value="<?=$data[$i]['somethingelseagain']"></td>
</tr>
<?php
} // end for
?>
Of course you can't copy and past the above, but that's a good starting point.
For dynamically doing it, you can't use php. What it sounds like you want to use is javascript ajax, and php combination.
Appends some HTML to all paragraphs.
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<p>I would like to say: </p>
<script>
$("p").append("<strong>Hello</`enter code here`strong>");
</script>
</body>
</html>

Categories