Display results of Dropdown in Text fields - javascript

Am hoping to ask another question here since the main one was answered on this thread:
How fill form data from Dropdown?
Though its abit of a continuation.
I am attempting to use javascript and an onChange() function to scroll through the files and then display them in the text input and text area fields on the form however I would appreciate any help in resolving my javascript. As it stands right now I can pull the file into the dropdown menu, but when I select one from the dropdown menu, nothing happens or populates on the form.
edited to update All errors seem to be resolved however nothing gets moved into the text boxes when selecting a file from the dropdown menu.
Javascript:
<script>
function CodeChange() {
var filesContentJS = "$filesContents"
var index = filesContentJS.selectedIndex;
var e = document.getElementById("CodeList");
var strUser = e.options[e.selectedIndex].value;
strUser = "0";
integer document.getElementById("CodeId").value = 0;
document.getElementById("CodeName").value = "";
document.getElementById("CodeValue").value = "";
}
</script>
updated javascript
And the form html and php itself for reference:
<input type="hidden" name="Action" value="EDIT" /><input type="hidden" name="Selection" id="Selection" value="-1"><div>Below is the list of your saved codes. To edit your codes, select it from the list.</div>
<select size="1" name="CodeList" id="CodeList" onchange="CodeChange();"><option value="0">(Add New Code)</option>
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file )
{
if ( ! is_dir( $file ) )
{
$filesContents[$file] = file_get_contents($directory , $file);
echo "<option>" . $file . "</option>";
}
}
?>
</select>
<h3>Saved Codes</h3>
<form method="post" action="/evo/avsaveprocess.php">
<input type="hidden" name="Action" value="SAVE" />
<input type="hidden" name="CodeId" id="CodeId" value="0" />
<table width="100%" border="0">
<tr>
<td>Description:</td>
<td><input type="text" name="CodeDescription" size="40" maxlength="50" id="CodeName" value="" /></td>
</tr>
<tr>
<td valign="top">Code:</td>
<td>
<textarea rows="10" style="width:99%" name="Code" id="CodeValue"></textarea>
</td>
</tr>
</table>
<input type="submit" value="Save" />
</form>

Your PHP array is still an array. You have to convert it to JS.
So, after you did all the $filesContents[$file] = file_get_contents($directory , $file);, then you need JS:
<script>
var filesContentJS = <?=json_encode($filesContents) ?>;
function CodeChange() {
var e = document.getElementById("CodeList"); // getting dropdown element
if (e.selectedIndex<=0) { // nothing selected - clean form
document.getElementById("CodeId").value = 0;
document.getElementById("CodeName").value = "";
document.getElementById("CodeValue").value = "";
} else {
var eStr = e.options[e.selectedIndex].value; // getting current element value
// fill the form with data
document.getElementById("CodeId").value = 0;// not sure what CodeId is - but this is the place to fill it
document.getElementById("CodeName").value = eStr;
document.getElementById("CodeValue").value = filesContentJS[eStr];
}
</script>

Try with
var e = document.getElementById("CodeList");
var strUser = e.options[e.selectedIndex].value;

Related

How to make sure form cannot be submitted if text field is empty when user selects False Hit radio button?

I am doing something to prevent user from submitting HTML Form without leaving their remarks for False Hits.
Conditions:
Only if False Hit radio button is selected
The remarks text field cannot be empty (Compulsory)
Currently, I have used JavaScript to check if the text field (Remarks) is empty.
function empty() {
var x;
x = document.getElementById("roll-input").value;
if (x == "") {
alert("Please enter remarks for false hits selected.");
return false;
};
I am also able to check which radio button is selected with JavaScript.
<input type="radio" name="select" id="truehit" value="true" />
<input type="radio" name="select" id="falsehit" value="false" />
if(document.getElementById('falsehit').checked) {
//False Hit radio button is checked
}
else if(document.getElementById('truehit').checked) {
//True Hit radio button is checked
}
However, I am quite stuck at linking both conditions together. Is there a simpler method to this? Any help is greatly appreciated. Thank you in advance.
This is how my Form looks like.
<body bgcolor="#FFFFFF">
<br />
<div align="center" class="h1">
<h1>Entity Search</h1><br />
</div>
</html>
<br />
<?php
include("db_connect.php"); //connect to database
#$loginid = strtoupper(base64_decode($_POST['LanID'])); //to capture
the user's LanID as the UserID
if($loginid == "")
{
$userID = $_SESSION['loginid'];
}
else
{
$_SESSION['loginid'] = $loginid;
$userID = $_SESSION['loginid'];
}
$userID = $_SESSION['loginid'];
//to insert date and time of the records
date_default_timezone_set('Asia/Singapore');
$Date = date('Y-m-d');
$Time = date ('h:i:s a');
$userID = $_SESSION['loginid'];
$loginid = "";
$entityfromform = $_GET["entity"];
?>
<br />
<?php
//connection to database
$connectionInfo = array( "Database"=>"test","UID"=>$test,"PWD"=>$test);
$db_connect=sqlsrv_connect($serverName, $connectionInfo);
//to retrieve the department name from the user database and insert
department name of the user into the records
$namesql = "SELECT Name, DeptName, Role FROM RPDB.dbo.Userdb WHERE
LanID='$userID';";
$name_query = sqlsrv_query($db_connect,$namesql);
while($row = sqlsrv_fetch_array($name_query, SQLSRV_FETCH_ASSOC))
{
$nameontop = iconv("gb2312","UTF-8",$row['Name']);
$admincheck = iconv("gb2312","UTF-8",$row["Role"]);
$deptnamecheck = iconv("gb2312","UTF-8",$row["DeptName"]);
}
$negative = "Negative Hit: No results found.<br />";
$result = "$entityfromform <br />Negative Hit: No results found.<br />";
//variable to insert into the table as result
//search for keyword from form in the Entity Table List where Name =
keyword
$entitysql = "SELECT * FROM RPDB.dbo.entitysearch_table WHERE Name LIKE
'%" . $entityfromform . "%' OR Name = '".$entityfromform."'";
$entity_query = sqlsrv_query($db_connect,$entitysql);
//variables
$i=0;
while($row = sqlsrv_fetch_array($entity_query, SQLSRV_FETCH_ASSOC))
{
$name[$i] = $row["Name"];
$brn[$i] = $row["Business_Registration_Number"];
$address[$i] = $row["Registered_Address"];
$group[$i] = $row["Applicable_Limb_of_Related_Party_Group"];
$selectradio[$i] = 'selectradio'.$i;
$text[$i] = 'text'.$i;
$i++;
}
if(#$name != NULL) //Positive Result
{
echo "<input type='button' name=uncheck' value='Uncheck All'
class='uncheck' onClick='window.location.reload()'>"; //uncheck all
function where it clears all changes
echo "<h2><div align='center'>Results found for:
$entityfromform</div></h2><br />";
//table to display the data
echo "<div align='center'>
<table>
<tr>
<th>Name</th>
<th>Business Registration Number</th>
<th>Registered Address</th>
<th>Applicable Limb of Related Party Group</th>
<th>True Hit</th>
<th>False Hit</th>
<th>Unable To Ascertain</th>
<th>Remarks, for false hit</th>
</tr>
</div>";
echo "<strong><div class='wording'>Positive Hit: </div></strong>";
echo "<br /><br />";
$x=0;
?>
<!--The form data is sent for processing to action_handler.php by HTTP POST method-->
<form method="post" id="form" action="action_handler.php" enctype="multipart/form-data">
<?php
//data displayed in tables along with checkboxes for true hit, false hit, unable to ascertain and text box for remarks where applicable
for($x=0;$x<$i;$x++)
{
echo "<tr>
<td>" . $name[$x] . "</td>
<td>". $brn[$x] . "</td>
<td>". $address[$x] . "</td>
<td>". $group[$x] . "</td>
<td>
<label class='container'>
<input type='radio' id='truehit' name='".$selectradio[$x]."' value='true hit' class='btn' required>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='falsehit' name='".$selectradio[$x]."' value='false hit' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='unabletoascertain' name='".$selectradio[$x]."' value='unabletoascertain' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label><input type='text' name='".$text[$x]."'>
</label>
</td>
</tr>" ;
}
echo "</table>"; //table closed
echo "<br /><br /><br />";
echo "<input type='button' value='Submit' class='submit' onClick='empty()'>"; //submit button to confirm
?>
</form>
<?php
//sessions to be used in others
$_SESSION['num'] = $x;
$_SESSION['entityfromform'] = $entityfromform;
}
else
{
echo "<div align='center'><h2>Results found for: $entityfromform</h2>
<br />";
echo "<div class='wording' align='center'>$negative</div><br><br>
<br>";
}
?>
</table>
</body>
your empty() function does not return anything if the textbox has a value and hence for that condition it is undefined; you can create a function for your requirement like:
function doSubmit()
{
if(document.getElementById('falsehit').checked)
{
if(document.getElementById("roll-input").value == '')
{
alert("Please enter remarks for false hits selected.");
return false;
}
}
return true;
}
and call this method to validate, so if falsehit is checked and remarks has a value it'll return true or else false.
Hope this helps; let me know if I'm missing to understand your problem here..
Happy coding...
You can use a set of if statements like below. This basically checks if the falsehit radio button is checked. If it is, then it checks if the text is empty. If the text is empty, it alerts what you wanted it to. If the text isn't empty, it submit's the form.
Also, if falsehit is not checked, it automatically submit's the form.
As per request in the comments: Now I get every radio button, and loop through them to check if they're selected. If they aren't, you get an alert message saying Please select all accordingly. Otherwise, it just works the same as before.
function empty() {
var text;
var groups = document.querySelectorAll("[id^=group]");
var selected = {};
var radioButtons;
var submitForm = true;
groups.forEach(e1 => {
radioButtons = e1.querySelectorAll("input[type=radio]");
radioButtons.forEach(e2 => {
if (e2.checked) {
selected[e1.id] = true;
}
});
if (selected[e1.id] == undefined) {
selected[e1.id] = false;
}
});
groups.forEach(e => {
text = e.children[0].value;
for (var i = 0; i < e.children.length; i++) {
if (e.children[i].id == "falsehit") {
if (e.children[i].checked) {
if (text.length == 0) {
alert("Please enter remarks for false hits selected.");
submitForm = false;
}
} else if (selected[e.id]) {
//Don't need to do anything. Just need to prevent the next else from accessing these values
} else {
alert("Please select all accordingly.");
submitForm = false;
}
}
}
});
if (submitForm) {
document.getElementById("form").submit();
}
}
<form id="form">
<fieldset id="group1">
<input type="text" id="roll-input" />
<input type="radio" name="group1" id="truehit" value="true" />
<input type="radio" name="group1" id="falsehit" value="false" />
</fieldset>
<fieldset id="group2">
<input type="text" id="roll-input" />
<input type="radio" name="group2" id="truehit" value="true" />
<input type="radio" name="group2" id="falsehit" value="false" />
</fieldset>
<input type="button" value="Submit" onclick="empty()" />
</form>

Add form fields dynamically populated dropdown list with php

I'm trying to make 3 form fields (a dropdown list dynamically populated by a .php script and 2 text fields) and also with a button add 3 more and 3 more and so on (as user clicks the button) I have tried several ways but nothing seems to work for me. (I'm noob in JS, AJAX, jQuery so I mostly tried scripts I've found on the internet).
Here's the code of these form fields:
<form id="form1" name="form1" method="post" action="results.php">
<div id="itemRows">
<select name="species">
<option value="">Select Species</option>';
<?php $sql = "SELECT common FROM species";
$speciesq = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($speciesq))
{
echo "<option value=\"" . $row['common'] ."\">" . $row['common'] ."</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>
and after this form there's the code:
<script type="text/javascript">
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) {
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
}, "json");
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
getlist.php is a simple script that populates the dropdown list and sends the data:
<?php
include("dbcon.php");
$sql = mysqli_query ($con, "SELECT common FROM species");
$result = array();
while ($row = mysqli_fetch_array($sql)){
$result[] = array(
'value' => $row['common'],
);
}
echo json_encode($result);
?>
So when I click the "+" button (to add the row) nothing happens.
SOLVED: for those who come here please read also the comments below the answer.
You just have some code in the wrong spot:
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
needs to be moved into the post return function like this:
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.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}, "json");
}

Checking multiple files

I currently have a file element, and a button that allows a user to add more file elements so that if they wanted to, they could select multiple at once. I want to be able to loop through them and need some assistance as to what direction I should take or if there is a correct syntax to do this. Form, php, and JS code below.
Form:
<form action="<?php echo htmlspecialchars($_SERVER['PHP']);?>" method="post" enctype="multipart/form-data" name="upload_form" id="upload_form">
<br />
<input type="file" name="file[]" id="file"/>
<input id="addbutton" type="button" onclick = 'javascript: add()' value="ADD ANOTHER FILE" />
<br />
<input type="submit" id="submit" name="submit" value="SUBMIT" />
</form>
PHP:
if($_POST['submit'] == "SUBMIT")
{
$count = count($_FILES[ "file" ][ "tmp_name" ]);
echo $count;
for($i = 0; $i < $count; ++$i)
{
if($_FILES && $_FILES['file']['name'])
{
//code that does some stuff here
}
}
}
JS:
<script>
function add()
{
var form = document.getElementById("upload_form");
var addButton = document.getElementById('addbutton');
var br = document.createElement("br");
form.insertBefore(br, addButton);
form = document.getElementById("upload_form");
input = document.createElement("input");
input.type="file";
input.name="file[]";
form.insertBefore(input, addButton);
}
every thing is looks ok, u just need to add index to access particully uploaded file like
<?php
// ...
for($i = 0; $i < $count; ++$i)
{
echo $_FILES['file']['tmp_name'][$i];
// ...
Looks perfect, but you can just use this for multiple selection:
<input type="file" name="file[]" id="file" multiple="multiple" />
You won't need that javascript...

passing a javascript variable into a hidden form in codeigniter

I have a page in Codeigniter in which i can set the product quantity (sq.m) that the client wants to buy. When the client sets the quantity i have to do some calculations (about the quantity number whis was set before) and i am doing that with Javascript setting some variables. Now i want to show these variables in the same (php) page and it's working, but i don't know what should i do to put these variables in the values of the hidden inputs so that i can send them to the controller. Here is the coding:
<input type="text" name="productQuantity">
<input type="button" class="button" onclick="return showHide();" value="Calculate Packs">
<script type="text/javascript" language="javascript">// <![CDATA[
function showHide() {
var ele = document.getElementById("showHideDiv");
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
<?php $pack = explode(' ', $pro->productPackSize); ?>
ele.style.display = "block";
var val = document.getElementById('productQuantity').value;
document.getElementById('val').innerHTML = val;
var req = Math.round(val/<?php echo $pack[0]; ?>);
document.getElementById('req').innerHTML = req;
var total = req * <?php echo $pack[0]; ?>;
document.getElementById('total').innerHTML = total;
}
}
// ]]></script>
<div id="showHideDiv" style="display:none;">
<?php echo form_open('main/add_to_cart_validation/' . $pro->productId); ?>
To cover <strong id="val"></strong> sq.m, you will need <strong id="req"></strong> Packs
which is <strong id="total"></strong> sq.m in total</a> //the ids' here are working, i can show them in the page
<input type="hidden" id="" value="" name="productPacks"> //how can i get the 'reg' variable here?
<input type="hidden" id="" value="" name="productQuantity"> //the same here as above for 'total' variable
<input type="submit" class="button" value="Add to Cart">
</form>
</div>
Thanks for your answers
Add these lines in the else condition after your math:
document.getElementById("productPacks").value = val;
document.getElementById("productQuantity").value = total;
Starty by giving your inputs an id and then you can pass the values like this :
document.getElementById('myField').value = total;
It is very simple.You do it the same way.
var MyHiddenValue = document.getElementById('myHiddenField').value;
alert(MyHiddenValue);
WORKING FIDDLE

How to button enable when all textbox has value in jQuery?

I am new in programming. Here I have given description of my problem
I have one pair of two text box. One text box is for URL and other is for instruction but all text-boxes created dynamically depending on what value comes from database.
For example $testing_type_id=2 so I get total two pair of text boxes, let it called bundle. $i is used to identify textbox uniquely.
<input type = "text" size="33" class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
<input type = "text" class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" /> <br/>
<input type="submit" name="checkout" id="checkout" class="graybtn1 ptr button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />
Here what I wanted to do that if all bundle has value, either in one textbox or both textbox so and so enable submit button. If I removed value so disable submit button using jQuery.
I think this will work
$(document).ready(function(){
$("input[class^='uploadtxt']").keyup(function(e){
var alltxt=$("input[class^='uploadtxt']").length;
var empty=true;
$("input[class^='uploadtxt']").each(function(i){
if($(this).val()=='')
{
empty=true;
$('#checkout').prop('disabled', true);
return false;
}
else
{
empty=false;
}
});
if(!empty) $('#checkout').prop('disabled', false);
});
});​
An example is here.
if($('.uploadtxt1').val() !='' && $('.uploadtxt2').val() !='')
{
$('#checkout').hide();
}
else
{
$('#checkout').show();
}
So assuming you want to show/ enable the button if the textareas / inputs have values. You could do something like this using jQuery.
$(window).ready(function(){
if( $('input, textarea').val().length >=0 ){
//run function to enable button
}
else if ( $('input, textarea').val().length <=0 ){
//run function to disable button
}
});
I think this is what you are sort of looking for. Let me know if I am way off or not understanding you correctly.
I am going to suggest a minor markup changes so that will be easy to handle the traversing.
Wrap the elements in a <div>
<div class="item">
<input type = "text" size="33" class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
<input type = "text" class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" /> <br/>
<input type="submit" name="checkout" id="checkout" class="graybtn1 ptr button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />
</div>
Then, Attach a snippet on the change event
$("input[type=text]", $(".item")).change(function() {
var allField = true;
$(this).closest(".item").find("input[type=text]").each(function() {
allField = allField && ($(this).val().length > 0)
});
if(allField) {
$(this).closest(".item").find("input[type=submit]").prop('disabled', false);
}
});
Demo of Working Solution

Categories

Resources