Add submit button to HTML form - php

I have a simple form with four input field (contact id, tel number, name, salutation). if i input 'contact id' & press Enter button, the rest of the field will auto filled retrieve from DB. now I want to add a 'submit' button to the form, so that those info can be save to another DB table by clicking on that button. i've tried to add the button, but the auto fill function is not working anymore. anyone can help? thanks in advance :)
here is my index.html file:
<html>
<body>
<script language="javascript" type="text/javascript">
function ajaxFunction(e){
var e=e || window.event;
var keycode=e.which || e.keyCode;
if(keycode==13 || (e.target||e.srcElement).value==''){
var http; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
http = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var url = "getagentids.php?param=";
var idValue = document.getElementById("agid").value;
var myRandom = parseInt(Math.random()*99999999); // cache buster
http.open("GET", "getagentids.php?param=" + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
}
}
</script>
<form>
<table>
<tr>
<td>Contact ID:</td>
<td><input id="agid" type="text"
name="contactid" onkeyup="ajaxFunction(event)"></td>
</tr>
<tr>
<td>Tel Number:</td>
<td><input id="agtel" type="text"
name="contacttel"></td>
</tr>
<tr>
<td>Name:</td>
<td><input id="agfn" type="text"
name="contactfullname"></td>
</tr>
<tr>
<td>Salutation:</td>
<td><input id="agsal" type="text"
name="contactsalutation"></td>
</tr>
<tr>
<td><input type="reset" value="Clear"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>

If you want to add the submit button after you populate the form, you can do this by a using innerHTML
...
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
document.getElementById('buttons').innerHTML = "<input type=\"submit\" name=\"submit\" value=\"Submit\"/>"; // add Submit button by innerHTML
}
...
And in your table add a <div id="buttons"> to where you want to add the submit button
<tr>
<td><div id="buttons"></div><input type="reset" value="Clear"></td>
<td></td>
</tr>

Related

Multi-file upload using google app script

I am trying to use use a form and image uploader using google app scripts. I want to have the option to dynamically increase the number of images uploaded using a button, and then upload those to my drive. I am able to add more file inputs, but can't seem to get the files to upload if I have more than one image. I commented out the for loop, and am using only two images as an example. The if/else statement functions, but it does not upload the image. I am relatively new to programming and very new to google app scripts. Any help would be much appreciated. Thanks!
form.html:
<form id="myForm">
<p>Name</p>
<input type="text" name="PosterName">
<p>Email</p>
<input type="text" name="email">
<p>What are you selling/renting?</p>
<table>
<tr>
<td><input type="radio" name="sell" value="apt" id="apt"></td>
<td><label for="apt">Apartment</label></td>
</tr>
<tr>
<td><input type="radio" name="sell" value="furn" id="furn"></td>
<td><label for="furn">Furniture</label></td>
</tr>
<tr>
<td><input type="radio" name="sell" value="books" id="books"></td>
<td><label for="books">Books</label></td>
</tr>
<tr>
<td><input type="radio" name="sell" value="other" id="other"></td>
<td><label for="other">Other</label></td>
</tr>
</table>
<p>Give a description</p>
<textarea name="desc" rows="10" cols="50"></textarea>
<table id="submittable">
<tr>
<td><input type="file" name="myFile1"></td>
<td><button onclick="addmore();" id="D">Add More</button></td>
</tr>
</table>
<input type="submit" value="Upload File"
onclick="this.value='Uploading...';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
<input type="text" id="test" name="appt">;
</form>
<div id="output"></div>
<script>
function addmore() {
var tname = document.getElementById('submittable');
var row = tname.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var numrows = tname.rows.length;
cell1.id = "A";
cell2.id = "B";
var place1 = document.getElementById("A");
var place2 = document.getElementById("B");
var fle = document.createElement("input");
var add = document.createElement("button");
add.setAttribute("onclick", "addmore()");
var x = document.getElementById('test');
x.setAttribute("value", numrows);
fle.setAttribute("type", "file");
fle.setAttribute("name", "myFile" + numrows);
var y = fle.getAttribute("name");
add.innerHTML = y;
place1.appendChild(fle);
place2.appendChild(add);
cell1.id = "C";
cell2.id = "D";
var place3 = document.getElementById("D");
place3.parentNode.removeChild(place3);
}
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
And
code.gs:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "shukimages";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var spreadsheet = DriveApp.getFilesByName(dropbox);
var ss = SpreadsheetApp.openById("1O4GM0DT5kqu5MNLcYFZe_vrI2KK1lmO9s5XviHWsMEg");
var sheet = ss.getSheets()[0];
sheet.appendRow([form.PosterName, form.email, form.sell, form.desc]);
//return "Files uploaded successfully";
var nums = form.appt;
if (nums < 1) {
var blob = form.myFile1;
var file = folder.createFile(blob);
return "File uploaded successfully";
} else {
return "Files uploaded successfully";
//for (i = 1; i <= nums; i++) {
var blob = form.myFile2;
var file = folder.createFile(blob);
//}
}
} catch (error) {
return error.toString();
}
}
EDIT:
A little more clarification; if I only attempt to upload one image, it works and the image is uploaded, but it will not upload more than one image.
Where I got createFile:
https://developers.google.com/apps-script/reference/drive/drive-app

Autofill Input Field Based On Another Input Field OnKeyUp (Dynamic Generated)

I hope today I'll find good solution for my case below.
Case
Actually, I have dynamic input fields and let say there field A, B and C. So, the purpose is when field A receives OnKeyUp Action then field B and C will autofill based query result from field A value.
index.php
<html>
<body>
<script type="text/javascript">
var ct = 1;
// Function Tambah Form
function new_link()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// Link to Delete Form
var delLink = '<div style="text-align:left"><a id="del" href="javascript:delIt('+ ct +')">Delete</a></div>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// Function Delete Form
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(ele);
}
function ajaxFunction(str,divId)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById(divId).innerHTML=httpxml.responseText;
}
}
var url="cek.php";
url=url+"?txt="+str;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<form name="myForm">
<a id="new" href="javascript:new_link()">ADD NEW PAYMENT</a>
<div id="newlink">
<table width="50%" border="1">
<tr>
<td><input type="text"
onkeyup="ajaxFunction(this.value,'displayDiv');" name="username" /></td>
<td>
<div id="displayDiv">
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr"></td><td><input type="text" name="amount"></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
<div id="newlinktpl" style="display:none" >
<div>
<table width="50%" border="1">
<tr>
<td><input type="text"
onkeyup="ajaxFunction(this.value,'displayDiv<?php echo ++$np;?>');" name="username" /></td>
<td>
<div id="displayDiv<?php echo $np;?>">
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr"></td><td><input type="text" name="amount"></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</div>
cek.php
<?php
mssql_connect('localhost','sa','');
mssql_select_db('NCD');
$in=$_GET['txt'];
$msg="";
$t=mssql_query("SELECT * FROM DPaym1 WHERE (JENIS = 1) AND (DPSPAID = 0) AND (CNDPSNO = '$in')");
while($nt=mssql_fetch_array($t)){
//$msg = "$nt[CURRID]#$nt[AMOUNT]";
$curr = "$nt[CURRID]";
$amount = "$nt[AMOUNT]";
}
//echo $msg;
//echo "$curr $amount";
?>
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr" value="<?php echo $curr?>"></td>
<td><input type="text" name="amount" value="<?php echo $amount?>"></td>
</tr>
</table>
Above code already success for row 1. but when I input value in row 2 (dynamic add new row) the result change field B and C in row 1 not in row 2.

Why the form submitted using AJAX is redirecting to next page and the error/success messages are not displayed into alert on the same page?

I'm using PHP, Smarty, jQuery, AJAX, etc. for my website.Following is HTML code of my form which I'm submitting using AJAX:
<form name="question_issue_form" id="question_issue_form" action="http://localhost/xyz/pqr/web/control/modules/questions/question_issue.php">
<input type="hidden" name="form_submitted" id="form_submitted" value="yes"/>
<input type="hidden" name="op" id="op" value="question_issue"/>
<input type="hidden" name="question_id" id="question_id" value="35718"/>
<table class="trnsction_details" width="100%" cellpadding="5">
<tbody>
<tr>
<td></td>
<td>
<input type="checkbox" name = "que_issue[]" value = "Question is wrong" id ="chkQueWrong">Question is wrong</input>
</td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Answers are wrong" id ="chkAnsWrong">Answers are wrong</input></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Question direction is incorrect" id ="chkDirIncorrect">Question direction is incorrecct</input></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Other" id ="chkOther">Other</input></td>
</tr>
<tr>
<td></td>
<td class="set_message" style="display:none;"><textarea name="que_issue_comment" id = "que_issue_comment" rows="4" cols="25" maxlength="100"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" id="report_question_issue" class="c-btn submit_form"/></td>
</tr>
</tbody>
</table>
</form>
The AJAX code for submitting the form is as follows:
$(document).ready(function() {
$('#question_issue_form').submit(function() {
var ans = confirm("Are you sure to report the question issue?");
if (!ans) {
return false;
}
var post_url = $(this).attr('action');
$.ajax({
type: "POST",
url: post_url,
data: $('#question_issue_form').serialize(),
dataType: 'json',
success: function(data) { alert(data);
var error = data.error_message;
if(error)
alert(error);
else {
alert("Question issue has been reported successfully.");
$.colorbox.close();
}
}
});
});
});
The PHP code of a file(question_issue.php) where I'm submitting this form is as follows:
<?php
require_once("../../includes/application-header.php");
$objQuestionIssue = new QuestionIssue();
prepare_request();
$request = $_POST ;
$user_type = $_SESSION[SESSION_NAME_CONTROL][STAFF_TYPE];
if($user_type == 'super_admin' || $user_type == 'admin' || $user_type == 'data_entry_operator' || $user_type == 'owner' || $user_type == 'faculty' || $user_type == 'content_development_head' || $user_type == 'test_admin' || $user_type == 'student_admin')
$requested_user_type = 'staff';
else
$requested_user_type = 'student';
$form_data = array();
$form_data['question_id'] = $request['question_id'];
$form_data['reported_site_id'] = SITE_ID;
$form_data['reported_user_type'] = $requested_user_type;
$form_data['reported_user_id'] = $_SESSION[SESSION_NAME_CONTROL][STAFF_ID];
$form_data['que_issue'] = implode(",", $request['que_issue']);
$form_data['que_issue_comment'] = $request['que_issue_comment'];
$form_data['que_issue_date'] = time();
switch( $op ) {
case "question_issue":
if($request['form_submitted']=='yes') {
$ret = $objQuestionIssue->InsertQuetionIssue($form_data, $question_issue_error_messages);
/*If condition : If there are any errors in submission of a report question form*/
if(!$ret) {
$error_msg = $objQuestionIssue->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg['error_msgs'];
$data = json_encode($data);
echo $data;
die;
/*Else condition : If there is no error in submission of a report question form*/
} else {
$data = array();
$data['success_message'] = "success";
$data = json_encode($data);
echo $data;
die;
}
} else {
$smarty->assign('question_id', $request['question_id']);
$file_to_show = 'question-issue.tpl';
}
$smarty->display($file_to_show);
break;
die;
}
?>
The issue I'm facing is when I click on Ok button of confirmation alert, the form gets submit but the error messages or success messages in json format are appearing on a blank screen.
Actually they should be appeared in a pop-up alert and page should not get redirected to other URL. But the error/success messages are printing on a blank white page and page is also redirected to the question_issue.php. Can someone please help me in avoiding these things and showing the error/success messages into an alert box on the same page?
I think you should prevent default behavior of the form, so it won't really submit but only ask for json:
$('#question_issue_form').submit(function(e) {
e.preventDefault();
// your code

Submitting dynamic ajax field

I have an an ajax drop down box that if selected adds another field to a form, this works but this new field doesn't get submitted with the form. Any suggestions?
findTest.php called via ajax
<?php
$work = ($_GET['work']);
if ($work == "Work1") {
?>
<tr>
<td>New work1<input name="newWork1" size="20" type="text"/></td>
</tr> <?
} elseif ($work == "Work2") {
?>
<tr>
<td>New work<input name="newWork" size="20" type="text"/></td>
</tr><?
} elseif ($work == "Work3") {
?>
<tr>
<td>No work today</td>
</tr><?
}?>
Test.php
<?php
$page = '';
$answer = null; //clean start.
$Comments = $_POST['Comments'];
$new = $_POST['new'];
// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
?>
<p align="center" id="infomessage">Test message <?= $_POST['Comments'] ?>
and <?= $_POST['new'] ?> or this should be
work2 <?= $_POST['newWork'] ?></p>
<? } ?>
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007#yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
function getWorkDone(workId) {
var strURL = "findTest.php?work=" + workId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('workdiv').innerHTML = req.responseText;
} else {
alert("1 There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<table id="meters" width="800" border="0" cellspacing=0 cellpadding=2>
<form name="meters" method="POST" action="test.php">
<tr>
<td width="200" align="right">Work Done:</td>
<td><select name="WorkDone" tabindex="14"
onchange="getWorkDone(this.value)">
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Work3">Work3</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td><p id="workdiv">New Work<input name="newWork" size="20"
type="text"/></td>
</tr>
<tr>
<td width="200" align="right">Comments:</td>
<td><textarea name="Comments" tabindex="40" cols="40"
rows="4"><?= $_POST[Comments] ?></textarea></td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="Submit"
class="button" value="Submit">
</td>
</tr>
</tr>
</table></form>
UPDATE: new code.
findTest.php called via ajax
<?php
if (isset($_GET['work'])) {
$work= $_GET['work'];
if ($work == "Noworktoday") {
echo "<tr><td>No work today</td></tr>";
} else {
echo "<tr><td>New ".$work."<br>";
echo "<input name=\"new".$work."\" type=\"text\"";
echo " size=\"20\" value=\"new".$work."\" />";
echo "</td></tr>";
}
}?>
And Test.php
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";
}
?>
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007#yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getWorkDone(workId) {
var strURL="findTest.php?work="+workId+"&new1="+"&$new";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('workdiv').innerHTML=req.responseText;
} else {
alert("1 There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<table id="meters" width="800" border="0" cellspacing=0 cellpadding=2>
<form name="meters" method="POST" action="test.php">
<tr>
<td width="200" align="right" >Work Done:</td>
<td><select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="">Select</option>
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Work3">Work3</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr >
<td ></td>
<td ><p id="workdiv">New Work<input name="newWork" size="20" type="text" /></td>
</tr>
<tr>
<td width="200" align="right" >Comments:</td>
<td><textarea name="Comments" tabindex="40" cols="40" rows="4" ><?=$_POST[Comments]?></textarea></td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="Submit" class="button" value="Submit">
</td>
</tr>
</tr>
</table>
</form>
UPDATE edit double up and correct $newWork to $newWork1
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork1 = $_POST['newWork1']; } else {
$newWork1 = 'n/a'; }
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";}
?>
This now shows n/a but not the value of newWork1
You have very modified the original question, I can only respond to what was previously.
The important part is also findTest.php
from this script you replace your
document.getElementById('workdiv').innerHTML=req.responseText;
So how does findTest.php know about $_POST['newwork1']
<td>New work1<input name="newWork1" ... value="<?=$_POST['newwork1']?>" /></td>..
This must come via a GET / POST, but in your GET there ist only
strURL="findTest.php?work="+workId;
Only 1 GET variable named $_GET['work'].
and you use this variable (without test)
$work=$_GET['work'];
And then you mixed the request from $_GET to $_POST['newwork1']
so why not use your select value to get it all together.
Test.php
...
<select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Noworktoday">No work today</option>
<option value="Other">Other</option>
</select>
...
findTest.php
if (isset($_GET['work'])) {
//for example : $work == "Work1"
$work=$_GET['work'];
if ($work=="Noworktoday") {
echo "<tr><td>No work today</td></tr>";
} else {
echo "<tr><td>New ".$work."<br>";
echo "<input name=\"new".$work."\" type=\"text\"";
echo " size=\"20\" value=\"new".$work."\" />";
echo "</td></tr>";
}
//<tr><td>New Work1<input name="newWork1" type="text" size="20" value="newWork1" /></td></tr>
Update:
You can not see your values because you did'nt echo them
and you have to test all $_POST
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a';
}
if (isset($_POST['newWork1'])) {
$newWork1 = $_POST['newWork1']; } else {
$newWork1 = 'n/a';
}
....
and so on for all possible values
echo your variables
if (isset($_POST['Submit'])) {
?>
<p align="center" id="infomessage">Test message = <? echo $Comments; ?>
and = <? echo $newWork1; ?> or this should be
work2 = <? echo $newWork; ?></p>
<? } ?>
Update:
I can not see the actual code, you need a if (isset ... for all possible variables . In my example I have described only two possibilities. You need also e.g.
if (isset($_POST['newWork2'])) { ...
if (isset($_POST['newOther'])) { ...
and so on !! And make only asimple output.
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";
}
and put it logical together
This is illogical Work2 assigned to newWork !!!

Validate Dynamic Dropdown With Ajax

I have a drop down menu of mobile brands. When a user selects a mobile brand a dynamic drop populates with the mobile model according to the mobile brand I want to validate that mobile model drop down for a blank select value. I am using ajax xmlhttp request for getting the mobile model drop down menu.
My entire code is:
Code for page with mobile brand drop down menu
<script type="text/javascript">
function validate() {
if (document.myform.step3_mobilebrand.value=="") {
document.getElementById("error1").innerHTML = (error1) ? "<img src='images/formerror.gif' height='15' width='18'>" : "";
document.myform.step3_mobilebrand.focus();
return false;
}
var myTextField = document.myform.getElementById('step3_mobilemodel').value;
if (myTextField == "") {
document.getElementById("error2").innerHTML = (error2)?"<img src='images/formerror.gif' height='15' width='18'>" : "";
document.myform.step3_mobilemodel.focus();
return false;
}
}
</script>
<?php
if (isset($_POST['submitted']) and $_POST['submitted']=="Continue") {
$mobilebrand1 = $_POST['step3_mobilebrand'];
$mobilemodel1 = $_POST['step3_mobilemodel'];
if ($mobilemodel1=="") {
echo "Please Select Mobile Model";
}
$connectiontype=$_POST['step3_connectiontype'];
$internet=$_POST['step3_internet'];
include("admin/config.php");
$sql="insert into member_detail (mobilebrand,mobilemodel,connection_type,internet) values('$mobilebrand1','$mobilemodel1','$connectiontype','$internet')";
mysql_query($sql);
}
?>
<script type="text/javascript">
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
<form name="myform" method="post" action="" onsubmit="return validate();">
<table>
<tr>
<td>Mobile Brand</td>
<td><?php
include ("admin/config.php");
echo "<select name='step3_mobilebrand' onchange='showUser(this.value)'><option value='' selected>Select Mobile Brand</option>";
$result = mysql_query ("select * from mobilebrand order by mobilebrand");
while ($adcom=mysql_fetch_array($result)) {
echo "<option value=\"".$adcom['id']."\">".htmlspecialchars($adcom['mobilebrand'])."</option>";
}
echo "</select>";?><span id="error1" style="color:red;"></span></td>
</tr>
</table>
<div id="txtHint"></div>
<table>
<tr>
<td>Connection Type</td>
<td><input type="radio" name="step3_connectiontype" value="PrePaid" checked="checked">Prepaid
<input type="radio" name="step3_connectiontype" value="PostPaid">Postpaid
<span id="error3" style="color:red;"></span>
</td>
</tr>
<tr>
<td>Have Internet On Mobile</td>
<td><input type="radio" name="step3_internet" value="Yes" checked="checked">Yes
<input type="radio" name="step3_internet" value="No">No
<span id="error4" style="color:red;"></span>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitted" value="Continue"></td>
</tr>
</table>
</form>
and the code of getuser.php is
<table>
<tr>
<td>Mobile Model</td>
<td>
<?php
$q=$_GET["q"];
include("admin/config.php");
echo "<select name='step3_mobilemodel' id='step3_mobilemodel' ><option value=''>Select Mobile Model</option>";
$result = mysql_query ("select * from mobilemodel where brandcode='".$q."'");
while ($adcom=mysql_fetch_array($result)) {
echo "<option value=\"".$adcom['mobilemodel']."\">".htmlspecialchars($adcom['mobilemodel'])."</option>";
}
echo "</select>"; ?>
</td>
</tr>
</table>
The Output am getting is correct i just want to validate the mobile model drop down menu for blank select
For validating select you can do:
var e = document.getElementById("step3_mobilemodel");
var mobileVal = e.options[e.selectedIndex].value;
if(mobileVal == "") {
...//show your error here
}
Hope it helps
This is pretty much what Sudhir posted (+1 from me) but with an example in a fiddle: http://jsfiddle.net/5TYwH/1/ using the onchange event handler.
May be you can just add a php validation for $q.
<table>
<tr>
<td>Mobile Model</td>
<td>
<?php
$q=$_GET["q"];
echo "<select name='step3_mobilemodel' id='step3_mobilemodel'>"
if($q != ""){
include("admin/config.php");
echo "<option value=''>Select Mobile Model</option>";
$result = mysql_query ("select * from mobilemodel where brandcode='".$q."'");
while ($adcom=mysql_fetch_array($result)) {
echo "<option value=\"".$adcom['mobilemodel']."\">".htmlspecialchars($adcom['mobilemodel'])."</option>";
}}else{ echo "<option value=''>Please select a mobile first</option>";} echo "</select>";?></td>
</tr></table>

Categories