I have two dropdowns where the second one (#second) is dependent to the first dropdown (#first). Everytime that #first changes a request is made to the server to get the #second's options.
When I manually select a value of #first there is no problem, the problem is when I use jQuery to fill the form's data. I assign the json's data to corresponding form controls. When I assign the value to #first then I use $("#first").trigger('change') and then I try to assign the value to #second once its options have been loaded.
It seems jQuery tries to assign the value to #second before its options are loaded.
HTML:
<div class="form-group">
<div class="row">
<label for="desCa" class="control-label col-md-2">DES</label>
<div class="col-md-4">
<select name="desCa" id="first" class="form-control">
<option value="">Seleccione</option>
<!-- Incluir catálogo de DES -->
<?php $des=c atalogos( "des"); foreach($des as $des) { echo '<option value="'.$des[ 'idDes']. '">'.$des[ 'descripcion']. '</option>'; } ?>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<label for="entidadCa" class="control-label col-md-2">Entidad</label>
<div class="col-md-4">
<select name="entidadCa" id="second" class="form-control">
<option value="">Seleccione una DES</option>
<!-- Incluir catálogo de Entidades -->
</select>
</div>
</div>
</div>
When #first changes:
$("#first").on('change', function(){
var des = $(this).val();
var get_dependencias = $.get(base_url+'dsac/catalogos.php', {cat: 'dependencias', des: des});
get_dependencias.done(function(dependencias){
if (dependencias.length > 0) {
$("#second").empty();
$.each(dependencias, function(key, dependencia){
$("#second").append('<option value="'+ dependencia['id'] + '">' + dependencia['descripcion'] + '</option>');
});
} else {
$("#second").html('<option value="-1">Seleccione una DES</option>');
}
});
});
Where the problem is:
$.post(base_url+'dsac/cuerpoacademico/buscar.php', {clave: clave})
.done(function(xhr){
var data = $.parseJSON(xhr);
if(data.msgID === 1){
alert(data.msg);
} else {
llenarFormCA(data);
}
});
function llenarFormCA(data){ //data is in JSON format
var pane2 = '#pane2';
//Here a #first option is selected so I trigger change event in order to load #second options.
$(pane2 + " #first").val(data.campo5).trigger('change');
//Altough #second options are loaded, always the first option is selected, not the one that data.campo6 says.
$(pane2 + " #second").val(data.campo6);
}
I would really appreciate any help. Thanks.
Related
I'm now able to change the options dynamically using jQuery. The code below will change the breed options depending on the species selected:
<div class="pet-group">
<div class="form-group">
<select class="species">
<option value="1">Dog</option>
<option value="2">Cat</option>
</select>
</div>
<div class="form-group">
<select class="breed">
</select>
</div>
</div>
<script>
$(document).on("change", ".species", function(){
var elem = $(this),
speciesid = elem.val();
$.get("http://localhost/Vet/get_breeds/"+speciesid, function( result ) {
elem.closest('.form-group').find('.breed').html(result.breed_opts);
}, "json" );
});
</script>
But when a specific pet has been selected, I want the fields to be filled-in with data of the existing pet.
<div class="pet-group">
<div class="form-group">
<select class="pet">
<option value="1">Akamaru</option> <!-- e.g., Akamaru is a dog with Pug as the breed type -->
<option value="2">Nina</option> <!-- e.g., Nina is a dog with Great Pyrenees as the breed type -->
</select>
</div>
<div class="form-group">
<select class="species">
<option value="1">Dog</option>
<option value="2">Cat</option>
</select>
</div>
<div class="form-group">
<select class="breed">
</select>
</div>
</div>
<script>
$(".pet").change(function(){
var elem = $(this),
petid = elem.val();
$.get("http://localhost/Vet/get_pet_details/"+petid, function( result ) {
elem.closest('.pet-group').find('.species').val(result.species_id).trigger('change');
elem.closest('.pet-group').find('.breed').val(result.breed_id).trigger('change');
});
});
</script>
It does change the species field properly and dynamically loads the breed options but it doesn't select the right breed.
What should I so that the right breed will be selected?
When a specific pet has been selected, $.get("http://localhost/Vet/get_pet_details/"...) callback performs in this order:
Step 1: setting value of select.species:
elem.closest('.pet-group').find('.species').val(result.species_id)
Step 2: setting value of select.breed:
elem.closest('.pet-group').find('.breed').val(result.breed_id)
Step 3: call asynchronously event handler of select.species because of
elem.closest('.pet-group').find('.species').trigger("change");
Ajax gets new result.breed_opts, and fills the select.breed. Old value set in step 2 is erased.
So we can do this approach in your first script body:
<script>
$(document).on("change", ".species", function(){
var elem = $(this),
speciesid = elem.val();
$.get("http://localhost/Vet/get_breeds/"+speciesid, function( result ) {
var objbreed = elem.closest('.pet-group').find('.breed');
var oldbreedid = objbreed.val();
objbreed.html(result.breed_opts);
if(oldbreedid) {
objbreed.val(oldbreedid);
}
}, "json" );
});
</script>
After renewing html of select.breed, we restore the previously selected value, ie, that of step 2.
Bellow shown code does these things
when i select Scholership Programs from select list the div element with class="mystaff_hide mystaff_opt1" will be shown
and then i select Family Income now div with class="mystaff_hide mystaff_opt2" will be shown. Now both are there on my window.
Up to this the code works fine
What i want is after submission of my form i want both of them are must be there on my window
<div class="row">
<div class="col-md-6 col-sm-6 pull-left">
<div class="form-group">
<legend>Options to Search</legend>
<select class="form-control firstdropdown" name="sel_options" id="mystuff">
<option>Select Options</option>
<option value="opt1">Scholership Programs</option>
<option value="opt2">Family Income</option>
</select>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt1">
<div class="form-group">
<label for="LS_name">Scholarship</label>
<select class="form-control" name="LS_name[]" id="LS_name" multiple="multiple">
<option value="opt1">Scholership1</option>
<option value="opt2">Scholership2</option>
</select>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt2">
<div class="form-group">
<label for="Family Income">Family Income</label>
<select multiple class="form-control" name="FamilyIncome[]" id="FamilyIncome">
<option value="opt1">Family Income1</option>
<option value="opt2">Family Income2</option>
</select>
</div>
</div>
This is my script
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/multi-select/0.9.12/js/jquery.multi-select.min.js"></script>
<script>
$( document ).ready(function() {
$('.mystaff_hide').addClass('collapse');
$('#mystuff').change(function(){
var selector = '.mystaff_' + $(this).val();
$(selector).collapse('show');
});
});
</script>
After lot of search i got this code which is shows only recent related selected option's div
<?php if(isset($_POST['sel_options']) &&
!empty(isset($_POST['sel_options']))){
?>
<script>
var selected_option = "<?php echo $_POST['sel_options']; ?>";
var selector = '.mystaff_' + selected_option;
//show only element connected to selected option
$(selector).collapse('show');
</script>
<?php } ?>
Take a look at localStorage or sessionstorage to store information about the state of webpage and read them after reload to restore the UI state
Example:
Localstorage
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Sessionstorage
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Or you may want to use AJAX
AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
As you are using jquery, you may want to look at using Ajax in jquery.
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
I need to send a Form with just the values append to the URL, like this:
http://thisistheurl.com/serv#search/VALUE1/VALUE2/VALUE3/VALUE4
I could send like this:
http://thisistheurl.com/serv?variable1=value&variable2=value&variable3=value&variable4=value#search/
The form is very simple.
<form id="consultatickets" name="consultatickets" role="form" method="get" class="tickets-form" action="http://thisistheurl.com/serv#search/" target="_blank">
<div class="row">
<div class="form-group col-md-12 col-sm-12">
<label for="ciudadorigen" class="tickets-imputs">Ciudad de Origen</label>
<select name="ciudadorigen" class="form-control ciudadorigen tickets-imputs" for="ciudadorigen">
<option selected disabled>1</option>
<option value="562">2</option>
<option value="582">3</option>
</select>
</div>
</div>
<!-- Here goes the rest of the form -->
<a type="submit" class="btn btn-warning waves-effect btn-block" href="javascript:{}" onclick="document.getElementById('consultatickets').submit();">Buscar <i class="fa fa-search" aria-hidden="true"></i></a>
</div>
I don't know how to extract the just the values from the variables and append to the URL.
If the order doesn't matter, you can achieve this by serializing the values of the form and appending it to the action attribute of the form to build the final url.
<form id="consultatickets" name="consultatickets" role="form" method="get" class="tickets-form" action="http://thisistheurl.com/serv#search" target="_blank">
<div class="row">
<div class="form-group col-md-12 col-sm-12">
<label for="ciudadorigen" class="tickets-imputs">Ciudad de Origen</label>
<select name="ciudadorigen" class="form-control ciudadorigen tickets-imputs" for="ciudadorigen">
<option selected disabled>1</option>
<option value="562">2</option>
<option value="582">3</option>
</select>
<label for="campo_adicional">Campo adicional</label>
<input id="campo_adicional" type="text" name="campo_adicional" />
</div>
</div>
<input type="submit" value="search"/>
</form>
$("#consultatickets").on('submit',
function(e) {
e.preventDefault();
var values = $(this).serializeArray();
var baseUrl = $(this).prop("action");
$.each(values, function(i, v) {
baseUrl += "/" + encodeURIComponent(v.value);
});
alert(baseUrl);
}
);
https://jsfiddle.net/kb3rvLjs/
Untested and I'm not sure if I got your question correctly but it seems you look for something like this:
// your form submit event handler
function formSubmit() {
var form = $('#consultatickets');
// build your url
var url = 'http://thisistheurl.com/serv#search/' +
getValues(form).join('/');
// redirect to your new location
location.href = url;
};
// function to get the values from the form elements
function getValues(form) {
// get all form fields in the form
var fields = $( "input, select", form);
var values = [];
// loop over the fields, add them to array
jQuery.each( fields, function( field ) {
values.push(encodeURI(field.val()));
});
return values;
}
In case you want to trigger the form submit with the a tag, simply change your onclick attribute to: onclick ="formSubmit();".
hello i want to display data of business3's data according to business2's and business2's data according to business1's dropdown list but on change() of business1 i got data in response but I didn't get second on change() in dropdown list.
<!-- ajax code for first business starts here -->
<script>
$(document).on('change', 'select.Business1', function(){
var business1 = $('select.Business1 option:selected').val();
alert(business1);
var value = $(this).val();
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url('client_area/select_business_sub_cat'); ?>',
success : function (data){
$('#business2').empty();
$('#business2').append(data);
}
});
});
</script>
<!-- ajax code for first business ends here -->
// This script is not working. i can't find second change event.
<!-- ajax code for second business starts here -->
<script>
$(document).on('change','#business2',function(){
alert('Change Happened');
});
</script>
<!-- ajax code for second business ends here -->
I have tried with live() method also so alert called on first dropdown selection and then the ajax request calls so second drop down fills (Alternate for second script) ,
<script>
$(document).live('change', '#business2', function() {
alert('Change Happened');
});
</script>
Model function
public function select_business_sub_cat()
{
$business1 = $this->input->post('business1');
$result_sub_cat1 = $this->db->query("select category.id,subcategory.* From category LEFT JOIN subcategory ON category.id = subcategory.category_id where category.id = '$business1'");
$row_cat1 = $result_sub_cat1->result();
$data = array(
'id' => $row_cat1['0']->id,
'name' => $row_cat1['0']->name
);
echo "<option value='" . $row_cat1['0']->id . "'>" . $row_cat1['0']->name . "</option>";
// return $this->output->set_output($data);
}
View --
<div class="form-group">
<label>Business 1</label>
<select name="txtBusiness1" id="" style="height: 30px;width: 100%;" class="Business1">
<option value=""> Select Business </option>
<?php
$result_cat1 = $this->db->query("select * from category");
$row_cat1 = $result_cat1->result();
?>
<?php foreach($row_cat1 as $item){ ?>
<option value="<?php echo $item->id; ?>"><?php echo $item->name; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label>Business 2</label>
<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">
<option value=""> Select Business2 </option>
</select>
</div>
<div class="form-group">
<label>Business 3</label>
<select name="txtBusiness4" id="business3" style="height: 30px;width: 100%;" class="Business3">
<option value=""> Select Business3 </option>
<?php echo $abc; ?>
</select>
</div>
Maybe that's because by calling $('#business2').html(data); you remove the event handlers, from jQuery documentation: http://api.jquery.com/html
When .html() is used to set an element's content, any content that was
in that element is completely replaced by the new content.
Additionally, jQuery removes other constructs such as data and event
handlers from child elements before replacing those elements with the
new content.
One option would be to use empty and append like this
$('#business2').empty();
$('#business2').append(data);
instead of $('#business2').html(data);
The Script which is not working for you !!!
<script>
$(document.body).on('change','#business2',function(){
alert('Change Happened');
});
</script>
Try this in place of the above script :
$(document).on("change", "#business2", function(){
alert('Change Happened');
});
I am new in SE 4.20. I am having a problem of creating a form element onchange of this form element.
For explanation,
I have a form. I am able to return some select option value on change of this form element. But now I want to add a form element on change of this element.
You want to add a form element, like a text box, if the user changes the select box? Maybe something like:
$("#selectBoxId").change(function (){
$("#formId").append("<input type='text' name='additionalFormElement' />");
});
Here is the html:
<div class="form-elements">
<div id="typeName-wrapper" class="form-wrapper">
<div id="typeName-label" class="form-label">
<label for="typeName" class="required">Type</label>
</div>
<div id="typeName-element" class="form-element">
<select name="typeName" id="typeName">
<option value="Grant">Grant</option>
<option value="Cooperative Agreements">Cooperative Agreements</option>
<option value="Publication">Publication</option>
</select>
</div>
</div>
<div id="resourceName-wrapper" class="form-wrapper">
<div id="resourceName-label" class="form-label">
<label for="resourceName" class="required">Name</label>
</div>
<div id="resourceName-element" class="form-element">
<select name="resourceName" id="resourceName">
<option value="ABC">ABC</option>
<option value="XYZ">XYZ</option>
</select>
</div>
</div>
Here are the mootool js:
$('typeName').addEvent('change', function(event) {
var typeName = $('typeName').value;
var base_path = "<?php echo $this->baseUrl();?>/";
var url = 'http://xxxxxxx.com/test/resource/getresourcebytype';
var request= new Request.JSON({
url: url,
method: 'GET',
data: {"typeName":typeName},
onSuccess: function( response )
{
console.log(response);
//clear the select box
var name = $('resourceName');
while (name.firstChild) {
name.removeChild(name.firstChild);
}
//now add new option
for (var i = 0; i < response.length; i++){
console.log(response[i]);
new Element('option', {'value': response[i].value, 'text':response[i].label}).inject(name);
}
}, onFailure: function(){
console.log('failed');
}
});
request.send();
});