jQuery on change dropdown call web service to load options - javascript

I have a form with a dropdown list and a variable amount of options (in the form of checkboxes and text inputs).
What I want to achieve is onchange value of the dropdown list, call a web service and load the various options below it. I know roughly I have to use jQuery's onchange event and have Ajax load the markup into the div.
But how exactly do I achieve that?
I am using Bootstrap 3, and some of my form code is below. I am not sure how to write my Javascript or Ajax part, though.
Dropdown list
<div class="form-group">
<label for="inputBranch" class="col-lg-2 control-label">Branch</label>
<div class="col-lg-10">
<select class="form-control" id="resBranch">
<?php
// print all branch name
// if is same as merchantID, mark as selected
foreach($branchesArray as $branch) {
if($branch['merchantID'] == $merchantID) {
echo "<option selected>" . $branch['name'] . "</option>";
} else {
echo "<option>" . $branch['name'] . "</option>";
}
}
?>
</select>
</div>
</div>
Options
<div class="form-group">
<label for="" class="col-lg-2 control-label">Options</label>
<div class="col-lg-10">
<?php
foreach ($featuresArray as $feature) {
?>
<div class="checkbox">
<label>
<input type="checkbox" value="<?php echo $feature['customValue']; ?>">
<?php echo $feature['customValue']; ?>
</label>
</div>
<?php
} // end foreach
?>
</div>
</div>

You could send an ajax request with the currently selected form option to a php web service which returns the html to add to the form.
The js could look something like this:
$( document ).ready(function () {
$('select').change(function () {
$.get('ajax.php?option=' + $('select').val(), function(data) {
if(data == "error")
{
//handle error
}
else {
$('div.ajax-form').append(data); //create an element where you want to add
//this data
}
});
});
});
The php might look like this:
if(isset($_GET['option'])) {
if($_GET['option'] == 1)
{
//echo form data for option one here
}
elseif($_GET['option'] == 2)
{
//echo form options for option two here
}
elseif($_GET['option'] == 3)
{
//echo form options for option two here
}
//other options here
else
{
echo "error"; //select value not correct
}
}

Related

Retain selected value of the dropdown after page refreshes

I need to retain selected value of the dropdown after page refreshes on click.
What is happening:
After I select an item from the dropdown the page reloads by itself and the value of the dropdown go to starting position though the value displays on the end of the url.
This is my code:
<script>
function refreshPage(passValue){
window.location="index.php?cat_page=admin_post&sw_cat=sw_catn="+passValue;
}
</script>
<div class="form-group col-md-4">
<label for="inputState">Your health proplem</label>
<select name="illness_id_cat" class="form-control" onchange="refreshPage(this.value);" >
<?php
while(mysqli_stmt_fetch($stmt)){
echo "<option value='{$illness_id_cat}'>{$illness_name_cat}</option>";
}
?>
</select>
</div>
This option doesn't work too:
<script>
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
</script>
<div class="form-group col-md-4">
<label for="inputState">Your health proplem</label>
<select name="illness_id_cat" class="form-control" id="dropdown" >
<?php
while(mysqli_stmt_fetch($stmt)){
echo "<option value='{$illness_id_cat}'>{$illness_name_cat}</option>";
}
?>
</select>
</div>
This I don't know how to implement, what is a "itemname":
<script>
var text = localStorage.getItem("itemname");
if(text !== null) {
$("select option").filter(function() {
return this.text == text;
}).attr('selected', true);
}
</script>
A more conventional way to do this would be using PHP, and getting the querystring value you're passing in via the window.location command:
<script>
function refreshPage(passValue){
window.location="index.php?cat_page=admin_post&sw_cat="+passValue;
}
</script>
<div class="form-group col-md-4">
<label for="inputState">Your health problem</label>
<select name="illness_id_cat" class="form-control" onchange="refreshPage(this.value);" >
<?php
while(mysqli_stmt_fetch($stmt)){
echo "<option";
//get the category value from the querystring and check it against the current category value in the loop. If it matches, pre-set the option as selected
if (isset($_GET["sw_cat"])) {
if ($_GET["sw_cat"] == $illness_id_cat) echo " selected";
}
echo " value='{$illness_id_cat}'>{$illness_name_cat}</option>";
}
?>
</select>
</div>

display data after selecting options from dropdown codeigniter

I'm very new here and also to codeigniter and Ajax.
I need to display data after selecting from the drop down option without reloading the page / submit button. It displays after the option is selected as I'm able to properly display data for the options, now I just need to display data based on that option on two separate fields.
For example :
paket : paket 1
description : its something something
jadwal : soon to be announced
the options are the product, the one I need to be displayed on their separate fields is the description on description field and jadwal on jadwal field.
Here is the code I have for the view:
//this is the code for the options
<div class="form-group">
<label for="paket">Pilih Paket</label>
<select class="form-control form-control-sm" name="paket" id="paket">
<option value="">Pilih Paket</option>
<?php
foreach ($datatour as $dttour)
{
if ($id==$dttour->id)
{
$s='selected';
}
else
{
$s='';
}
?>
<option <?php echo $s ?> value="<?php echo $dttour->id;?>"><?php echo $dttour->paket;?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<div class="col-md-8" align="left">
<label for="jadwal">Jadwal</label>
<div style="border:1px solid #ccc;text-align:left;background-color:white;">
// this is where i display the jadwal data
</div>
</div>
</div>
<div class="kolom" style="border:1px solid #ccc;background-color:white;overflow:auto;" align="center">
<div class="row">
<h3>Detail Paket</h3> <br>
// this is where i display the description data
<p></p>
</div>
</div>
I haven't written any code for the models and the controllers, any help and explanation of the process (if that's not much to ask) would be very much appreciated, thank you.
Separate your view in two views:
First view: named sand_main.php in folder sandbox_v
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="form-group">
<label for="paket">Pilih Paket</label>
<select class="form-control form-control-sm" name="paket" id="paket">
<option selected value="">Pilih Paket</option>
<option value="123">123</option>
<option value="324">566</option>
<option value="555">333</option>
<!-- I've used my own code, for checking the result, you should use your:
<option value="">Pilih Paket</option>
<?php
foreach ($datatour as $dttour)
{
if ($id==$dttour->id)
{
$s='selected';
}
else
{
$s='';
}
?>
<option <?php echo $s ?> value="<?php echo $dttour->id;?>"><?php echo $dttour->paket;?></option>
<?php
}
?>
-->
</select>
</div>
<div id="info"></div>
Where JS should be next:
<script type="text/javascript">
$(function(){
$('#paket').unbind('change');
$('#paket').change(function(){
var opt_sel = $('#paket').val();
$.ajax({
method:"POST",
url:'/index.php/sandbox/s1',
data:{
sel_op:opt_sel
}
}).done(function(a){
$('#info').html(a);
}).fail(function(){
alert("It's an epic fail.");
});
});
})
</script>
Second view: named sand_view_2.php in folder sandbox_v
<div class="row">
<div class="col-md-8" align="left">
<label for="jadwal">Jadwal</label>
<div style="border:1px solid #ccc;text-align:left;background-color:white;">
<?= $j_info; ?>
</div>
</div>
</div>
<div class="kolom" style="border:1px solid #ccc;background-color:white;overflow:auto;" align="center">
<div class="row">
<h3>Detail Paket</h3> <br>
<?= $d_info; ?>
<p></p>
</div>
</div>
Controller: in my example sandbox.php
<?php
class Sandbox extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
// here you should get your $datatour data
$this->load->view('sandbox_v/sand_main.php', [
'datatour' => $datatour
]);
}
public function s1() {
$sel_val = $this->input->post('sel_op');
/*you can use your DB for getting a description for each value
* in this case you should add in __construct() your model as $this->load->model('your_model);
* or use your DB connection directly here.
*/
/* with your model:
* $jdwal_info = $this->your_model->your_jdwal($sel_val);
* $detail_info = $this->your_model->your_detail($sel_val);
*/
// without. It means that you've got info in the other way, for example, in predefined way:
if ($sel_val == 555) {
$jdwal_info = 'descr 1';
$detail_info = 'detail 1';
} else if ($sel_val == 123 ) {
$jdwal_info = 'descr 123';
$detail_info = 'detail 123';
} else if ($sel_val == 324 ) {
$jdwal_info = 'descr 324';
$detail_info = 'detail 324';
} else {
$jdwal_info = 'descr N\A';
$detail_info = 'detail N\A';
}
$this->load->view('sandbox_v/sand_view_2.php',[
'j_info' => $jdwal_info,
'd_info' => $detail_info
]);
}
}
Model: named your_model.php
<?php
class Your_model extends CI_Model {
function __construct()
{
$this->load->database();
}
public function your_jdwal($a) {
// process of getting result from DB over input variable $a (the name of it doesn't matter)
return $res;
}
public function your_detail($a) {
// process of getting result from DB over input variable $a (the name of it doesn't matter)
return $res;
}
}
Check it. It works for me.
Try to implement this code, reference in W3schools Jquery
$(document).ready(function(){
$("#btn_form_submit").click(function(){
$.ajax({
cache:false,
type:"POST"
//equivalent of action attribute in form tag
url:"path/to/your/php/"
data: $("my_form").serialize(),
success: function(data){
//returns data from php if success
}
});
});
});

JQuery/Javascript -- show div based on select but NOT value

I am using PHP to dynamically populate a select box (a list of equipment). The value is set with the ID of the item selected so I can use it later in my programming.
What I need help with...
Based on the item selected I need to show/hide one of two form fields but I can't use the value as this is the id.
What I need to be able to do is read the text in the select box which will contain the item name with either (Service: Set by dates) or (Service: Set by hours) and show either the form field for the date or the form field for the hours?
Is this possible? I can find loads great resources based on the value but not on the text in the select.
I think something like this should work but not sure how to use the text in the select rather than the value.
$(function() {
$('#system').change(function(){
$('.system').hide();
$('#' + $(this).val()).show();
});
});
Any help would be greatly appreciated!!!!
Regards
Matt
(N.B this is what I'm working with at the mo based on the answers so far, thank you all so much for the help (and for your example Louys Patrice Bessette) - not quite there yet... I was getting an error and managed to track it back to the script not getting the result from the select box. See below now working code! Thanks all!!!
<div class="col">
<div class="form-group">
<label for="system_select">Equipment or System to be serviced</label>
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name; ?></option> <?php
}
?>
</select>
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$("#due_dates").hide(); // Hide both divs
$("#due_hours").hide(); // Hide both divs
$('#system_select').change(function(){
var dataType = $(this).find(':selected').attr('data-type') // should be "Set by dates" or "Set by hours"
if (dataType == 'Set by dates') {
$("#due_hours").hide();
$("#due_dates").show();
} else if (dataType == 'Set by hours') {
$("#due_dates").hide();
$("#due_hours").show();
}
});
});
</script>
<div class="row">
<div class="col-md-3" id="due_date">
<div class="form-group">
<label for="service_date">Next Service (Set by dates)</label>
<input type="date" class="form-control" name="service_date" id="service_date" value="<?php echo escape(Input::get('service_date')); ?>" autocomplete="off">
</div>
</div>
<div class="col-md-3" id="due_hour">
<div class="form-group">
<label for="service_hours">Next Service (Set by hours)</label>
<input type="number" class="form-control" name="service_hours" id="service_hours" value="<?php echo escape(Input::get('service_hours')); ?>" autocomplete="off">
</div>
</div>
</div>
I think that you PHP $system->service_type; is echoing either "Set by dates" or "Set by hours".
If you echo that in a data attribute like this:
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type; ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name . ' (Service: '. $system->service_type .')'; ?></option> <?php
}
?>
</select>
Then, in jQuery, you could use it like this to decide to show <div id="due_hours" class="col-md-3"> or <div id="due_hours" class="col-md-3">.
$(function() {
$('#system').change(function(){
$('.system').hide(); // I don't know what this is for...
$("div[id=^'due']").hide(); // Hide both divs
var dataType = $(this).data("type"); // should be "Set by dates" or "Set by hours"
var type = dataType.split(" by ")[1]; // should be "dates" ot "hours"
$("#due_"+type).show();
});
});
Now be carefull with the s on dates...
Try this out... Console.log the values to make sure you have the correct one to match the id to show.
;)
If $(".classname").text() is not working you could try to add that info that you need in a "data" attribute.
Something like this ->
<option data-service="service name" class="myClass">15</option>
Using data attributes can give you a lot of freedom on what you can add. You could add lots of information that a normal user cant read (without inspecting element).
Then you would simply do something like this ->
$(".myClass").on("click", function() {
var serviceData = $(this).attr("data-service");
})
You can then do if checks, compare and whatever you need.
EDIT: Or you can use your approach with on.change and get the selected data attr, it would probably be better
If you change your select into something like this:
<select class="form-control" name="system_select" id="system_select">
<option data-hide='#due_date' data-show='#due_hours'>Show Hours</option>
<option data-hide='#due_hours' data-show='#due_date' value="B">Show Dates</option>
</select>
And your jquery like this:
$('#system_select').change(function () {
$($(this).children("option:selected").attr("data-hide")).hide();
$($(this).children("option:selected").attr("data-show")).show();
});
It could work.

Add second SELECT on change of first SELECT (PHP/AJAX) Not working as it should

firstly, let me express that I have tried four methods (All slightly different) that all seem to produce the same issue, which is no data being outputted, even simple echo 'test' to rule out a DB issue (and also trying TEST in html on the called page, no result.
Here is a snapshot of the HTML and Javascript:
(document).on('change','category_id',function(){
var id = $(this).val();
$.ajax({
method: 'POST',
url: 'supportgetsubcats.php',
data: {'subcatid' : id},
success: function(data){
$('#subcatresponse').hide().html(data).fadeIn(); // update the DIV
}
});
});
<div class="form-group">
<label class="col-sm-2 control-label">Category *</label>
<div class="col-sm-4">
<select class="form-control" class="category_id" name="category_id" id="category_id">
<option value="" selected="selected">-- Select --</option>
<?php
$query="select * from support_categories where hide = '0' or hide is NULL order by name ASC";
$rs=sqlsrv_query($conn,$query);
while($row=sqlsrv_fetch_array($rs))
{
extract($row);
?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php
}
?>
</select>
</div>
</div><!-- form-group -->
<div class="form-group">
<div id="subcatresponse" name="subcatresponse" class="col-sm-4">
</div>
</div><!-- form-group -->
Here is the PHP that is called:
<?php require_once("includes/header.php");
error_reporting(E_ALL);
echo 'TEST';
if(isset($_POST["subcatid"])){
// Capture selected country
$category = $_POST["subcatid"];
$query="select * from support_subcategories where parent_category = '" . $category . "' order by name ASC";
$rsp=sqlsrv_query($conn,$query);
$subCatArr = array();
while($row=sqlsrv_fetch_array($rsp))
{
$subcat = $row['name'];
array_push($subCatArr, $category, $subcat);
}
// Display city dropdown based on country name
if($category == '-- Select --'){
} else {
echo '<label class="col-sm-2 control-label">Sub Category</label>';
echo '<select class="form-control" name="subcategory_id" id="subcategory_id">';
foreach($subCatArr[$category] as $value){
echo '<option value="'. $value .'">'. $value .'</option>';
}
echo "</select>";
}
}
?>
I get no response, not even basic text back, so I am not entirely sure what is wrong with the AJAX call, jQuery is included and proven to be working as the menu system on this interface won't display without jQuery so I am confident that is not the issue.
It looks like for whatever reason, the data from the HTML Select is not being passed to the AJAX call for POST.
Any thoughts greatly appreciated, TIA.
Try changing
(document).on('change', 'category_id', function() {
to
$(document).on('change', '#category_id', function() {
The second parameter to the on call takes a selector, but you seem to be passing in the name of the element instead. The name of the element is used when trying to access the element in PHP, and you use the selector (id, class, element) in JavaScript.
Alternatively, you could also use
$('#category_id').on('change', function()
You haven't posted it in your question, but in case you don't have it, it is always a good idea to only execute your jQuery code after the page has finished loading, otherwise your code may be trying to access an element that hasn't been loaded yet.
Surround your jQuery code with
$(document).ready(function() {
// Run jQuery code
}
add type='POST' to your ajax call
Also change this
(document).on('change','category_id',function(){
to
$(document).on('change','category_id',function(){

Disable divs with checkboxes using class approach

I have combination of divs and check-boxes. In each div there are text-boxes and radio buttons. So at the top level if I want to disable any div I should be able to do so with checkbox corresponding to that div.
I have written JQuery to do so but if I check or uncheck checkbox for one div, it is also affecting another div and its content. So I want a class based approach to get this functionality. Also on page load, the div contents should be disabled. Thanks
$(".disableDivCheckbox").click(function () {
$(".disableDiv *").prop("disabled", !this.checked);
});
Refr this code working fine.
<script>
$(function () {
$("#chkPassport").click(function () {
if ($(this).is(":checked")) {
$("#dvPassport").show();
} else {
$("#dvPassport").hide();
}
});
});
</script>
//html/php code
<div class="form-group col-sm-12">
<label class="form-group col-sm-3">
<input type="checkbox" id="chkPassport" name="chkPassport" value="first_checkbox">Add Payment</label>
<div id="dvPassport" style="display: none">
<label class="form-group col-sm-12">Payment Type</label>
</div>
<div class="col-sm-4">
<?php
$stmt = $conn->prepare('Select pay_type_name from tbl_payment_type');
$stmt->execute();
$result = $stmt->fetchAll();
print '<select class="col-sm-11" name="pay_type_name" id="pay_type_name">';
foreach ($result as $row) {
print "<option value=".$row['pay_type_name'].">".$row['pay_type_name']."</option>";
}
print '</select>';
?>
</div>
</div>

Categories