I have a button that is setup from database content as well as a select option that is setup from the same database. I would like to be able to click the button or choose from the dropdown to chose the option.
I have tried a lot of different options that I have found online. Currently I am able to alert the text I want to select but have been unable to change the dropdown.
PHP file
$q = "SELECT CONCAT(user_first, ' ', user_last) AS name1, user_id as id from users ";
$r = #mysqli_query($conn, $q);
// Count the number of returned rows:
$num = mysqli_num_rows($r);
if ($num > 0) { // If it ran OK, display the records.
echo '<select class="select" name="name1" id="Seltherapist" autofocus tabindex="1">';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<option value="'.$row['id'].'">' . $row['name1'] . '</option>
';}
echo '</select>';
mysqli_free_result ($r);
} else {
echo '<p class="error">There are currently no registered users.</p>';
}
$num = mysqli_num_rows($r);
if ($num > 0) {
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<button name="name22" value="'.$row['name'].'" id="'.$row['id'].'" class="btn">' . $row['name'] . '</button>
';}
JavaScript File
$('button[name="name22"]').click(function(){
alert($(this).attr("value"));
alert($(this).attr("id"));
event.preventDefault();
return false;
});
I've not sure where you're getting the text from so lets just call that yourText.
let yourText = "someTextToMatch";
//By option text something like this.
$('#Seltherapist').find('option').each(function(i, v){
if ($(v).text() === yourText)
{
$(v).prop('selected', 'selected');
return false;
}
});
//by option value
$('#Seltherapist').val(yourText);
Related
In my dropdown list, i put all the "pack_name(s)" the user has posted and I display it all in the list for the user to select and update. So when the user selects one and hits submit, i want to get that "value" submitted and use it for later purposes but ive been researching and only found "pre-set" values with html and the value was given using Jquery. So i wondering if its possible to basically take the "pack_name" selected and when the user hits submit, echo out the selected value.
PHP
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicserver', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$userid = $_SESSION['id'];
$stmt = $handler->prepare("SELECT * FROM pack_profile WHERE pack_developer_id = :userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
echo "<select>";
while($result = $stmt->fetch()){
echo "<option>" . $result['pack_name'] ."</option>";
}
echo "</select>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
}
}
?>
You need to give the select element a name attribute, and give each option element a value attribute.
For example:
echo "<select name=\"pack\">";
while($result = $stmt->fetch()){
echo "<option value=\"" . $result['pack_name'] . "\">" . $result['pack_name'] ."</option>";
}
echo "</select>";
Of course you should be escaping anything which could contain &, < or " with something like htmlspecialchars().
I am creating a form for inserting data which technologies are being used by which customers.
I get data of customer's ID and name and select a customer in an drop-down list, and i get data from technologies id and description and display description in a table + it creates a textbox (ID='box-". $row1['ID_T']."') for every technology entry in a DB.
So now i would like to check this dynamically created textboxes with jquery for value (if empty or filled with data) (getelementbyid) but i can not find a way to check theese DYN textboxes.
The ID_T and ID_C will be loaded into another table containing these two PK's and add string from textbox to value.
i would appreciate your help so much!
<HTML>
<HEAD>
<SCRIPT>
function update_tech(id,description)
{
var x = confirm('Do you want to edit technology '+description);
if (x == true)
{
document.getElementById('update_id').value = id;
//document.getElementById('description').value = description;
//document.form_update.submit();
}
}
</SCRIPT>
</HEAD>
<?php
include "connection.php";
$sql = "SELECT ID_C, Name FROM empresa";
$rs = mysql_query($sql, $conn);
$sql2 = "SELECT ID_T, description FROM technologies";
$rs2 = mysql_query($sql2, $conn);
while($row = mysql_fetch_array($rs2))
{
if (isset($_POST["box-".$row["ID_T"]]))
if ($_POST["box-".$row["ID_T"]] != "")
echo "INSERT ....".$_POST["box-".$row["ID_T"]]."<br>";
}
$rs2 = mysql_query($sql2, $conn);
mysql_close($conn);
?>
<BODY>
<SELECT NAME="customers" ONCHANGE="showCustomer(this.value)">
<?php
if (mysql_num_rows($rs))
{
while($row = mysql_fetch_array($rs))
{
?>
<option value='<?php echo $row['ID_C'] ?>'><?php echo $row['Name']?></option>
<?php
}
}
else {
echo "<option value=\"0\">No customers</option>";
}
?>
</SELECT>
<FORM METHOD="POST">
<?php
echo "<table border='0'>";
while($row1 = mysql_fetch_array($rs2))
{
echo "<tr>";
echo "<td><INPUT TYPE='text' name='box-". $row1['ID_T']."' ID='box-". $row1['ID_T']."'></td>";
echo "<td>" . $row1['description'] . "</td>";
echo "</tr>";
}
echo "</TABLE>";
?>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
You can either maintain an array of input box ids or use the jquery partial selector to identify all the input boxes.
jQuery approach is something like:
$('input[id^="box-"]').each(function(e, i) { console.log(e); };
I am working on a very basic administrator functionality of a social network and I came across this issue of not being able to remove an option from select dropdown list that I previously generated using jquery. The dropdown list contains all users of the social network. Administrator upon clicking on "Delete account" deletes the corresponding record from the database.
Now the question being - when I click on "delete account" it works perfectly fine but the option with a username is still there in a dropdown list and is possible to be picked - when picked it obviously returns dozens of PHP warnings and errors because the record is not in a database anymore. How can I remove this option straight away? I tried something like the following, but it doesn't work.
admin_panel.php (only relevant stuff)
<select name='users' id='users'>
<option value="" disabled selected>Select user</option>
<?php
$sql = mysql_query("SELECT * FROM users WHERE id <>'".$_SESSION['user_id']."'ORDER BY username DESC") or die(mysql_error());
$userList = [];
while($row=mysql_fetch_assoc($sql)){
$username = $row['username'];
$userID = $row['id'];
$userList .= '<option name="userID" value='.$userID.'>'.$username.'</option>';
}
echo $userList;
?>
</select></br></br></div>
<div id="user_info">
<!-- generated user info table-->
</div>
<script type="text/javascript">
"$('#user_info').on('click', '#deleteAccount', function(e){
data.command = 'deleteAccount'
data.userID = $('#users').val()
$.post(theURL, data, function(result){
//Do what you want with the response.
$('#delete_account_success').html(result);
})
$("#users option[value='data.userID']").remove();
$('#delete_account_success').show();
$('#delete_account_success').fadeOut(5000);
})
</script>
processUser.php (part of a switch statement)
if(isset($_POST['command'])){
$cmd = $_POST['command'];
$userID = $_POST['userID'];
$sql=mysql_query("SELECT * FROM users WHERE id='".$userID."'");
$userData = [];
while($row = mysql_fetch_assoc($sql)){
$userData['userid'] = $row['id'];
$userData['username'] = $row['username'];
$userData['name'] = $row['name'];
$userData['date'] = $row['date'];
$userData['email'] = $row['email'];
$userData['avatar'] = $row['avatar'];
$userData['about'] = $row['about'];
$userData['admin'] = $row['admin'];
}
switch($cmd){
case 'deleteAccount':
$sql= "DELETE FROM users WHERE id =".$userID;
$result=mysql_query($sql);
echo "<img src='pics/ok.png' class='admin_updated_ok'>";
break;
}
On this line
$("#users option[value='data.userID']").remove();
You're removing any option items from #users where the value is equal to the string literal data.userID
Try changing it to
$("#users option[value='" + data.userID + "']").remove();
I have two dropdown lists as a part of a form I'm creating, both of which have options that are being pulled from a mysql database. I would like the options in the second dropdown to change based on the selection in the first dropdown. I know how to do this using Javascript when the second list is static, but I would like both dropdowns to dynamically pull from the database. Below is the HTML and Javascript I'm currently using. Any ideas would be great.
HTML:
<form>
<label for="org_name">Organization Name:</label>
<select id="org_name" name="org_name" onchange="configureDropDownLists(this,'submitter_name')">
<option value="empty"> </option>
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$query = "SELECT * FROM Table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<option value='" . $row['org_name'] . "'>" . $row['org_name'] . "</option>";
}
mysql_close();
?>
</select>
<label for="submitter_name">Request Submitted By:</label>
<select id="submitter_name" name="submitter_name">
<option value="empty"> </option>
</select>
<input type="Submit" value="Submit">
</form>
Javascript:
function configureDropDownLists(org_name,submitter_name) {
var org = new Array('Submitter 1', 'Submitter 2');
switch (org_name.value) {
case 'org':
document.getElementById(submitter_name).options.length = 1;
for (i = 0; i < org.length; i++) {
createOption(document.getElementById(submitter_name), org[i], org[i]);
}
break;
default:
document.getElementById(submitter_name).options.length = 1;
break;
}
createOption(document.getElementById(submitter_name), 'Other', 'Other');
if (org_name.value === 'empty') {
document.getElementById(submitter_name).options.length = 1;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
As suggested, AJAX was the answer. For anyone curious who comes across this, below is the solution I came up with. I left the HTML unchanged other than removing onchange="configureDropDownLists(this,'submitter_name')" from the first dropdown. Instead of the above Javascript, I used the below AJAX and PHP. Works really nicely.
JQuery:
$(document).ready(function() {
$("#org_name").on("change", function() {
var orgName = document.getElementById("org_name").value;
$.post('admin_list.php', { org: orgName }, function(result) {
$('#submitter_name').html(result);
}
);
});
});
and the referenced PHP page:
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$org_name = $_REQUEST['org'];
$query = mysql_query("SELECT * FROM Table WHERE user = '$org_name'");
while($row = mysql_fetch_array($query)){
echo "<option>" . $row['admin_first_name'] . " " . $row['admin_last_name'] . "</option>";
}
mysql_close();
?>
Sounds like you need some AJAX to pull your data from the database, format on the server side (JSON will likely be easiest to work with), then use a callback function in Javascript to populate the second drop down based on the JSON data received.
I have the checkboxes in the backend and file admin/ban-country-ip.php
CONTENT
HERE IS GETTING THE COUNTRY list with checkbox in the admin backend
<?php
$countryiso = mysql_query("SELECT distinct country_name as country_name FROM location_country");
echo '<table>';
echo '<th>Country</th><th> Add/Remove </th>';
while ($row = mysql_fetch_assoc($countryiso)) {
echo '<tr>';
echo '<td>'. $row['country_name'] . '</td>';
echo '<td><input type="checkbox"></td>';
echo '</tr>';
}
echo '</table>';
?>
AND in the frond end registration it ECHO's them in registration.php.
$ctrstr="";
$res=mysql_query("select * from location_country where code NOT IN('A1','A2','AP','EU') order by name");
$ctrstr.="<select name=\"country\" id=\"country\" onChange=\"loadState();\" >
<option value=\"\" selected=\"selected\">-Select Country-</option>";
while($row=mysql_fetch_row($res))
{
if($country==$row[0])
$ctrstr.="<option value=\"$row[0]\" selected>$row[1]</option>";
else
$ctrstr.="<option value=\"$row[0]\">$row[1]</option>";
}
$ctrstr.="</select>";
I would like to know how can i hide a value from a select list using checkbox. When i un-check in the back-end a country, it should also be removed in the front end in the select field. If i check it again, should be showing again. I want to mention that the countries are stocked in mysql in a column.
MYSQL - TABLE STRUCTURE
# Name Type Collation Attributes Null Default Extra
1 code varchar(2) utf8_unicode_ci No
2 name varchar(255) utf8_unicode_ci No
using jQuery you can do that to hide option from list:
Add ID attribute to checkbox :
<input type="checkbox" id='hide'>
jQuery :
<script type="text/javascript">
$(document).ready(function() {
$("#hide").click(function(){
if( $("#hide:checked").length == 1 ) {
$("#country option[value='1']").hide();
} else {
$("#country option[value='1']").show();
}
});
});
</script>
And if you want to print this script using PHP :
$script = '<script type="text/javascript">
$(document).ready(function() {
$("#hide").click(function(){
if( $("#hide:checked").length == 1 ) { alert($("#hide:checked").length);
$("#country option[value=1]").hide();
} else {
$("#country option[value=1]").show();
}
});
});
</script>';
echo $script;