Dynamic dropdown list not loading in modal - javascript

I have a dependent dynamic drop listing that works fine but as soon as I include it inside a modal, it doesn't work.
This is my code within the modal:
<script src="plugins/jQuery/2.1.1.jquery.min.js"></script>
<script src="js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#BugMaster').on('change',function(){
var bugmasterID = $(this).val();
if(bugmasterID){
$.ajax({
type:'POST',
url:'ajax/bugs/populate.cat.php',
data:'id_bug_master='+bugmasterID,
success:function(html){
$('#BugMasterCat').html(html);
}
});
}else{
$('#BugMasterCat').html('<option value="">Select BugMaster first</option>');
}
});
});
</script>
This is the html part of the form with the list :
<select class="form-control" name="BugMaster" id="BugMaster">
<option value="0" selected="selected">Please select module</option>
<?
while($r_b_c = mysqli_fetch_array($q_b_c)){
?>
<option value="<? echo $r_b_c['id_bug_master']; ?>"><? echo $r_b_c['name']; ?>
</option>
<? } ?>
</select>
This is the dependent list
<select name="BugMasterCat" id="BugMasterCat">
<option value="">Select country first</option>
</select>
The 'populate.cat.php' file looks like this:
if(isset($_POST["id_bug_master"]) && !empty($_POST["id_bug_master"])){
$id_bug_master = clean_data($_POST['id_bug_master']);
$q_cat = mysqli_query($sqllink,"SELECT * FROM bugs_categories
WHERE valid='1' AND id_bug_master='$id_bug_master'");
while($r_cat = mysqli_fetch_array($q_cat)){
echo "<option value='$r_cat[id_cat]'>$r_cat[name]</option>";
}
}
Then again, all this works fine if I load it directly from a page, but as soon as I open it in a modal, it fails and no categories are shown. I'm thinking it has to do with $(document).ready(function() that is not loading.
By not working I mean that the second drop down list is not being loaded.
Any help will be appreciated. Thank you.

I think no event is attached to your drop down
change your code:
... $('#BugMaster').on('change',function(){ ....
with
$(document).on('click', '#BugMaster', function() {

You need to load your JAVASCRIPT code from model itself, not from the parent / Base page.
But if you want to use another option that either use delegate or use inline javascript function call.
$(document).delegate('#BugMaster', 'change', function(){
//Implement your code here
});
OR
<select class="form-control" name="BugMaster" id="BugMaster" onchange="CALLJAVASCRIPTFUNCTIONHERE();">

Related

Select option and display content related to option with JQuery

this is my first question and after grinding through several threads on here I am still completely lost and can't find a proper solution to my problem.
What I want to do?
A select Box with various options, each options is connected with a JQuery script which makes a related div visible when selected.
<center>
<select onclick="changeview()">
<option value="foo" id="location1" class="ticketbuttons my_active">Location 1</option>
<option value="bar" id="location2" class="ticketbuttons">Location 2</option>
</select>
</center>
When you switch between the options, I want specific DIVs to appear or not appear by this script
<script>
jQuery( document ).ready(function() {
jQuery( "#location1" ) function changeview() {
jQuery(".changing_ticket").hide();
jQuery("#loc1").fadeToggle();
jQuery(".ticketbuttons").removeClass("my_active");
jQuery("#location1").addClass("my_active");
alert('Hello1');
});
jQuery( "#location2" ) function changeview() {
jQuery(".changing_ticket").hide();
jQuery("#loc2").fadeToggle();
jQuery(".ticketbuttons").removeClass("my_active");
jQuery("#location2").addClass("my_active");
alert('Hello2');
});
jQuery( "#location3" ) function changeview() {
jQuery(".changing_ticket").hide();
jQuery("#loc3").fadeToggle();
jQuery(".ticketbuttons").removeClass("my_active");
jQuery("#location3").addClass("my_active");
alert('Hello3');
});
jQuery( "#location4" ) function changeview() {
jQuery(".changing_ticket").hide();
jQuery("#loc4").fadeToggle();
jQuery(".ticketbuttons").removeClass("my_active");
jQuery("#location4").addClass("my_active");
alert('Hello4');
});
});
</script>
and last but not least the frontend output
<div id="loc1" class="change_ticket">Info about location 1</div>
<div id="loc2" class="change_ticket hidden">Info about location 2</div>
I have read about several options like change, onselect, on("change", function () .. and tested but nothin really worked for me.
Hope someone can help me! Thanks in advance!
You could try something like this. Create a variable to store the value of the select dropdown ID & then check which option is selected and hide() the other values and display only the one necessary.
<!-- original dropdown. Replaced by updated for loops in PHP
<center>
<select id="changeEvent">
<option value="1">Location 1</option>
<option value="2">Location 2</option>
<option value="3">Location 3</option>
<option value="4">Location 4</option>
</select>
</center>
-->
<!-- Changes made for dynamic option list-->
<!--Add a data attribute for counter to pass to your jquery loop-->
<center>
<!-- Counter used for creating number of necessary options-->
<?php $counter = 20;?>
<select id="changeEvent" data-counter-id="<?php echo $counter;?>">
<?php
for($i = 1;$i <= $counter; $i++){
?>
<option value="<?php echo $i;?>">Location <?php echo $i;?></option>
<?php
}
?>
</select>
</center>
Your divs use the same counter variable
<!-- Original divs. Replaced by for loop to create dynamic option list
<div id="loc1>" style="display:none;">Info about location 1</div>
<div id="loc2>" style="display:none;">Info about location 2</div>
<div id="loc3>" style="display:none;">Info about location 3</div>
<div id="loc4>" style="display:none;">Info about location 4</div>
-->
<?php
for($x = 1;$x <= $counter; $x++){
?>
<div id="loc<?php echo $x?>" style="display:none;">Info about location <?php echo $x?></div>
<?php
}
?>
In your jQuery function you could add an on('change') event instead of inline on your select dropdown & grab the value of the Select option list and do a check to see which one was selected and display the appropriate DIV. Add a fadeIn() to the item you want to show()
<script>
$(document).ready(function() {
$("#changeEvent").on('change', function() {
/*Original code
var options = $(this).val();
if(options == '1'){
$("#loc1).fadeIn('slow').show();
$("#loc2).hide();
$("#loc3).hide();
$("#loc4).hide();
}else if(options == '2'){
$("#loc1).hide();
$("#loc2).fadeIn('slow').show();
$("#loc3).hide();
$("#loc4).hide();
}else if(options == '3'){
$("#loc1).hide();
$("#loc2).hide();
$("#loc3).fadeIn('slow').show();
$("#loc4).hide();
}else{
$("#loc1).hide();
$("#loc2).hide();
$("#loc3).hide();
$("#loc4).fadeIn('slow').show();
}
*/
/* This will loop through options and display the selected*/
var options = $(this).val();
var counter = $(this).data("counter-id");
for(let i = 1; i <= counter; i++){
if(options != i){
$("#loc" + i).hide();
}else{
$("#loc" + options).fadeIn('slow').show();
}
}
});
});
</script>
Try using onchange instead of onclick on the select tag
<select onchange="changeview()"></select>
or you could try putting ID on the select tag and do some jQuery
<select id="selectOption"></select>
jQuery
$(document).on('change','#selectOption', function () {
// DO THINGS HERE
});

jquery about attributes ( load from loaded html )

I have a 2 select options. When I select the first one it posts to a link using javascript then return full options to the second one with data from a database.
I have an attributes in the second select called data-price. When I'm trying to use it, it shows nothing:
var x = $("#services").find(':selected').attr('data-price');
However when I'm trying with the first select attribute it works correctly. Anyone know how to fix ? Thanks
<script type="text/javascript">
$(document).ready(function(){
var category = document.getElementById("category").value;
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
$('#category').on('change',function(){
var category = $(this).val();
if(category){
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
}else{
$('#services').html('<option value="">Select category first</option>');
}
});
});
var x = $("#services").find(':selected').attr('data-price');
document.getElementById("demo").innerHTML = x;
</script>
<div class="form-group">
<label>Category</label>
<select name="category" id="category" class="form-control">
<?php foreach($categories->result() as $cat): ?>
<option data-price="55" value="<?=$cat->id;?>">- <?=$cat->title;?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Service</label>
<select name="service" id="services" class="form-control">
<option data-price=""></option>
</select>
</div>
<div id="demo"></div>
To find the selected one you do:
$("#services option:selected")
then you can get whatever you want from that option.
For a data attribute it can be:
$("#services option:selected").data('price');
or alternatively
$("#services option:selected").attr('data-price');
This answer is based on the assumption that your select as an id attribute of services, if it is not all the above code will fail
Based on the updated code you posted you probably are looking to update the selected value when the user changes the selection.
I'd do it binding the change event like this:
$("#services option:selected").change(function(){
var price = $(this).attr('data-price');
$('#demo').html(price);
});

Changing the select value in php

I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output

Remove one value from all drop down using jquery

I have multiple drop down with same value.If they select Lunch first time from other drop down I have to remove Lunch. Following is my code
Front end code
<?php for($i=1; $i<=7; $i++)
{?>
<select name="task<?php echo $i;?>" onchange="checkSelected(this,<?php echo $i; ?>);" id="task<?php echo $i;?>"
<option value="Testing">Testing</option>
<option value="Lunch">Lunch</option>
<option value="Other">Other</option>
</select>
<?php } ?>
In javascript I am removing 3rd select box (task3) its got removed but i have to remove all the other except the selected one how i can implement this
javascript function
function checkSelected(e,number)
{
if(e.value == 'Lunch')
{
$('#task3 option[value="Lunch"]').remove();
}
}
I tried this but its not working
$("#task+"number"+ > option[value='Lunch']").remove();
It should be
$("#task" + number + " > option[value='Lunch']").remove();
You could use the .each() function to remove only the option that has the value you select from the list.
$('select').change(function(){
var value = $(this).val()
// Probably best to store this value here before removing the option below.
$(this).children().each(function(){
if($(this).val() == value){
$(this).remove();
}
});
});
Working example - http://jsfiddle.net/amQuU/
Example with multiple dropdowns http://jsfiddle.net/amQuU/1/
Example that removes the options from another select box - http://jsfiddle.net/amQuU/2/
The only problem in doing this is that by removing the selected option it is not shown as the selected option. you can however store the value after selecting it and before removing it from the list as commented above.
Another thing you should consider is changing .remove() to .attr('disabled','true') so that you can re-enable the option later on if you need to e.g. someone wants to go back and change the previous select. Here is an example of that too http://jsfiddle.net/amQuU/3/
If only the "lunch" option is concerned by your answer (see my comment above), then there's a solution. It's not already full-optimized, but you see how you can do it.
JSFiddle http://jsfiddle.net/4qndV/1/
HTML
<form action="demo.html" id="myForm">
<p>
<label>First:</label>
<select class="event_handler" name="task1">
<option value="Testing">Testing</option>
<option value="Lunch">Lunch</option>
<option value="Other">Other</option>
</select>
</p>
<p>
<label>Second:</label>
<select class="event_handler" name="task2">
<option value="Testing">Testing</option>
<option value="Lunch">Lunch</option>
<option value="Other">Other</option>
</select>
</p>
<input type="submit" value="Submit">
</form>
JQuery
$(function () {
// Handler for .ready() called.
$(".event_handler").on("change", function () {
event.preventDefault();
var name_select = $(this).attr("name");
if ($(this).val() == "Lunch") {
//Loop through each "lunch" element
$('.event_handler option[value=Lunch]').each(function(){
//Remove all 'lunch' option, except the ont in the 'name_select' select
if($(this).parent().attr("name") != name_select){
$(this).remove();
}
});
}
})
});
NB: I suppose you have to allow the user to change his selection. It's why I use "disable" in place of "remove". But you can easily adapt this code if you really want to remove the option element.

Onclick event firing in Firefox and IE but not in Chrome

I have the following javascript function.
<script type="text/javascript">
function showhidefields(value,formobj,epsflag,respflag) {
//alert(epsflag);
if (epsflag==0 && respflag==4) {
document.getElementById("tpnr").style.position = "static";
document.getElementById("tpnr").style.top = "0px";
formobj.tussenPersoonNotext.disabled =false;
formobj.email.disabled =true;
}
</script>
<select name="moduleidval" class="validate['required']">
<option value="">-- Selecteer Proces--</option>
<option onclick="showhidefields(this.value,this.form,'<?php echo 1; ?>');"
value="<?php echo $epsmodules; ?>"><?php echo 'MBO'; ?></option>
</select>
My problem is when i click on the option in case of firefox or IE the onclick event fires but in case of chrome it doesnot fire at all.i tried changing the function name also but no luck.
fiddle
thanks in Advance
option elements don't fire the click event in all browsers, you should stray away from relying on this. Instead you can use onchange() event for select. You may use something like this
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>`enter code here`
</select>
</body>`enter code here`
</html>
In Your case you use like
<form id='myForm' action="#">
<select id='mySelect' name="moduleidval" class="validate['required']" onchange="showhidefields(this.value,this.form,'0');">
<option value="-">-- Selecteer Proces--</option>
<option value="1"> 'Klantprocessen'</option>
</select>
</form>
Sure, there is no click event on an option tag.
You may listen to the onchange event of the select tag.
<!-- HTML -->
<form id='myForm' action="#">
<select id='mySelect' name="moduleidval" class="validate['required']">
<option value="-">-- Selecteer Proces--</option>
<option value="MBO">MBO</option>
</select>
</form>
// JavaScript
document.getElementById('mySelect').onchange = function(){
alert('value:'+this.value);
alert('form id:' + this.form.id);
}
See Demo here
Few browsers lack in support of onclick event of option tag. Here is the reference
so you can go for onchange of select tag.
You can pass the value directly in the function specified, like:
<select onchange="trig(value);">
This value can then be used in the trig function.
function trig(val) {
//do foo
alert(val);
}
Short and simple.
A working demo in Chrome: http://jsfiddle.net/amarprabhu/9C3VU/
Check javascript is enabled in ur chrome.
Select Customize and control Google Chrome to the right of the address bar
From the drop-down menu, select Settings
At the bottom of the page, click Show advanced settings…
Under Privacy, click the Content settings… button
Under the JavaScript heading, select the Allow all sites to run JavaScript radio button

Categories

Resources