javascript onchange with 2 different dropdown lists - javascript

Im pretty new with javascript programming.
I have some .php code, where 2 dropdown lists (in the same FORM) are populated by 2 different mysqli queries, this works without any problem.
Im trying to get javascript to handle the selected parts of the dropdown lists, with onchange, this works for only one dropdown list, and i cant really figure out how to get around this one.
This is the code that works with one dropdown menu, and it updates automaticly the page without submitting:
$chosen_location = $_GET['Lid'];
$chosen_car = $_GET['Cid'];
?>
<script type="text/javascript">
function changeDropDown(dropdown){
var location = dropdown.options[dropdown.selectedIndex].value;
*var car = dropdown.options[dropdown.selectedIndex].value;*
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
Part of the .php code:
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<option value = <?php echo ($location_id) ?> selected><?php echo ($location_name) ?></option>
<select size="1" name="form_car" id="form_car" onchange='changeDropDown(this);'>
<option value = <?php echo ($car_type_id) ?>><?php echo "" . ($car_class) . " - " . ($car_manufacturer) . " - " . ($car) . "" ?></option>
The italic marked I know will not catch the correct value, but this is where im at right now...
How is it possible to get an action URL with both selected values ? as this is going to be used in a mysqli query to show data from the actual selection
Thanks in advance... :)

Currently, you are submitting the form through JavaScript. If the selects are inside the form, their values will automatically be submitted when you submit the form. You don't even have to change the action of the form.
So, you can just generate a normal form (including submit button, if you will), and it will work. Then, add a little JavaScript sauce to make it submit automatically.
The code below does just that. JavaScripts adds a class to the body. This is a way to easily change styling based on JavaScript being enabled or not. In this case, I use it to hide the submit button, which is only needed in a non-JavaScript situation.
Then, I bind the on change handler, not unlike yours, to submit the form when a value is selected. By giving the selects a proper name, their values will automatically be added as intended.
Note how the event handlers are bound through code. You don't have to hardcode any calls to JavaScript in the HTML, so you can keep the HTML clean and separate (readability!).
// Bind to load event of the window. Alternatively, put the script at the end of the document.
window.addEventListener("load", function() {
// Indicate that JavaScript works. You can use this to style the document, for instance
// hide the submit button, if the form is automatically submitted on change..
document.body.classList.add("js");
// With JavaScript, you can automatically submit the form, but you still don't have to modify it.
var theform = document.getElementById("theform");
var selects = document.querySelectorAll("#theform select");
for (var i = 0; i < selects.length; ++i) {
selects[i].addEventListener("change",
function() {
alert("submitting now");
theform.submit();
});
}
});
.js button[type="submit"] {
display: none;
}
<!-- Just a form with selects is enough. You don't even have to have JavaScript to post this. -->
<form id="theform" action="test.php" method="get">
<select name="Lid">
<option>Example...</option>
<option>Use PHP,</option>
<option>to fill these.</option>
</select>
<select name="Cid">....</select>
<button type="submit">Post</button>
</form>

You can update your code to following
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var elCar = document.getElementById('form_car');
var location = elLocation.options[elLocation.selectedIndex].value;
var car = elCar.options[elCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}

try to do this
<script>
// get select elements
var form_location_id = document.getElementById('form_location_id');
var form_car = document.getElementById('form_car');
// on change
form_location_id.addEventListener('change', changeDropDown1);
form_car.addEventListener('change', changeDropDown2);
</script>
And change the 'changeDropDown1' and 'changeDropDown2' to your handler function

try this
<script type="text/JavaScript">
var dropdownLocation = document.getElementById("form_location_id");
var dropdownCar = document.getElementById("form_car");
function changeDropDown() {
var location = dropdownLocation.options[dropdownLocation.selectedIndex].value;
var car = dropdownCar.options[dropdownCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
dropdownLocation et dropdownCar are outside the function to save time because this 2 vars need only to be set one time

Related

Problem with $_GET / $_POST when passing variable from Javascript popup to parent window to use in PHP MySQL query

The flow chart of my end goal is essential:
Click the "add" button in the parent window ---> Popup window showing a list to choose an item from.
The user clicks a row from the list & submits that item as an index/ID.
Popup / Child window closes and the variable is passed back to the parent window.
Parent window can use that variable in PHP to query the item ID in MySQL and add the data into a new row.
The parent window is also always open during this process, so I used window.onunload of the child window to trigger the SQL query.
First of all, I understand from similar posts that JS is client-side while PHP is server-side, so it's possible to get a PHP variable in JS using <? php echo ?>, but not the other way around, at least directly.
I used form.submit() to send the data back to the parent window via POST method through a form. However, isset($_POST['itemID'] turns up false, as the predefined value I set for $full_id is still 1.
Child Window
var txt = window.opener.document.getElementById("txtName");
txt.value = "1chosen";
var submit = window.opener.document.getElementById("submit");
submit.value = str;
document.getElementById('myID').value = str;
var form = document.getElementById('myForm');
form.submit();
window.close();
}
window.onunload = function (e) {
opener.somefunction(); //or
}
;
</script>
</body>
<form action="/combine-quote.php" id="myForm" method="get">
<input id="myID" name="itemID"><br><br>
<input type="submit" value="Submit">
</form>
Parent Window
window.somefunction = function(){
var choice = document.getElementById('txtName').value;
var id = document.getElementById('submit').value;
if (choice =="1chosen"){
if (id != ""){
<?php
$xd=1;
$full_id = "1";
if (isset($_GET['itemID'])){
$full_id=$_GET['itemID'];
}
?>
alert(<?php echo $full_id; ?>);
}

How to make divs which are created when a form is submitted, remain in place when the form is resubmitted

I am making a webpage where the user can use a form to search for a string and then divs will appear showing rows with matching info from a database. Then when a checkbox is clicked on a row it will move up to another div. I would like for the rows which have been selected via the checkbox to remain where they are when the form is resubmitted but still disappear when the checkbox is unclicked.
I have taken this video to show how it is currently working, which should hopefully make my question make sense.
https://imgur.com/a/DmkP0ut
This is the code for my form
<form action = "" method = "POST">
<div class = "searchcontainer">
<input id = "search" type="search" name = "search" class = "textbox" placeholder
= "Type the students name and press Enter to search...">
<input type = "submit" style="display:none" id = "submitsearch"/>
</div>
</form>
Then when the form is submitted this code will run to create the divs that appear (This is just a really short version, let me know if you need to see all of it)
<?php
if(isset($_POST['search'])){
$input = $_POST['search'];
$result = $conn->query("select * from logins");
let r<?php echo $studentid ?> = document.createElement("div");
r<?php echo $studentid ?>.id = "r<?php echo $studentid ?>";
r<?php echo $studentid ?>.className = "rowcontainer";
document.getElementById("tablecontainer").appendChild(r<?php echo $studentid ?
>);
Then this is the Javascript code which moves the rows to the 'selected' container when the checkbox is ticked and back to the 'tablecontainer' when unckecked.
<script>
const main = document.querySelector(".tablecontainer");
const selected = document.querySelector(".selected");
main.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("move")) {
const rowContainer = tgt.closest(".rowcontainer");
if (tgt.checked) {
selected.append(rowContainer);
}
}
})
selected.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("move")) {
const rowContainer = tgt.closest(".rowcontainer");
main.append(rowContainer)
}
})
</script>
From what I found online it looks like I will need to se session variables to keep the rows in place once they have been selected, but I dont really know how to do this, so help would be appreciated.
Thanks
Edit: I have a had a look through these answers but as a beginner they do not make much sense to me. I have found that I can use
var rowsselected = document.getElementById("selected").children;
to get a list of all the children divs in my selected div, so is there a way I can save this list so it persists when the form is resubmitted and take the children from this list and append them to selected again. If you could show examples that would be good. Also I should have mentioned this in the main post but I would also like to carry over info from the rows which have been selected to the next page so if I could make the ids of these rows into session variables or something like that that would be good.

pass JavaScript variable to HTML input box and (to use in PHP file)

I'm trying to pass a JavaScript variable to the value of an hidden input button to use in my PHP file output.
My HTML is:
<input type = "hidden" id = "location2" name = "location2" value = ""/>
I'm using this onclick="myFunction();" in my "Submit Form" input to run the function as it is not able to be done in the window.load()
My JavaScript below is calling indexes from another function and assigning the text to the variable 'location' (I know this sounds strange but it was the only way I have got it to work so far):
function myFunction() {
var x = document.getElementById("box2").selectedIndex;
var y = document.getElementById("box2").options;
var location=(y[x].text);
document.getElementById("location2").value=(location);
}
Any help would be hugely appreciated as I am really struggling and have been working on this for some time (as you can probably tell, I dont really know what I'm doing) - I just need to call the value of this variable into my PHP file output and the majority of my web form is completed.
Thanks very much
Marcus
I've just changed my HTML as follows
I've removed myFunction from my submit
I've added the following HTML button:
<button onclick="myFunction();" id = "location2" name = "location2" value="">Click me</button>
The variable is now passing!!!! The only problem is when I press the onclick button, it is now submitting my form!!
Is it okay for me to replace my previous submit button with this code??
THANKS TO EVERYONE FOR THEIR HELP ON THIS!!
I Was not sure what you doing but below example may help you. It will post the value as well as the option text.
Here we are using print_r to print the $_POST array from the AJAX Request. using this method, you should be able to debug the issue.
<!DOCTYPE html>
<html>
<body>
<?php if($_POST) {
print_r($_POST); die;
} ?>
<form name="" id="" method="post" >
Select a fruit and click the button:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<input type = "hidden" id = "location2" name = "location2" value = ""/>
<input type = "hidden" id = "locationname" name = "locationname" value = ""/>
<button type="submit" id="submit">Display index</button>
</form>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//alert("Index: " + y[x].index + " is " + y[x].text);
document.getElementById("location2").value=(y[x].index);
document.getElementById("locationname").value=(y[x].text);
//alert($("#location2").val());
}
var submit = document.getElementById('submit');
submit.onsubmit = function(e){
myFunction();
};
</script>
</body>
</html>
i'm assuming your form method is 'POST' and action value is the same php page where you are expecting to see the 'location2' hidden input value, if that is the case, you can use $_POST['location2'] to get the value in that php page.
Yes it is fine to use button tag by default it acts like the submit button inside the form tag. You can also make it act like button(won't submit the form) by using the attribute type='button'.
Edited
button or input type='submit' can submit the form only when it is placed within the form tag(without javascript).
<form action='http://www.stackoverflow.com/'>
<button>stackoverflow</button> <!-- this works -->
</form>
<form action='http://www.stackoverflow.com/'></form>
<button>stackoverflow</button><!-- this won't work -->
var go = function() {
document.forms[0].submit();
};
<form action='http://www.stackoverflow.com/'></form>
<button onclick='go()'>stackoverflow</button><!-- still works -->

Emptying A Select Form Element With JavaScript

I am creating a small app and on one part of the app, i am creating a drop down select menu, that is populated with values from an array.
The problem i have is that when the form is loaded, it successfully loads and populates the select options with array values, but the problem is that when i add another element to an array and call the form again, it will still only load the values from when the form was first called.
How would i have the select option clear its values when i press the submit button. Here is the code the is called:
<div class="popupForm" id="newRelate_Form" style="display:none">
<form name="relationFormOne">
<script type="text/javascript" language="javascript">
var $selectFrom = $('<select id="mySelect">');
$($selectFrom).attr('id', 'objFrom');
for (var i = 0; i < objectArray.length; i++)
{
var value = objectArray[i].Name;
$('<option>').val(value).text(value).appendTo($selectFrom);
}
$selectFrom.appendTo($("#from_Object"));
var fromVal = document.getElementById("objFrom");
</script>
<button class="closeDOMWindow" onclick="createObj(fromVal.options[fromVal.selectedIndex].text)">Create</button>
</form>
The value is then passed to the function createObj():
function createObj()
{
/*
DO THE WORK NEEDED
*/
}
Now what javascript code would clear the select option so that when it is called again it can be repopulated with any new objects placed into the array?
Thanks for any feedback.
BTW the popup form refers to the fact that im using the following jquery plugin: DOM Window
Thanks for any feedback.
Plain JavaScript:
var ob = document.getElementById('selectID');
while (ob.hasChildNodes())
ob.removeChild(ob.firstChild);
jQuery:
$('#mySelect').children().remove()
Don't forget to delete the previously created select tag using $('#mySelect').remove() and then run the function.
First of all, the best way to add a piece of html is to write it from string:
<form id="relationFormOne">
<script type="text/javascript" language="javascript">
$(function(){
var objectArray = [{Name:'1'},{Name:'2'},{Name:'3'}];
var selectHtml = [];
$('#relationFormOne').append($('<select name="mySelect">'));
$(objectArray).each(function(ix, val){
selectHtml.push('<option>'+val.Name+'</option>');
});
$('select[name=mySelect]').html(selectHtml.join(''));
});
</script>
<input type="button" value="clear" onclick="$('select[name=mySelect]>option').remove()" />
</form>
When you want to clear your select just use the code like the following:
$('#mySelect>option').remove();

Refresh a Div, Table or TR without reloading page and without using Ajax

Is it possible to refresh a div, table or <tr>. Here no such data comes from database, its a simple error displaying block and value comes from Java-script.
Issue is that when an user inputs a value in textbox, value stored in that database and Successfully Stored Message comes on the Screen.
Then again at the same page, user try to enter wrong value then error shows in that block, but the previous value remains ie "Successfully Stored Message".
An suggestion ???
Yes, you can easily clear an element of it's children (i.e. a success message) when some event occurs. In your case, the event would be entering data in a textbox. Assuming the following markup:
<input type="text" id="textbox" name="textbox"/>
<div id="message">
Successfully Stored Message
</div>
When you detect another event on your textbox, you just empty the <div id="message"> as follows:
var textbox = document.getElementById('textbox');
textbox.onchange = function(){
// Do some test to determine if you should clear #message
// Get your #message container and remove all its children
var message = document.getElementById('message');
while(message.hasChildNodes()){
message.removeChild(message.firstChild);
}
};
Change the input's value in this example to see it in action.
So after looking all over the web for this i found a simple way to do "fix":
<script>
$(document).ready(function()
{
$("#refresh").click(function()
{
$("#Container").load("content-that-needs-to-refresh.php");
return false;
});
});
</script>
<div id="Container">
<?php include('content-that-needs-to-refresh.php'); ?>
</div>
Refresh
in the file: content-that-needs-to-refresh.php
You put whatever you would like to have refreshed / Updated / Changed.
Contents of file: content-that-needs-to-refresh.php
<?php
$random = rand(1, 10);
$numbers[1] = "1";
$numbers[2] = "2";
$numbers[3] = "3";
$numbers[4] = "4";
$numbers[5] = "5";
$numbers[6] = "6";
$numbers[7] = "7";
$numbers[8] = "8";
$numbers[9] = "9";
$numbers[10] = "10";
?>
<?=$numbers[$random]?>
This will the give you a random number each time you click on the "Refresh" link.

Categories