Get value from select with JavaScript for use in PHP - php

I have this select:
<select id="mymenu" name="id" onchange="getID()">
<option></option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
I want to get the value from mymenu to use it in another select in the same form. I searched the 'net and found that I should use onchange.
<select name="uid">
<option></option>
<?
$sql = mysql_query("Select * from $table WHERE id = '$ch_id'");
while ($row = mysql_fetch_array($sql)) {
?>
<option value="<? echo $row['unit_id']; ?>"><? echo $row['unit_name'];?></option>
<?
}
?>
</select>
This is the getID() function:
<script type="text/javascript">
function getChapterID(){ //run some code when "onchange" event fires
var selectmenu=document.getElementById("mymenu")
<?$ch_id?> = this.options[this.selectedIndex].value
}
</script>

You can't redefine a PHP value thru JS, it would be very unsafe. I suggest you to use kind of form that when you change it, it submits, posts into a php self and redefines it. I won't write that code for you, but this is what you need.
Good luck

google "ajax php select menu", the first example here: http://www.w3schools.com/php/php_ajax_database.asp
explains the process...
Beware the w3 demo though, it does not sanitize $_GET[] variable, and is wide open to a sql injection.

Related

Disabling options in select

I have a select with options. I want to disable the options based on ids. Some options have the same id. When i disable the options, it only disables just one id (the first option from the db).
How do I get the jquery to disable all options with id = 0
File.php
<select id="select_id" name="select_id">
<option id="<?php echo $item->part; ?>"><?php echo $item->part; ?></option>
</select>
<script>
$('#0').attr('disabled', 'disabled');
</script>
Applying the same id to multiple elements is not a good practice. I would recommend you use class in this case, instead of id. And then to disable all you would do :
$(".0").attr("disabled", "disabled");
Try this :
html :
<select id="select_id" name="select_id">
<option id="sel1">01</option>
<option id="sel2">02</option>
<option id="sel3">03</option>
<option id="sel1">04</option>
</select>
jquery :
let searchId = 'sel1'
$('#select_id option[id="'+searchId+'"]').attr('disabled', 'disabled')
jsfiddle :
https://jsfiddle.net/bmr1zsq9/
I think it's not a good way to have multiple ids with same values.
You should use name or value or class value to have a valid html
Hope this help
You can either use class attribute or custom attribute like data and you can call it using jQuery selectors.
<select id="select_id" name="select_id">
<option data-id="<?php echo $item->part; ?>"><?php echo $item->part; ?></option>
</select>
<script>
$('select option[data-id="0"]').attr('disabled', 'disabled');
</script>
I think you missed to add value attribute
The issue you are having is because you are using ID's, the DOM expects ID's to be unique thus will not operate recursively. Please update your code to utilize html classes and not ID's.
I.E.
<select id="select_id" name="select_id">
<option value="val1" class="sel1">01</option>
<option value="val2" class="sel2">02</option>
<option value="val3" class="sel3">03</option>
<option value="val4" class="sel1">04</option>
</select>
Also please make sure to set a value to your options for best practice.

PHP to show div info based on selected option in form

I want to use PHP to change a div's information based on what option is selected. Below is my HTML & PHP. I don't think I'm using the right operator or syntax in the if statement. I basically want to pull information from a table in my database based on the option selected. Right now I do not have that in my code because it is irrelevant at this point. Any help is appreciated.
<select id=\"numberofstaff\">
<option class=\"staffselection\" value=\"\">--Select--</option>
<option class=\"staffselection\" value=\"smalljobsite\">1-3 staff</option>
<option class=\"staffselection\" value=\"mediumjobsite\">4-7 staff</option>
<option class=\"staffselection\" value=\"largejobsite\">8+ staff</option>
</select>
<?php
$selectOption = $_POST['numberofstaff'];
echo "<div id='jobsite_price'><p>";
if ($selectOption == 'smalljobsite'){
echo "smalljobsite";
};
if ($selectOption == 'mediumjobsite'){
echo "mediumjobsite";
};
if ($selectOption == 'largejobsite'){
echo "largejobsite";
};
echo "</p></div>";
?>
You need form tags and a POST method, while giving the select a name attribute. You can't rely on an id alone, not without JS/Ajax anyway.
Sidenote: I removed the \ from the escaped quotes, since they're not in an echo statement/PHP in your posted code. This would throw an error/warning such as "unquoted attribute". If you are using it inside an echo'd statement, then you'll need to add those back in.
FYI: Escaping quotes \" is only done when inside an echo/PHP.
Additional note:
If you want to run seperate SQL statements, it's rather simple. Where the echos are and where I have in a comment form // RUN SQL HERE, you can simply include a file in there with your SQL query. I do it myself and it cuts down on a lot of code and is more manageable that way.
HTML/PHP:
<form method="post" action="">
<select id="numberofstaff" name="numberofstaff">
<option class="staffselection" value="">--Select--</option>
<option class="staffselection" value="smalljobsite">1-3 staff</option>
<option class="staffselection" value="mediumjobsite">4-7 staff</option>
<option class="staffselection" value="largejobsite">8+ staff</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
$selectOption = $_POST['numberofstaff'];
echo "<div id='jobsite_price'><p>";
if ($selectOption == 'smalljobsite'){
// RUN SQL HERE
echo "smalljobsite";
}
if ($selectOption == 'mediumjobsite'){
// RUN SQL HERE
echo "mediumjobsite";
}
if ($selectOption == 'largejobsite'){
// RUN SQL HERE
echo "largejobsite";
}
echo "</p></div>";
} // brace for if(isset($_POST['submit']))
?>
Foonotes:
To include files, you can use include():
// Include your SQL query
include('query_file.php');
where you see // RUN SQL HERE in commented code.
Another option is to use Ajax.
Here are a few links:
http://www.w3resource.com/ajax/working-with-PHP-and-MySQL.php
http://www.tutorialspoint.com/php/php_and_ajax.htm
How to use AJAX to perform a MYSQLI query (prepared statement)
If you're just using php to check the selected value, you can use jquery for that, i.e.:
$("select").on('change', function() {
$("#jobsite_price").html("<p>"+$(this).val()+"</p>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="numberofstaff">
<option class="staffselection" value="">--Select--</option>
<option class="staffselection" value="smalljobsite">1-3 staff</option>
<option class="staffselection" value="mediumjobsite">4-7 staff</option>
<option class="staffselection" value="largejobsite">8+ staff</option>
</select>
<div id='jobsite_price'></div>
You can use pure javascript to do this.
window.addEventListener('load', function(){
var el = document.querySelector("#numberofstaff");
el.addEventListener('change', function(){
var data = { numberofstaff : el.value };
var request = new XMLHttpRequest();
request.open('POST', 'YourUrl.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
request.onload = function(result){
document.querySelector("#jobsite_price").innerHTML = result.responseText;
}
});
});

JQM selectmenu first option blank when echoing php-based select items

I'm populating a jQuery Mobile select menu in a form from mySQL database using this php:
$OTsql = "SELECT * FROM OrderTypes";
$OTresult = mysql_query($OTsql) or die (mysql_error());
while ($row = mysql_fetch_array($OTresult))
{
$OTid=$row["id_ot"];
$OTname=$row["orderTypes"];
$OToptions.="<OPTION VALUE=\"$OTid\">".$OTname;
}
the html is this:
<label>Order Type:</label><br>
<select name="orderType" id="orderType" data-overlay-theme="e" data-native-menu="false" data-icon="arrow-d">
<option id="0" value=""> Select Order Type </option>
<option>
<? echo $OToptions ?>
</option>
</select>
While I can click on the selectmenu and see the options listed from the database, it shows a blank (no text listed on the selectmenu button itself) and when I click the menu the top spot is a blank placeholder.
I've tried a variety of jQuery options like variations of this which I've found here at SO:
$(document).bind('mobileinit',function(){
$.mobile.selectmenu.prototype.options.hidePlaceholderMenuItems = true;
});
The bigger problem (I could possibly live without there being the first option listed by default on the button or "Select Order Type" as the item listed on the button--which would be ideal), but when I go to save a pre-existing form, it changes whatever had been selected there to a blank in the database record.
Any insight would be greatly appreciated. I'm not even sure if I'm going about this the right way.
Can you try this,
$OToptions.="<option value=\"$OTid\">".$OTname."</option>";
<select name="orderType" id="orderType" data-overlay-theme="e" data-native-menu="false" data-icon="arrow-d">
<option id="0" value=""> Select Order Type </option>
<?php while ($row = mysql_fetch_array($OTresult))
{
$OTid=$row["id_ot"];
$OTname=$row["orderTypes"];
echo "<option value=\"$OTid\">".$OTname."</option>";
}
?>
</select>
You are constructing your options wrong. Try this:
$OTsql = "SELECT * FROM OrderTypes";
$OTresult = mysql_query($OTsql) or die (mysql_error());
while ($row = mysql_fetch_array($OTresult))
{
$OTid=$row["id_ot"];
$OTname=$row["orderTypes"];
$OToptions.="<option value=\"$OTid\">".$OTname ."</option>";
}
HTML
<label>Order Type:</label><br>
<select name="orderType" id="orderType" data-overlay-theme="e" data-native-menu="false" data-icon="arrow-d">
<option id="0" value=""> Select Order Type </option>
<?php echo $OToptions ?>
</select>
</label>
BTW, mysql_* functions are deprecated. Change to mysqli_* or _PDO functions
As I can see from your code, I expect the generated output to be:
...
<option>
<option>....</option>
...
<option>....</option>
</option>
...
which is wrong. Try to remove the outer tags by modifying your html markup:
<select name="orderType" id="orderType" data-overlay-theme="e" data-native-menu="false" data-icon="arrow-d">
<option id="0" value=""> Select Order Type </option>
<? echo $OToptions ?>
</select>
Additionally, just for an improved style, I suggest you to reformat the PHP part in a more readable way, e.g.:
$OToptions .= '<option value="'.$OTid.'">'.$OTname;

Can I pass Ajax var result to PHP code?

Disclaimer: It's been a while since I last wrote any code. The quality of my code is likely to be sub-par. You've been warned.
Greetings.
I am coding a basic form that uses a SELECT list I populate from my database.
However, my user needs the form to be dynamic and wants to be able to select either MasterTable1 or MasterTable2 or MasterTable3...
Instead of hardcoding the table name for the database query that populates the SELECT list, I attempted to implement a basic Ajax action (used example from w3schools)...and that's when I lost my sanity...
I can output <div id='txtHint'></div> in my page and it shows the correct table name that was picked.
But how do I pass the correct table name to my query that will populate my SELECT list???
I tried
<select name="DBFilename" id="DBFilename" size="0">
<option value="">Select Filename</option>
<?php
$sql="select distinct filename from "."<div id='txtHint'></div>";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){ ?>
<option value="<?php echo $row['filename']; ?>"><?php echo $row['filename']; ?></option>
<?php } ?>
</select>
But to no avail. This is confusing since I can do this...
...
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gettable.php?q="+str,true);
xmlhttp.send();
}
</script></head>
<body><form><select name="SrcTbl" id="SrcTbl" size="0" onchange="showTable(this.value)">
<option value="">Select Data Table</option>
<option value=""> </option>
<option value="MasterTable1">up to 31 days old</option>
<option value="MasterTable2">62 days old</option>
</select>
</form><br /><div id="txtHint"><select name="tabList"><option></option></select> </div>
</body></html>
And the name of my table will be displayed in the SELECT list 'tablist'.
How do I pass the correct table name to my query that will populate my SELECT list? Thanks!!
(Pastebin =>form code)
m8, ajax is mainly used for user experience and populating a select list is so easy mode that it shouldnt be bothered with ajax in the first place!
You should use ajax if you want to use some methods on user submitted data and create an illusion of seamless data exchange between the server and the client, and based on the return results render a corresponding view or an element of the view.
unless you load every element of the view with ajax, you should populate your html with php from the start!
<select name="DBFilename" id="DBFilename" size="whatever since style belongs to css">
<option selected="selected">Select Filename</option>
<?php
$sql="SELECT DISTINCT filename from 'wherever'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){ ?>
<option value="<?php echo $row['filename']; ?>"><?php echo $row['filename'];?>
</option>
<?php } ?>
</select>
Create a separate php script which returns a list of select options -> values depending on the table name given to it. You must remember to protect against sql injection. Then use ajax to retrieve the list and insert it into the select.

quick javascript question about a dropdown with onchange action

Using smarty, take a look at the code below:
<select name="unitSelect" class="uniForm" id="unitSelect" style="width:1250px;" onchange="location.href='{$ABS_MANAGER_URL}/managerEditUnit.php?unit_id={$set[i].id}'; return false">
<option value="0" selected="selected">Select Unit</option>
{section name=i loop=$set}
<option value="{$set[i].id}" >{$set[i].unitName}</option>
{/section}
</select>
What I want, is for the value in the options to load into the select onchange"" call, for the GET variable... I can't figure out how to do this with javascript...any ideas anyone?
Thanks.
UPDATE
It wasn't easy, but between a few of your comments I got one working, thanks all:
<script type="text/javascript">
function viewUnit(value) {
var url = "managerEditUnit.php?unit_id=";
url += value;
document.location.href=url;
}
</script>
Here is an example:
<select onchange="alert(this.options[this.selectedIndex].value)">
<option value="0">Option 1</option>
<option value="1">Option 2</option>
<option value="2">Option 3</option>
</select>
EDIT:
Sorry for the duplicate.
If you want to use it with a function:
function yourfunction(value) {
alert(value);
}
And ofcourse change alert in the above HTML to yourfunction.
You could get the value in the select object by doing this in the onchange event:
onchange="alert(this.options[this.selectedIndex]"
Since you can get that value, then you can dynamically build up your GET request. Some like this:
onchange="document.location.href='somepage.php?id=' this.options[this.selectedIndex];"
jQuery makes it even easier, you can just use:
onchange="alert($(this).val())"
This should do it:
<select onchange="yourfunction(this.options[this.selectedIndex].value);">
I could suggest you to use following for getting the value when select an option from dropdownlist -->
this.value
moving to your javascript means -->
onchange="JavaScript:userDefinedFunction(this.value);"
eg::
select name='state' onchange="JavaScript:userDefinedFunction(this.value);"

Categories