Forgive me if this question is naive. I'm new to JavaScript and am learning my way through some setbacks with a form I'm using to display data.
An icao code is passed to the #depicao <select> menu via $_GET['icao'] in the JavaScript code at the bottom of the script. On page load, the <select> menu is populated with the $_GET['icao'] value.
After the #depicao <select> menu is populated, I'd like the form to automatically submit itself with its populated value. My train of thought is that if I include
document.getElementById("form").submit();
as the last line in the script, I can get the script to submit itself after it loads with the $_GET['icao'] value. Unfortunately, this hasn't been working, however.
NOTICE: The code contains multiple <input type="submit" name="submit"> buttons. I believe that this is the culprit.
See code below.
<form id="form" action="<?php echo actionurl('/schedules/view');?>" method="post">
<div id="tabcontainer">
<ul>
<li><span>Via departure airport</span></li>
<li><span>Via arrival airport</span></li>
</ul>
<div id="depapttab">
<select id="depicao" name="depicao">
<option value="">Select All</option>
<?php
$exclude = array(13, 18, 19, 22); // Airport IDs found in phpVMS_airports not to be included in the dropdown menu
if(!$depairports) $depairports = array();
foreach($depairports as $airport) {
if(!in_array($airport->id, $exclude)) { // Exclude values in the above array from the dropdown menu
echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
}
}
?>
</select>
<input type="submit" name="submit" value="Find Flights" />
</div>
<div id="arrapttab">
<select id="arricao" name="arricao">
<option value="">Select All</option>
<?php
$exclude = array(13, 18, 19, 22); // Airport IDs found in phpVMS_airports not to be included in the dropdown menu
if(!$depairports) $depairports = array();
foreach($depairports as $airport) {
if(!in_array($airport->id, $exclude)) { // Exclude values in the above array from the dropdown menu
echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
}
}
?>
</select>
<input type="submit" name="submit" value="Find Flights" />
</div>
</div>
<input type="hidden" name="action" value="findflight" />
</form>
<script type="text/javascript">
function formReset() {
document.getElementById("form").reset();
}
function setSelectedIndex(s, valsearch) {
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++) {
if (s.options[i].value == valsearch) {
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
setSelectedIndex(document.getElementById("depicao"),"<?php if(isset($_GET['icao'])) { echo $_GET['icao']; } else { echo 'Select All'; } ?>");
document.getElementById("form").submit();
</script>
Form Auto Submission Confusion ?:
After the #depicao menu is populated, I'd like the form to automatically submit itself with its populated value.
How I understood you was that you want the form to be submitted automatically when the select menu is populated ? I think you meant when the user chooses a selection, it should submit automatically. If this is what you mean. Please add a onchange="//submitfunction()" onto the <select> tag
Related
I have a dropdown that is disabled to the user. I want for the user to be able to press a button that changes the selected item to a different one. For example: from the 4th item in the dropdown to the 7th.
I've tried disabling the dropdown, but when I do that and submit the form, I get a PHP error saying Undefined index: id.
HTML:
<form>
<select id='id' name='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<button type='submit'>Submit</button>
</form>
JavaScript:
const dropdown = document.getElementById('dropdown');
const options = dropdown.options;
for (let i = 0; i < options.length; ++i) {
if (options[i].value === id) {
dropdown.selectedIndex = i;
break;
}
}
PHP (This line seems to be the one breaking):
$id = $_POST['id'];
It seems you haven't defined method and action in your form tag. By default, I think, the method is set to 'GET', so when checking 'POST' you'll run into your error.
Therefore, set "method='post'" (and best also an action, e.g. "action='/yourPageName.php') and see if that helps.
I figured out a solution that suits my needs. It was kind of simple. I just enabled the dropdown when I submitted the form, and instantly disabled it again.
id.removeAttribute('disabled');
const data = new FormData(document.getElementById('form'));
id.setAttribute('disabled', '');
request.send(data);
Thanks for the help though :)
A disabled input field will be ignored when you submit the form. I would suggest creating a hidden input field of name="id" if you want the user to view the dropdown but not select it.
<form>
<select id='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<input type="hidden" name='id' value="6" />
<button type='submit'>Submit</button>
</form>
You can make an hidden input with the id="id" and change the select id to "temp_id". Then, since you are making the request from javascript, you can just update the hidden field before making the request.
<select id='temp_id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10>orange</option>
</select>
<input type="hidden" name="id" id="id" value="">
Then, on your javascript, just before you make the request, run the code:
document.getElementById("id").value = document.getElementById("temp_id").value;
Okay it seems the original request was confusing so let me try re-wording. I have a form, see below code, with two Selects, users move things from the Available Locations list (One) to the Selected Locations list (Two) and input some other fields (I included one text field as an example), I need to be able to see what values are in the first select (One) and which are in the second list (Two)
There will be a large number of values so having the user just click or ctrl+click on the values they want isnt practical.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test for P1727410</title>
<script src="/ref-files/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').click(function () {
moveItems('#Two', '#One');
});
$('#right').on('click', function () {
moveItems('#One', '#Two');
});
$('#leftall').on('click', function () {
moveAllItems('#Two', '#One');
});
$('#rightall').on('click', function () {
moveAllItems('#One', '#Two');
});
});
</script>
</head>
<body>
<h2>Test for P1727410</h2>
Available Locations | Selected Locations
<form method="POST" action="#">
<select id="One" name="One" multiple="multiple">
<option value="1">Loc1</option>
<option value="2">Loc2</option>
<option value="3">Loc3</option>
</select>
<select id="Two" name="Two" multiple="multiple">
</select>
<br />
<input type="text" name="something" /><br />
<input type="hidden" name="form" value="1" />
<input type="button" id="leftall" value="<<" />
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="rightall" value=">>" />
<br />
<input type="Submit" name="Submit" value="Submit" />
</form>
<p>
<?php
if(isset($_POST['form'])) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
}
?>
</p>
</body>
</html>
This question is confusing because we're not sure what you exactly want to show on the front-end (HTML + Javascript), what do you want to send to the back-end (PHP), and what do you want to insert/update/delete in the database.
The simplest solution I think of is the following:
You should have 3 tables in your database: users, locations, and user_locations. The user_locations should have at least 2 columns: "user_id" and "location_id".
HTML: Add a new html input hidden:
<input type="hidden" id="two_values" name="two_values" value="" />
Javascript: When user clicks submit button, take all values of the 2nd dropdown, and send them to the server. Like so:
<script>
$(document).ready(function() {
// on user clicks submit button, this code will be executed first
$('form').submit(function() {
// we'll take all values of the Two dropdown and put them in 1 string
var all_values = '';
$("#Two option").each(function() {
if(all_values === '') {
all_values += $(this).val();
} else {
all_values += ',' + $(this).val();
}
});
$('#two_values').val(all_values);
});
});
</script>
PHP: Get the two_values, and split them to array.
if(isset($_POST['form'])) {
$two_values_arr = explode(',', $_POST['two_values']);
// ...
}
PHP and MySQL: First, delete all previous user's locations:
$q = 'DELETE FROM `locations` WHERE `user_id` = ' . $user_id;
// run the $q ..
Then, do a loop to insert each value for this user
foreach($two_values_arr as $location_id) {
$q = 'INSERT INTO `user_locations` (user_id, location_id) VALUES (' . $user_id . ', ' . $location_id . ')';
// run the $q ..
}
Viewing HTML: When user views the page, you should fetch all user's locations, locations the user have should be printed to the Two dropdown, and ones he doesn't have in the One dropdown
I have dropdown list of items and a popup (used colorbox for opening popup) with a list of checkboxes. The popup is shown on click of '+Add/Edit'. Both the dropdown items and the checkboxes are generated in PHP from a complaint.csv file.
complaint.csv file
1,complaint type 1
2,complaint type 2
3,complaint type 3
etc...
PHP code
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Chief Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<select name="Language.PrimarySpoken" ng-hide="showAddAnswer"
ng-model="question.response.value"
ng-options="a.text as a.getText() for a in question.answers.items"
id="Language.PrimarySpoken" ng-value="a.text" class="input-wide"
ng-class="{error:hasError()}">
<option class="hidden" disabled="disabled" value=""></option>
<?php
$file_handle = fopen("../complaint.csv", "r");
while (!feof($file_handle)) {
$lines_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
foreach ( $lines_of_text as $line_of_text):
?>
<option value="<?php print $line_of_text[1]; ?>">
<?php print $line_of_text[1]; ?></option>
<?php endforeach; ?>
</select>
<br/> <br/>
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Additional Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<div class="form-row added ng-binding" ng-bind-html="question.getText()" id="text" ></div>
<div class="form-row addlink ng-binding"
ng-bind-html="question.getText()">
<em><a class='inline' href="#inline_content">+ Add/Edit</a></em>
</div>
<div style='display:none'>
<div id='inline_content' style='padding:25px; background:#fff; font-size: 17px;'>
<form action="" id="popup_form">
<?php
// Setup ---------------------------------------------------------------
define('numcols',4); // set the number of columns here
$csv = array_map('str_getcsv', file('../complaint.csv'));
$numcsv = count($csv);
$linespercol = floor($numcsv / numcols);
$remainder = ($numcsv % numcols);
// Setup ---------------------------------------------------------------
// The n-column table --------------------------------------------------
echo '<div class="table">'.PHP_EOL;
echo ' <div class="column">'.PHP_EOL;
$lines = 0;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
foreach($csv as $item) {
$lines++;
if ($lines>$lpc) {
echo ' </div>' . PHP_EOL . '<div class="column">'.PHP_EOL;
$lines = 1;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
}
echo ' <label class="checkbox" for="checkbox'.$item[0].'" style="font-size:20px;">
<input type="checkbox" name="complaint" value="'.$item[1].'" id="checkbox'.$item[0].'" data-toggle="checkbox">'
.$item[1].
'</label><br />';
}
echo ' </div>'.PHP_EOL;
echo '</div>'.PHP_EOL;
// The n-column table --------------------------------------------------
?>
<br/>
<input type="submit" name="submit" id="update"
class="button button-orange"
style="width: 90px; margin-top: 450px; margin-left:-1062px;"
value="Update">
<input type="submit" name="cancel" id="cancel"
class="button button-orange"
style="width: 90px; background-color:#36606e;"
value="Cancel">
</form>
</div>
</div>
Question:
If a Main complaint item is select then that same complaint does not appear in Additional Complaint list (i.e. if 'complaint type 1' is selected for Main complaint, 'complaint type 1' does not display on Additional Complaint list)
How should I get that using one complaint.csv file like checking for the selected item, and avoid it when displaying the list e.g on select 'complaint type 1', the data from complaint.csv file will be display on popup checkbox list except 'complaint type 1' which is selected?
There is empty space generating if we remove the element. I don't want the empty space of removed item in checkbox list. Empty space means if 'complaint type 2' is removed then there empty space creates between 'complaint type 1' and 'complaint type 3'.
Is there any way to have AJAX for this situation like when the item is selected AJAX will call and it will remove the item from the checkbox list which is selected and then load the new items list except the selected one. (right now both list are loading at a same time on page load insted of that using AJAX the dropdown list should load on page load and checkbox list on click '+Add/Edit' button avoiding selected item.) Thus might be the empty space will not be there.
How this should be done using AJAX?
OR
Can anyone please suggest any solution with PHP or JS to get both requirements?
In your code, make sure the select dropdown value is $line_of_text[0] e.g. 1, 2, 3 etc.
Now add onChange="hideSpaceAndComplain(this.value)" on the select element.
Copy the following javascript function as is
function hideSpaceAndComplain(id){
//Hide selected one
$("#popup_form").find('label').show();
//Hide selected one
$('input[value=' + id + ']').parents('label').hide();
//Now rearrange all the visible label in columns
var visibleLabels = $("#popup_form").find('label:visible');
visibleLabels.each(function(i,v){
var column = Math.floor(i/4); // 4 being the number of column
$(this).appendTo($("#popup_form").find('.column:eq('+column+')'));
});
}
This is doing both hiding the element which is selected and then re arranging the labels in column to remove one extra space.
Since the logic you describe depends on what the user does in the browser, what you functionality does must be done in the browser, that means in Javascript.
According to the tags of the question you are using JQuery, so here are some pointers on how to do it with JQuery. First you have to attach an event handler to the dropdown to know when the user changes its value:
$('select').on('change', function() {
//Put here what to do when the value of the dropdown changes.
}
In that function, you want to do two things:
Un-hide the complaint that you may have hidden previously
Hide the main complaint
To do so, write something like this in the event handler:
//Un-hide everything
$('label').show();
//Hide selected one
$('input[value=' + $(this).val() + ']').parent().hide();
You can see a working example in this JSFiddle.
Hope this helps.
Note that I see in your code that you uses Angular, so you may want to use this instead. But I am not sure why you generate the select options both with Angular and PHP, so I am assuming this is some copy-pasted code that you are not using.
I have a html form and a dropdown list like this:
<form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<div>
<span>Select Event</span>
<select id = "events" onchange="run()" class = "pass" style="width: 209px">
<?php while($row = oci_fetch_array($curs)):?>
<option value="<?php echo $row[0];?>"><?php echo $row[1];?></option>
<? endwhile; ?>
<input type="submit" name="action" value="New Event">
</select>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select"><br>
</div>
</form>
I can successfully show the values that I take from the database table. And after that I want to use the selected value for another query which needs this selected value simultaneously without pressing submit button.And my run function is like:
<script>
function run() {
document.getElementById("srt").value = document.getElementById("events").value;
}
How can I assign this selected value to a php variable simultaneously?
`
It is not possible.
PHP script will never execute on onchange event.
Don't confuse it with JavaScript.
PHP scripts will only run on events like GET, POST, etc.
I have a list, (a simple list) from which i am able to select and set elements (using js), and then a form that allows me to choose how many elements i want, and a submit form.if one doesn't select an element, there is a script that throws an exception. The problem is that i want that the form doesn't submit, if an element is not selected, but not throw an exception, but to show me a message down the submit button (using jquery). my script below:
<? foreach ($types as $type):?>
<ul class = "product_types">
<? if ($type->stock_2 > 0):?>
<li id = 'product_types'><a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?></a></li>
<? else: ?>
<li id = 'product_unavailable_types'><label><?= $type->label; ?></label></li>
<? endif; ?>
</ul>
<? endforeach; ?>
<form name="addtobasket" method="POST" action="<?= Route::url('Add to Basket', array('sale_id' => $sale->id)); ?>">
<input type="hidden" name="idOfSelectedItem" id="idOfSelectedItem" value="-1">
<select name="number" id="number">
<option value=0>Alege numarul de produse</option> </select>
<button type="submit" name = "submit" onclick="addtobasket";>Adauga in cos</button><br />
</form>
and the js that sets the list elements:
<script type="text/javascript">
function selecteazaElement(id,stock)
{
document.addtobasket.idOfSelectedItem.value=id;
window["canSubmit"] = true;
var number23=document.addtobasket.number;
number23.options.length=0;
if (stock>=6)
stock=6;
for (i=1;i<=stock;i++)
{
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
//window.status="my status";
}
Add a submit listener to the form. When it's submitted, check to see if an element is selected, and if not you can prevent the submission by using return false. Here's an example:
$('#myForm').submit(function()
{
if (/* test case not true */) {
$('#myError').show();
return false;
}
// ... continue work
});
And here's the HTML:
<form id="myForm">
<input type="text"/>
<input type="submit"/>
</form>
If you don't want to use jQuery, you can also handle the submit event with plain JavaScript like so:
var myform = document.getElementById('myForm');
myform.addEventListener('submit', function() { console.log('Submitted!'); return false; });