Auto Select Dynamic Dropdown Matching value of php variable - javascript

i want to automatically select value of dropdown matching value of php variable
here is my
<select class="destinationId" id="destination" name="destinationId" onchange="getNationalityAndLiving(this.value,'','');">
<option value="" disabled selected>Select Traveling to</option>
<option data-prefix="azerbaijan" value="azerbaijan" >
Azerbaijan </option>
<option data-prefix="cambodia" value="cambodia" >
Cambodia </option>
<option data-prefix="egypt" value="egypt" >
Egypt </option>
<option data-prefix="india" value="india" >
India </option>
<option data-prefix="kenya" value="kenya" >
Kenya </option>
</select>
<select class="nationality" name="nationality" id="nationality">
<option value="" disabled selected>Select Citizen of</option>
</select>
this is my ajax code to retrive dynamic dropdown for select select option "nationality"
<script>
$(document).ready(function(){
$("#destination").change(function(){
var deptid = $(this).val();
var dbnm = "country";
var res = dbnm.concat(deptid);
$('.overlay').show();
$.ajax({
url: 'getcountry.php',
type: 'post',
data: {dest:res},
dataType: 'json',
success:function(response){
var len = response.length;
$("#nationality").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"'>"+name+"</option>");
}
$('.overlay').hide();
}
});
});
});
</script>
i have some dynamic php variable coming on this page from previous url.
for example
$nationality = "some value";
What i want is selected dropdown with value of $nationality in second dropdown,
if it was static i could have achieved this, but how to auto select in dynamic i am not able to get any workaround.

you can pass the php variable to js variable
var Nationality = "<?php echo $nationality; ?>";
then when append the option you can use
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"' "+ (Nationality.trim() == name.trim()) ? 'selected' : '' +">"+name+"</option>");

Related

JS jQuery on change get innerHTML of select option tag

I know how to get the "value" of a selected option tag on change of the select dropdown. But how do I get the associated "text" i.e. inner HTML into the JS variable "country_name" ?
<select name="country" class="country">
<option value="please-select" disabled="disabled" selected="selected">select country</option>
<option value="DE">Germany</option>
<option value="ES">Spain</option>
<option value="FR">France</option>
<option value="IT">Italy</option>
</select>
<script src="js/jquery-3.4.1.min.js"></script>
<script>
$('select.country').on('change',function(){
var country_code = $(this).val();
var country_name = 'Selected Country Name';
alert(country_code+" - "+country_name);
});
</script>
Desired alert output for for instance the second option:
ES - Spain
You just need to build a selector relative to the dropdown, reaching into its option children and filtering to just the selected one, via jQuery's :selected pseudo-selector:
var country_name = $(this).children(':selected').text();
to get the selected text of the selected option of a select field I would do the following
$("select.country").change(function(){
var selectedCountry = $(this).children("option:selected");
var country_code = selectedCountry.val();
var country_name = selectedCountry.text();
alert(country_code+" - "+country_name);
});
Just add this in you javascript
$('select.country').on('change',function(){
var country_code = $(this).val();
var country_name = ( $(this).find(":selected").text() )
alert(country_code+" - "+country_name);
});

How to construct url parameters through object

I am trying to construct the url parameters for the from the value selected from the input elements.
for example: i have a page where there is a one text input field and 3 select fields(name,department,brand,model),first i will enter the value to name text field,then i will select the value from department dropdown,then i wont select anything from brand dropdown, then i will select some value from model dropdown, finally when i press submit, the values which have been input by user should be put in to object with its key pair and generate the url params with $.params(obj) and append that to ajax call. how can i do it. i have the code below of what i have done.
ex:
var obj = {}
//after click on submit
obj = {
_pick:pick,
_dept:dept,
_model:model // this obj contains no brand object, because i have not selected anything from the brand dropdown
}
html:
<form name="populateForm">
<div class="dom_element">
<label>Department</label>
<input type="text" name="pick" id="pick">
</div>
<div class="dom_element">
<label>Department</label>
<select id="departmentSelect">
<option value="0">Select Department</option>
<option value="122">Department-1</option>
<option value="123">Department-2</option>
<option value="124">Department-3</option>
<option value="125">Department-4</option>
<option value="126">Department-5</option>
</select>
</div>
<div class="dom_element">
<label>Brands</label>
<select id="brandSelect">
<option value="0">Select Brand</option>
<option value="212">Brand-1</option>
<option value="213">Brand-2</option>
<option value="214">Brand-3</option>
<option value="215">Brand-4</option>
<option value="216">Brand-5</option>
</select>
</div>
<div class="dom_element">
<label>Model</label>
<select id="modelSelect">
<option value="0">Select Model</option>
<option value="328">Model-1</option>
<option value="324">Model-2</option>
<option value="326">Model-3</option>
<option value="325">Model-4</option>
<option value="322">Model-5</option>
</select>
</div>
</form>
<button class="ApplyFilter">Apply</button>
js:
$(document).ready(function(){
$('.ApplyFilter').on('click',function(){
var paramObj = {};
var pick = $('#pick').val();
var dept = $('#departmentSelect').val();
var brand = $('#brandSelect').val();
var model = $('#modelSelect').val();
if(pick != ''){
paramObj = {
_pick:pick
}
}
if(dept > 0){
paramObj = {
_dept:dept
}
}
if(brand > 0){
paramObj = {
_brand:brand
}
}
if(model > 0){
paramObj = {
_model:model
}
}
/*
this is the object i am expecting at the end, if any input does not have any value then that should not be in this object
paramObj = {
_pick:pick,
_dept:dept,
_brand:brand,
_model:model
}
*/
var urlParams = $.params(paramObj);
if(urlParams.length > 0){
$.ajax({
type: "POST",
url: "/api/getMydata/?"+urlParams,
success:function(response){
console.log(response.responseData);
}
})
}
});
});
Instead of
paramObj = {
_pick:pick
}
just do
paramObj._pick = pick;
The current way you're doing it, the paramObj object is just being reset each if statement.

Selecting an option is resetting another depending selection box

I have two selection (city, building) is the dependent on what the users choose for state.
<form method="post">
<div class="summary">
<div class="trip">
<select name="State" class="state">
<option selected disabled>Choose a State</option>
<option value="1">California</option>
<option value="2">New York</option>
</select>
<select name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<select name="Building" class="building" disabled="true">
<option value="Z">Select a building</option>
</select>
<br><br>
</div>
</div>
City and building is pull as json from an ajax call.
jQuery:
$(document).ready(function() {
var additional = $('.trip').html();
$('#result').hide();
$('form').on("change", "select", function(){
var current_index = $(this).index();
if ($(this).is('.state')) {
var stateid = $(this).val();
}
else {
var stateid = $(this).siblings('.state').val();
};
if($(this).eq(current_index).val() == 'Z') {
$('.city').eq(current_index).html("<option>Select a fare</option>");
$('.city').eq(current_index).attr('disabled', true);
$('.building').eq(current_index).html("<option>Select a fare</option>");
$('.building').eq(current_index).attr('disabled', true);
}
else {
var current = $(this);
$.getJSON('get_city/', {state_id: stateid}, function(data) {
var options_city = '<option value="Z">Select a city</option>';
for(var i=0; i<data.length; i++){
options_city+='<option value="'+data[i].pk+'">'+data[i].fields['name']+'</option>';
}
current.siblings('.city').html(options_city);
current.siblings('.city option:first').attr('selected', 'selected');
current.siblings('.city').attr('disabled', false);
});
$.getJSON('get_building/', {state_id: stateid}, function(data) {
var options_building = '<option value="Z">Select a building</option>';
for(var i=0; i<data.length; i++){
options_building+='<option value="'+data[i].pk+'">'+data[i].fields['building']+</option>';
}
current.siblings('.building').html(options_building);
current.siblings('.building option:first').attr('selected', 'selected');
current.siblings('.building').attr('disabled', false);
});
}
});
$('#add').click(function() {
if ($('.summary').children().length >= 4) return;
$('.summary').append('<div class="trip">' + additional + "<div>");
});
});
The output of the json AJAX for city looks like:
<option value="1">New York City</option>
<option value="2">Albany</option>
Similarly for buildings:
<option value="1">Empire State Building</option>
<option value="2">Penn Station</option>
The issue here is that when I select a city, the building select box resets and all of the options disappears. I know this is because the two getjson call is in the same function. How do I make it so that the selection of city and building are independent from each other?
Once state has been changed and select, I should only need to call $.getjson once until someone changes the state value again.
Here is the relevant code that is "resetting" the city and building checkboxes:
$('form').on("change", "select", function(){
var current_index = $(this).index();
if($(this).eq(current_index).val() == 'Z') {
} else {
current.siblings('.city option:first').attr('selected', 'selected');
current.siblings('.building option:first').attr('selected', 'selected');
}
});
So any time you change ANY dropdown, as long as the value isn't Z, you are setting the city and state to the first option.
Instead of doing $('form').on("change", "select", function(){}) and then if statements for each input, why don't you monitor the change event for each input directly:
<select id="selState" name="State" class="state">
<option selected disabled>Choose a State</option>
<option value="1">California</option>
<option value="2">New York</option>
</select>
<select id="selCity" name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<select id="selBuilding" name="Building" class="building" disabled="true">
<option value="Z">Select a building</option>
</select>
If you want to populate the city and building dropdowns based on the state dropdown, and do nothing when the city and building dropdowns are changed, you would do something like this:
$('form').on("change", "#selState", function(){
//get state id
var stateid = $(this).val();
//Get cities for selected state
$.getJSON('get_city/', {state_id: stateid}, function(data) {
//add "Select a city option"
$('#selCity').html('<option value="Z">Select a city</option>');
//Loop through returned cities.
for(var i=0; i<data.length; i++){
//add city to select
$('#selCity').append('<option value="'+data[i].pk+'">'+data[i].fields['name']+'</option>');
}
});
//Get buildings for selected state
$.getJSON('get_building/', {state_id: stateid}, function(data) {
//add "Select a building option"
$('#selCity').html('<option value="Z">Select a building</option>');
//Loop through returned buildings.
for(var i=0; i<data.length; i++){
//add building to select
$('#selBuilding').append('<option value="'+data[i].pk+'">'+data[i].fields['name']+'</option>');
}
});
//enable other select
$('#selCity').attr('disabled', false);
$('#selBuilding').attr('disabled', false);
})

How can i add value in Option Select?

i have a textarea text "ez.aaaa.value" i want to typing a text and when i select option , redirect automatically to google.com/search?tbm=isch&q= + ((value textarea))
image
Example :
........
<option value="href='http://www.google.com/search?tbm=isch&q=' + ez.aaaa.value">google search</option>
........
This should do it.
the location.href is what you would use to link out.
this refers to the select and selectedIndex returns the number of the selected option.
var sel = document.getElementById('mysel'),
query = document.getElementById('myquery');
sel.addEventListener('change' , function() {
console.log(this.options[this.selectedIndex].value + query.value);
// this would be how to link below
// location.href = this.options[this.selectedIndex].value + query.value;
});
<input type='text' id="myquery">
<select id="mysel">
<option>SELECT ONE</option>
<option value="http://google.com?q=">google</option>
<option value="http://bing.com?q=">bing</option>
</select>
Add select with ID outside of your option and then try this way
JS
var e = document.getElementById("select-menu");
var strUser = e.options[e.selectedIndex].value;
console.log(strUser);
HTML
<select id="select-menu">
<option value="href='http://www.google.com/search?tbm=isch&q=' + ez.aaaa.value">google search 1</option>
<option value="href='http://www.google.com/search?tbm=isch&q=' + ez.aaaa.value" selected="selected">google search 2</option>
</select>

Reset a dynamic dropdown back to initial state

I have an ajax dynamic dropdown form that onchange changes a second dropdown based on the firsts selection. However, if someone were to reset the form, all elements get cleared except for the dynamic one.
I made a reset button function that does: $('#myForm')[0].reset();
However it doesn't reset the dynamic dropdown.
Then I added $('#state').prop('selectedIndex',0); which only then selects the initial subitem.
Essentially I want it to go back to the default <option value="">State/Province</option> state that was there prior to becoming dynamic and I cannot figure out how to exactly to do this.
I am very very new and used previous questions and google to even get me this far.
Thanks
Update:
This is what I need reset:
<select name="state" class="dropdown" id="state">
<option value="">State/Province</option>
<!-- this is populated by ajax -->
</select>
This form changes the above:
<select name="country" class="dropdown" id="country" onchange="getStates();">
<option value="">Select Country</option>
<?php
$con = mysql_connect($db_host, $db_user, $db_pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('earth');
$query = "select id,country from regions order by country";
$result = mysql_query($query);
while ( $row = mysql_fetch_object( $result ) )
{
?>
<option value=<?php echo $row->id; ?>><?php echo $row->country;?> </option>
<?php }
mysql_free_result($result);
?>
</select>
Additional code:
function getStates()
{
$('#state').html('');
var e = document.getElementById("country");
var countryID = e.options[e.selectedIndex].value;
$.ajax({
type: "POST",
url: "getStates.php",
data: {countryID:countryID},
dataType:'json',
//success: function(result){
success: function(data){
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option value=' +o.id + '>' + o.name + '</option>';
});
$('#state').append(toAppend);
},
});
}
function reset_select_box(selector, default_value)
{
if(typeof default_value !== 'string') default_value = "";
var select_box = $(document).find(selector),
children = select_box.children();
console.log(children);
for(var i in children){
if(children[i].value === ""){
select_box.prop('selectedIndex', i);
}
}
};
function resetForm()
{
// since the form is dynamic, reset form does not reset the states
$('#frmSigGen')[0].reset();
}
This seems to do the trick:
function resetForm()
{
$('#frmSigGen')[0].reset();
$('#state').empty();
$('#state').append('<option value="">State/Province</option');
}
Maybe try looping through the select elements children looking for the default value?
var reset_select_box = function(selector, default_value){
if(typeof default_value !== 'string') default_value = "";
var
select_box = $(document).find(selector),
children = select_box.children();
console.log(children);
for(var i in children){
if(children[i].value === ""){
select_box.prop('selectedIndex', i);
}
}
};
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<select id="test">
<option value="">Default</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5</option>
</select>
<button type="button" onclick="reset_select_box('#test');">Reset</button>
</body>
</html>
You could mark the newests options adding a particular data tag, i.e. data-toreset. Then, when you need to reset, remove only options with that tag.
The newest options:
<option data-toreset="1"></option>
The JQuery script could be like:
$('*[data-toreset="1"]').remove();
And then you could select the first element of your combo.

Categories

Resources