clicking on the select option how to show hidden field using javascript? - javascript

I am working on php how to show hidden field?
I have bp_scholarship_enq table in my database and this database i have occupation field i want to add new occupation in my database how i do it?
<script>
function showss(ids)
{
var idss=ids;
if(idss=="other")
document.getElementById(idss).style.display='block';
}
</script>
<?php
echo "<select name='occupation' id='link_block' value='Source' style='width:196%'>
<option>select occupation </otpion>";
$sql = "SELECT * FROM bp_scholarship_enq";
$info = mysql_query($sql);
while ($row = mysql_fetch_array($info))
echo "<option > '" . #$row["occupation"] . "'</option>";
echo '<option onClick="showss('.input_field.')">other</option>';
echo "</select>";
echo '<input type="hidden" name="other" id="input_field" />';
?>

Hidden fields are not meant to be visible. You could use a textbox and set its visiblity to false in css and make visible it on changing the select option.
<input type="text" name="other" id="input_field" style="display:none"/>
<select name='occupation' id='link_block' value='Source' style='width:196%' onChange="showText(this.selectedIndex);">
...............
...............
<option value="other">other</option>
</select>
<script>
function showtext(ind){
var selectBox = document.getElementById('link_block');
if(selectBox.options[ind].value=="other"){
document.getElementById('input_field').style.display = "block";
}else{
document.getElementById('input_field').style.display = "none";
}
}
</script>

Instead of
<input type="hidden" name="other" id="input_field" />
Make it:
<input id="otherOccupation" class="hide" name="other" id="input_field" />
With hide being a class that sets visibility:hidden;
Then have some jquery to remove that class when the user selects "other"
$("#otherOccupation").removeClass("hide")

Related

Get the values of while loop using button with js

How can I get the values in the while loop using button with js?
<?php
while ($row = mysqli_fetch_array($query))
{
echo '<input type="text" name="sample" value="'.$row['sample'].'">';
}
?>
Thanks
You can get the value of textbox when you click on a button.
<input type="text" name="sample[]" value="abc" class="valueInput">
<input type="text" name="sample[]" value="xyz" class="valueInput">
<input type="text" name="sample[]" value="pqr" class="valueInput">
<input type="button" class="getValue" value="Get Value">
Note: I have set the static input box you can make it dynamic but make sure please add the class as valueInput.
Jquery Code.
$(document).on('click','.getValue',function(){
var valArr = [];
$(".valueInput").each(function(){
valArr.push($(this).val());
});
console.log(valArr);
})
The name of the input field should indicate an array with [].
<form action="action.php" method="POST">
<?php
while ($row = mysqli_fetch_array($query)){
echo '<input type="text" name="sample[]" value="'.$row['sample'].'">';
}
?><input type="submit">
</form>
action.php: (Processes the data on submit)
<?php
echo "<pre>";
print_r($_POST['sample']);
echo "</pre>";

Populating a dependent dropdown with AJAX, PHP and MYSQL

I'm trying to populate a dropdown with id='gymnasts' based on the value of another dropdown with id='classes'.
I understand that I must use AJAX, however after following multiple different tutorials I cannot seem to make the second aforementioned dropdown display any options whatsoever.
My code is as follows:
reports.php:
<script>
function getGymnasts(val){
alert('gets');
$.ajax({
type:"POST",
url:"ajax_populate.php",
data: 'classid='+val,
success: function(data){
$("$gymnasts").html(data);
}
});
}
</script>
<form method="post">
<table>
<tr><td>Select Class:</td><td><select id="classes" onChange="getGymnasts(this.value)" placeholder="Select Class" required/>
<?php $classes = mysqli_query($GLOBALS['link'], "SELECT * FROM classes;");
foreach($classes as $class){
echo('
<option value="'.$class['id'].'">'.$class['level'].'</option>
');
}?>
</select></td></tr>
<tr><td>Select Gymnast:</td><td>
<select id="gymnasts" placeholder="Select Gymnast" required/>
</select></td></tr>
<tr><td>Report:</td><td><textarea name="body" cols="60" rows="20" placeholder="Report text" required/></textarea></td></tr>
<tr><td>Progression Grade:</td><td><input type="text" name="progression" placeholder="A" required/></td></tr>
<tr><td>Effort Grade:</td><td><input type="text" name="effort" placeholder="A" required/></td></tr>
<tr><td></td><td><input type="submit" name="saveReport" value="Save"><input type="submit" name="savesendReport" value="Save and Send"></td></tr>
</table>
</form>
ajax_populate.php
include('dbconnect.php');
$classid = $_POST['classid'];
$sql = "SELECT * FROM gymnasts WHERE classid = '$classid'";
$result = mysqli_query($GLOBALS['link'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg ='<option value="'. $row["id"] .'">'. $row["name"] .'</option>';
}
}
else{$msg .="No Gymnasts were found!";}
echo ($msg);
mysqli_close($GLOBALS['link']);
Please help!
You are using wrong selector for gymnasts id, use # instead of $ in your success callback like
success: function(data){
$("#gymnasts").html(data);
// ^ change $ to # here
}
Also, make an option if no result found
else{$msg .="<option>No Gymnasts were found!</option>";}

Option Menu with 2 Values

I have the following option menu in a form that will insert the fields into a table:
<option value="">select staff</option>
<?php
do {
?>
<option value="<?php echo $row_Staff['Staff_Name']."||".$row_Staff['Email']?>">
<?php echo $row_Staff['Staff_Name']?></option>
<?php
} while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
I have 2 fields from source table in value of option from technique explained in How to post two values in an option field?: Staff_Name and Email.
I am trying to insert both fields from the form into a table using:
<input type="hidden" name="Staff_Name" class="form-control" id="Staff_Name" value=<?php
$staff =$_POST['Staff_Data'];
$staff_name = explode("||", $staff);
echo $staff_Name[0];
?> />
and
<input type="hidden" name="Email" class="form-control" id="Email" value=<?php
$staff =$_POST['Staff_Data'];
$email = explode("||", $staff);
echo $email[1];
?> />
Unfortunately, I can see the 2 fields separated by "||" in the table if I insert the option menu value but cannot seem to insert Staff_Name or Email into individual fields. On insert both fields are blank. Any help would be appreciated.
Instead of combine staffname and staffemail in the dropdown value. Please staffname in dropdown value and staffemail in the property of dropdown and onchange of the dropdown set those values in the hidden inputs so you will easily get those values on the form submission.
Please go through below code and let me know if you have any query.
//Dropdown
<select id="ddStaff">
<option value="">select staff</option>
<?php
do { ?>
<option value="<?php echo $row_Staff['Staff_Name']; ?>" staff-email = "<?php echo $row_Staff['Email'];?>">
<?php echo $row_Staff['Staff_Name']?>
</option> <?php
} while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
//Input hidden fields to store staff name and staff email
<input type="hidden" id="txtStaffName" name="txtStaffName">
<input type="hidden" id="txtStaffEmail" name="txtStaffEmail">
//Jquery code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#ddStaff").on('change',function(){
var staffName = $(this).val();
var staffEmail = $('option:selected', this).attr('staff-email');
$("#txtStaffName").val(staffName);
$("#txtStaffEmail").val(staffEmail);
});
});
</script>
Please check it on https://jsfiddle.net/z4a0fywp/
For testing purpose I have not made the inputs hidden in the fiddle.

PHP ifelse makes the post values to database null with upload

I try to make an upload form and post some values to database. I write this code, but when I echo it, it gives a result and when I check the database, I get values null - there are no values... the file uploaded and was renamed, but no values were send to database.
table name: companies
columns:
CO_ID
company_name
company_sign_1
company_sign_name_1
company_sign_name_p_1
company_sign_2
company_sign_name_2
company_sign_name_p_2
company_sign_3
company_sign_name_3
company_sign_name_p_3
company_logo_1
company_logo_2
company_logo_3
My code is:
<script type="text/javascript">
function showfield(name){
if(name=='company_sing_1'){
document.getElementById('div1').innerHTML='Manager Name 1:<BR><input type="text" name="company_sign_name_1" /><BR>Manager Position 1:<BR><input type="text" name="company_sign_name_p_1" />';
}else if(name=='company_sing_2'){
document.getElementById('div1').innerHTML='Manager Name 2:<BR><input type="text" name="company_sign_name_2" /><BR>Manager Position 2:<BR><input type="text" name="company_sign_name_p_2" />';
}else if(name=='company_sing_3'){
document.getElementById('div1').innerHTML='Manager Name 3:<BR><input type="text" name="company_sign_name_3" /><BR>Manager Position 3:<BR><input type="text" name="company_sign_name_p_3" />';
}
else document.getElementById('div1').innerHTML='';
}
</script>
<?php
$newfilenamepath = "$filepath_d" . "$filename_d";
$company_name= ($_POST['company_name'])?$_POST['company_name']:'';
$upload_type= ($_POST['upload_type'])?$_POST['upload_type']:'';
if ($upload_type = "company_sing_1") {
$company_sign_name_1= ($_POST['company_sign_name_1'])?$_POST['company_sign_name_1']:'';
$company_sign_name_p_1= ($_POST['company_sign_name_p_1'])?$_POST['company_sign_name_p_1']:'';
mysql_query("update companies set $upload_type='".$newfilenamepath."', company_sign_name_1='".$company_sign_name_1."', company_sign_name_p_1='".$company_sign_name_p_1."' where CO_ID='".$company_name."'");
} elseif ($upload_type = "company_sing_2") {
$company_sign_name_2= ($_POST['manager2'])?$_POST['manager2']:'';
$company_sign_name_p_2= ($_POST['manager2_pos'])?$_POST['manager2_pos']:'';
mysql_query("update companies set $upload_type='".$newfilenamepath."', company_sign_name_2='".$company_sign_name_2."', company_sign_name_p_2='".$company_sign_name_p_2."' where CO_ID='".$company_name."'");
} elseif ($upload_type = "company_sing_3") {
$company_sign_name_3= ($_POST['manager3'])?$_POST['manager3']:'';
$company_sign_name_p_3= ($_POST['manager3_pos'])?$_POST['manager3_pos']:'';
mysql_query("update companies set $upload_type='".$newfilenamepath."', company_sign_name_3='".$company_sign_name_3."', company_sign_name_p_3='".$company_sign_name_p_3."' where CO_ID='".$company_name."'");
} else {
mysql_query("update companies set $upload_type='".$newfilenamepath."' where CO_ID='".$company_name."'");
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="form1" id="form1">
<select name="company_name">
<option selected="selected" disabled="disabled">Please Select Name Of Company</option>
<?php
$company_lists = mysql_query("SELECT * FROM companies ORDER BY CO_ID DESC");
while ($row_com_list = mysql_fetch_array($company_lists)) {
echo "<option value='" . $row_com_list['CO_ID'] . "'>" . $row_com_list['company_name'] . "</option>";
}
echo "</select>";
?>
</select><BR /><BR />
<input name="file" type="file" size="20" /><BR /><BR />
<select name="upload_type" onchange="showfield(this.options[this.selectedIndex].value)">
<option selected="selected" disabled="disabled">Please Select Type Of Upload</option>
<option value="company_logo">Add A Logo</option>
<option value="company_logo_2">Add Second Logo</option>
<option value="company_logo_2">Add Third Logo</option>
<option value="company_sing_1">Add Sign For Manager 1</option>
<option value="company_sing_2">Add Sign For Manager 2</option>
<option value="company_sing_3">Add Sign For Manager 3</option>
</select><BR /><BR />
<div id="div1"></div></BR></BR>
<input name="submit" type="submit" value="Upload" />
</form>
What is the problem and what can we do?
edit:
when I fill the form and echo it and break at the first if I get this:
echo $upload_type;
echo "//////";
echo $company_sign_name_1;
echo "//////";
echo $company_sign_name_p_1;
echo "//////";
echo $newfilenamepath;
echo "//////";
echo $company_name;
break;
company_sing_1//////Abdulrahman Nahhas//////General Manager//////uploads/9-20140920-0494829001411172658.png//////2
this mean it take the form but not send the values to mysql I test the echo in the second elseif it gives me nothing.
your $upload_type is company_sing_1 etc instead of company_sign_1 etc. You have no fields in your db named company_sing_1 etc... Fix the naming and you'll fix your problem.

Add form fields dynamically with php

Referring to this post. Add form fields dynamically populated dropdown list with php I have used his code but will modify it to fit my needs since I pretty much nothing about javascript. I have everything working except when you press the + button it never creates more input boxes. Any help would be great.
This my php file
<?php
session_start();
require_once("dbconfig.php");
?>
<html>
<head>
<script type="text/javascript" src="addfish.js"></script>
</head>
<form id="form1" name="form1" method="post" action="results.php">
<div id="itemRows">
<select name="species">
<option value="">Select Species</option>';
<?php $stmt = $dbc->prepare("SELECT species FROM fish");
$stmt->execute();
while($speciesq = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<option value=\"" . $speciesq['species'] ."\">" . $speciesq['species'] ."</option>";
}
?>
</select>
Number: <input type="text" name="speciesnumber1" size="7" /> Weight: <input type="text" name="speciesweight1" /> <input onClick="addRow(this.form);" type="button" value="+" />
</div></form>
</html>
My addfish.js file
var rowNum = 0;
var ddsel = '<select name="species'+rowNum+'>';
var ddopt = '<option value="">Select Species</option>';
var ddselc= '</select>';
;
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
var frm = document.getElementById('form1')
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.speciesnumber1.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.speciesweight.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}, "json");
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
This is my getlist.php
<?php
session_start();
include("dbconfig.php");
$stmt = $dbc->prepare("SELECT species FROM fish");
$stmt->execute();
$result = array();
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
$result[] = array(
'value' => $rows['species'],
);
}
echo json_encode($result);
?>
Your code is using jQuery, but I don't see where you include this library. Try to put this code before include addfish.js in header :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you need to add rows with this fields dynamically I suggest you make a row which is the original row:
<div class="rows" data-rows="1">
<div class="row row-first">
<select name="row[0][select_name]">
<option value="1">Some value</option>
</select>
<input type="text" name="row[0][text_name]" />
</div>
</div>
and the javascript
<script type="text/javascript">
$('#add_row').on('click', function(){
var row = $('.row-first').clone(); // Clone the first row
var rows = parseInt($('.rows').attr('data-rows'));
rows++;
$('.rows').attr('data-rows', rows);
row.removeClass('row-first'); // Prevent multiple rows cloning
$(row).find('[name]').each(function(){
var name = $(this).attr('name');
name = name.replace(/\[[0-9+]\]/, '[' + rows + ']');
$(this).attr('name', name);
$(this).val("").change(); // Null the select
});
$('.rows').append(row);
});
</script>
So what you do is clone the first row and remove the class, which you search. Increment the rows count and replace all names in you row with the new row number e.g. row[0][name] becomes row[1][name], and append the row.
Also when you edit the rows you MUST put set the data-rows to the exact number. You can do it like count($myRows). And when you write the remove row function DO NOT REMOVE the first row.
Hope it hepls.
// You can use this
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);

Categories