I am trying to make an html select box which dynamically disables and enables based on what the user select in a different select box... This was working fine when I used just html, but I would like to use the jQuery plugin Chosen for this, and it is not working... The main thing I need dynamic chosen to be disabled or enabled based on the onchange for the other select box. Is this possible with chosen? And how? Thanks so much.
Old Code : Working
<script>
function myDisable() {
a=1;
b=3;
for (i=1;i<3;i++){
posi=a+b*i;
document.getElementById('drop'+posi).disabled = true;
} }
</script>
New code with PHP : Not Working
<script>
function myDisable() {
a=<?php echo $angka; ?>; // a variable number for id select box
b=<?php echo $fields; ?>; // b variable number of many fields table
j=<?php echo $jp; ?>; // j variable number of select boxes that will disable
for (i=1;i<j;i++){
posi=a+b*i;
document.getElementById('drop'+posi).disabled = true;
} }
</script>
PHP select box looping +/- 50 :
<select name="modul[]" id="drop<?php echo $angka ?>" onchange="fetch_select<?php echo $random ?>(this.value); check(this); myDisable();">
<option value="0">Lanjutan</option>
<?php
include 'include/conn.php';
$select=mysql_db_query(#$db,"select nama_modul,jp from modul where nama_pelatihan='$nama_pelatihan'",#$koneksi);
while($row=mysql_fetch_array($select))
{
$jp=$row['jp'];
echo "<option value='".$row['nama_modul']."'>".$row['nama_modul']."(".$row['jp'].")</option>";
}
?>
</select>
Try executing a call to $("#form_field").trigger("chosen:updated"); after the for loop just before exiting the myDisable() function. In your case #form_field will be some selector that identifies your html select box element. Chosen might need to redraw itself to reflect the updated options and this is how we can tell it to do that.
Related
Hello I want to achieve is to make "Select Form HTML" dynamic using JavaScript, What I mean by that is I expect every time I select a dropdown must be selected the value that I set to that tag.
The data from tag is from database I loop the data using php
ex. 1 src: Get selected value/text from Select on change
This example is 100% working correct but what I need is not to get the value but to assign like sample below next example 2
function handleSelectChange(event) {
var selectElement = event.target;
var value = selectElement.value;
alert(value);
}
<select onchange="handleSelectChange(event)">
<option value="1">one</option>
<option value="2">two</option>
</select>
ex 2 Those function will alert or run everytime I select/Click each of them F1 or F2
<table>
<tr>
<td onclick="myFunction1()">F1</td>
<td onclick="myFunction2()">F2</td>
</tr>
</table>
<script>
// Function 1 will run when I click the F1
function myFunction1() { alert('myFunction1'); }
// Function 2 will run when I click the F2
function myFunction2() { alert('myFunction2'); }
In example 1 As you can see the first example select form html will grab the the value of option tag, right?.
Now In example number 2 it will run the function when I click each of the F1 or F2
So what I need to the program is pass a value from my database to my javaScript function and run it like in alert or example 1 but in "Select tag" HTML version
ex. 3 Here's my query
<form action="">
<select name="customers" id="myId" class="form-control">
<option value="">Select a customer:</option>
<?php
$user_id = 1;
$sql = "SELECT * FROM `myTable` WHERE user_id = '$user_id' Order by create_at DESC";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{ ?>
<!-- appsFunction('<?php echo $row['colName2']; ?>') << will be the value that should run in console.log -->
<option value="<?php echo $row['id']; ?>" onclick="appsFunction('<?php echo $row['colName2']; ?>')"><?php echo $row['colName1']; ?></option>
<?php }
} else { return false; }
?>
</select>
</form>
ex. 3 part 2 javascript
<script>
function appsFunction(passVar) {
colose.log(passVar);
}
</script>
As you can see in my first example a "Select Tag" HTML when I select dropdown it returns to me a value right?, in second example when I click F1 or F2 it will run the function then return alert, What I need here is When I select the dropdown it will accept the value I pass in function "appsFunction(passVar)" appsFunction('<?php echo $row['colName2']; ?>') from select tag which the value is from my database.. so I need help idea how to do that properly..
NOTE: The function must be run when I select the dropdown, the function must be accept the value I set which from my database it's like totally example number 2 but in Select tag HTML version not just text or html table.
Thanks in advance for solving my problem.
If you register an event handler on the select element itself that listens for change events you will be able to process the selected OPTION and access any value/property associated with it. You cannot assign an event handler directly to an OPTION element as you are trying to do here. You can add as many dataset attributes as you need to the OPTION elements however which you can easily access in the Javascript event handler.
If the value you pass into the SQL statement is to be dynamic ( from a GET or POST request most usually ) you really need to use a Prepared Statement to help mitigate SQL Injection attacks.
As your select menu is making use of only 3 columns from the mytable table you should limit the returned fields to those columns which in turns helps when using a Prepared Statement as you can easily assign the results as variables.
<form name='geronimo'>
<select name="customers" class="form-control">
<option selected hidden disabled>Select a customer:
<?php
$user_id = 1;
$sql="select `id`, `colName1`, `colName2` from `mytable` where user_id = ? order by create_at desc";
$stmt=$mysqli->prepare($sql);
$stmt->bind_param('s',$user_id);
$res=$stmt->execute();
if( $res ){
$stmt->bind_result($id,$col1,$col2);
while( $stmt->fetch() ){
printf('<option value="%s" data-col="%s">%s', $id, $col2, $col1 );
}
$stmt->free_result();
$stmt->close();
}
?>
</select>
</form>
<script>
document.forms.geronimo.customers.addEventListener('change',function(e){
let id=this.value;
let col2=this.dataset.col;
let col1=this.options[this.options.selectedIndex].text;
alert( id + ' ' + col2 + ' ' + col1 )
});
</script>
I am using Jquery-nice-select plugin.(http://hernansartorio.com/jquery-nice-select/).
I have two select dropdowns. In the first one, I am displaying the country name form database and In second dropdown I am displaying the state name depending upon the country name.
I am able to display the both but the issue is, When I am selecting the country name then state name is displaying but that are not displaying inside select drop down. even I am not able to select it. Please check the below image.
Would you help me out in this?
Before
After selecting the country name
<?php
include('connection.php');
$country_list="SELECT id,name FROM countries";
/* create a prepared statement */
if ($stmt = $conn->prepare($country_list)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id, $country_name);
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="css/nice-select.css">
</head>
<body>
<!--country name-->
<select name="country_data" class="myselect form-control country_data">
<option value="" disabled selected>Select your country</option>
<?php
while ($stmt->fetch()) {?>
<option value="<?php echo $id;?>"><?php echo $country_name;?></option>
<?php }?>
</select>
<!--state name-->
<select name="state" class="myselect form-control state_get">
<option value=''>Select state</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/jquery.nice-select.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('select').niceSelect();
});
$(document).ready(function() {
$(".country_data").on('change',function(){
var country_id=$(this).val();
$.ajax({
url:"process.php?key=state_retrive",
method:"POST",
data:'id='+country_id,
success:function(data){
$('.state_get').html(data);
//alert(data);
}
});
});
});
</script>
</body>
</html>
Process.php
<?php
ob_start();
session_start();
include('connection.php');
switch($_GET['key']) {
case 'state_retrive':state_retrive($conn);break;
default : redirect('index.php');
}
function state_retrive($conn)
{
if (isset($_POST['id'])) {
$country_id=$conn->real_escape_string(trim($_POST['id']));
$state_data="SELECT name,id FROM `states` WHERE country_id=?";
//echo $state_data;
if ($stmt = $conn->prepare($state_data)) {
/* bind parameters for markers */
$stmt->bind_param("s", $country_id);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($state_name, $id);
/* fetch value */
echo $states="<option value=''>Select state</option>";
while ($stmt->fetch()) {
$states="<option value=".$id.">".$state_name."</option>";
echo $states;
}
/* close statement */
$stmt->close();
}
$conn->close();
}
}
?>
The plugin works this way:
It takes the select element and manipulate the DOM by hiding the select element and adding a styled DIV element that has a better UI but still behaves as a SELECT element.
The first time you call the plugin, it has its effect but after updating the state's element - you need to tell the plugin that there's new data.
So, first, we would like to update the SELECT element of the states.
Afterwards we want the tell the plugin that we've updated that select element so it would update the DIV.
success:function(data){
$('select.state_get').html(data); //Make sure you update the SELECT element. not the DIV (by adding "select.xxx").
$('select.state_get').niceSelect('update'); //Tell the plugin to recreate the DIV.
//alert(data);
}
Try to Check the Height of the State DropDown list when it open , check by inspecting it on Browser. Its Height is fixed try to change the Height. Check list height for State DropDown, May it is effected by another CSS files you using . Inspect it and fix.
You can append data in jQuery for that you need to pass json array from process.php file.
var myselect = $('<select>');
$.each(resultData, function(index, key) {
myselect.append( $('<option></option>').val(key).html(key) );
});
$('.state_get').append(myselect.html());
I was wondering if someone got an idea how to remove a choice you made in multiple dropdown menus.
I have no idea if you can do it with dropdown menu's maybe I need datalist or something else.
But what I mean is I have for example 6 dropdown menu's like this
dropdown menu's
I made it so you have 1 - 6 but if I choose number 3 in the first one, how can I remove it in the 2nd menu, or make in invisible.
I had this problem in multiple projects from me but never know how to solve it.
Code of 1 of the menu's
<select name="getal" form="enquete" />
<?php
for($i=1; $i<=5; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
$("#drop1").change(function () {
var d1 = this.value;
if(d1==3)
{
$('#drop3').hide();
}
});
Let´s say you got 2 option select items like this:
<select name="getal" form="enquete" class="selectmenu"/>
<?php
for($i=1; $i<=5; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
<select name="getal2" form="enquete" class="selectmenu"/>
<?php
for($i=1; $i<=5; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
You can add 2 jquery selectors - they can be dynamic - I´m showing you how to do it with 2 dropdown lists:
var $drop1 = $("#geta1");
var $drop2 = $("#geta2");
Create a function to react on change of dropdown 1 (again, you can do it on each beside the clicked one):
$drop1.change(function() {
var selectedItem = $(this).val();
if (selectedItem) {
$drop2.find('option[value="' + selectedItem + '"]').remove();
}
});
We are just removing the options, if you want you can re-add them when changed again. Create one array and iterate through the options, if not present, append the missing options.
Is this what you want to do?
I have a textarea where I will load the term respective to the value of my select. I'm loading the content to the textarea using .load("load_myinvoices_default_terms.php?id="+id). I can load the content successfully. But when I'm to type on the textarea and then change the selected option, the .load() function wont load anymore.
My hunch is that when I type on the textarea it is put on the value, while on I use the .load it is put on the html.
I just want to be able to type on the textarea and still be able to change it's value when I change the selected option.
invoice.php:
<select id="setDefaultTermSelection" name="invoice_term_id" onChange="load_myinvoices_default_terms();">
<option value="0">Set as new term</option>
<option value="1">Term 1</option>
<option value="2">Term 2</option>
</select>
<textarea id="default_terms" name="invoice_terms" placeholder="Enter your terms and conditions" rows="5"></textarea>
script:
<script type="text/javascript">
function load_myinvoices_default_terms()
{
var id = $("#setDefaultTermSelection").val();
$("#default_terms").load("load_myinvoices_default_terms.php?id="+id);
}
$("#default_terms").keyup(function(e)
{
$("#setDefaultTermSelection").val(0);
});
</script>
load_myinvoices_default_terms.php:
<?php
include ("includes/connection.php");
$id = $_REQUEST['id'];
if($id > 0)
{
$query = "SELECT * FROM terms WHERE user_id = $_SESSION[user_id] AND term_id = $id";
$selectQuery = mysqli_query($con,$query);
$row = mysqli_fetch_array($selectQuery);
echo $row['term_description'];
}
else
echo "";
?>
What's happening is that, when you set your select value programmatically like this: $("#setDefaultTermSelection").val(0);, the event change is not triggered.
onchange only triggers when the user clicks. From MDN:
The change event is fired for <input>, <select>, and <textarea>
elements when a change to the element's value is committed by the
user. Unlike the input event, the change event is not necessarily
fired for each change to an element's value.
But, you can trigger the change manually ("simulating" user click) with the jQuery's trigger() method. Something like this:
$("#setDefaultTermSelection").val("0");
$("#setDefaultTermSelection").trigger("change");
Or (one line):
$("#setDefaultTermSelection").val("0").change();
In the last example, .change() is an alias for .trigger("change")
Some points:
The value inside <option> tag is a string. So, you should set the value with .val("0");.
The event according to specification is actually onchange, and not onChange (capital "C"). However, modern browsers actually accept both ways.
I've solved the problem.
First, I've put these on my script as mrlew suggested.
$("#setDefaultTermSelection").val("0");
$("#setDefaultTermSelection").trigger("change");
then on the load_myinvoices_default_terms.php:
<?php
include ("includes/connection.php");
$id = $_REQUEST['id'];
if($id > 0)
{
$query = "SELECT * FROM terms WHERE user_id = $_SESSION[user_id] AND term_id = $id";
$selectQuery = mysqli_query($con,$query);
$row = mysqli_fetch_array($selectQuery);
$x = $row['term_description'];
json_encode($x);
}
else
echo "";
?>
<script>
var ar = <?php echo json_encode($x) ?>;
$("#default_terms").val(ar);
</script>
tho there are more efficient ways of solving this, so please let me know, thanks :)
As i mention on the question, i want to update one select box if another value in the another select box is selected.
for example:
<select id="makale" size="4"name="formMakale"style="height:7em;width:16em;border:0px;outline:0px;font-size:16px;padding-left:10px;" >
<?php
$authorsQuery = $hb->authors();
foreach($authorsQuery as $v){
echo '<option value="'.$v->id.'">'.$v->name.'-'.count($hb>aticlesbyauthor($v),1000).' yazi</option>';}
?>
</select>
<select id="kategoriSec" size="4" name="formCat"style="height:7em;width:16em;border:0px;outline:0px;fontsize:16px;padding-left:10px;" >
<?php
$catQuery = $hb->db->get_results("SELECT * FROM category");
foreach ($catQuery as $v) {
echo '<option value="'.$v->id.'">'.$v->name.'</option>';
}
?>
if i select something from this select box with id makale, i want to update the options of the select box with id kategorisec.
can you help me?
Thank you.
If you just want to change it on the browsers side, use the onchange event handler.
If you want to update the checkboxes based on server data, you could use ajax or simply use an iframe:
<input onclick="update(this)">
<iframe src="checkboxes.php">Oh ,update your browser</iframe>
<script>
function update(elem){
if(elem.selected){ iframe=document.getElementsByTagName("iframe")[0]
iframe.src="checkboxes.php?select="+elem.value;
}
}
</script>