I have 2 <select> inputs:
<select id="state">
<option value="" selected>Select</option>
<option value="california">California</option>
<option value="new-york">New York</option>
</select>
<select id="city">
<option value="">Select</option>
</select>
And the jQuery/AJAX code:
$('#state').change(function() {
var id=$(this).val();
var dataString = 'state='+id;
$.ajax({
type: 'POST',
url: scriptpath+'../ajax/fields.php',
data: dataString,
cache: false,
success: function(output) {
$('#city').html(null);
$('#city').append(output);
},
});
});
Explanation: Everything works fine. The #city input changes depending on the #state input value... Now if I load the page having "california" as the default value -- the #city input doesn't change since it's using the .change() event. How do I detect the selected value on the #state input when the page loads?
I've tried $('#state').on("change load",function() { without success.
Any ideas? Thanks in advance
Just trigger the change event when first page loads:
$('#state').change(function() {
//your code...
}).change();//trigger on page load
Related
So i have this SELECT tags here
<select id="url">
<option id="url1" >url 1</option>
<option id="url2" >url 2</option>
</select>
<button onclick="go()">GO</button>
Then a script here
<script>
function go() {
$.ajax({
url: 'url1.php?check=' + value,
type: 'GET',
async: true,
})
Now, I want to change the line of code that says: url: 'url1.php?check=' + value, to say whatever the selected option's id is rather than the hardcoded "ur1.php". How do I achieve these?
NOTE: I cut the code if you're wondering why is it like that.
Here's a working demo of what you need. I changed the following to make it work:
1) give your <option> tags value attributes (as per documentation) rather than ids. The one relating to the chosen option is then automatically read as being the value of the <select>.
2) get the currently selected URL value by using .val() to get the value of the <select>
3) (non-essential but good practice) using an unobtrusive event handler in the script itself rather than an inline "onclick".
4) (non-essential) you don't need async:true because that's already the default value.
var value = "something";
$("#go").click(function() {
var url = $("#url").val() + '.php?check=' + value;
console.log(url);
$.ajax({
url: url,
type: 'GET',
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="url">
<option value="url1">url 1</option>
<option value="url2">url 2</option>
</select>
<button type="button" id="go">GO</button>
The proper way to do this is to give each of your option's a value attribute. You can the get the select-element and get it's value (which will be the value of the selected option)
I added some code to help you:
function go() {
const select = document.getElementById('select');
const value = select.value; // <-- this here is the value you can use to make your request
console.log(value);
}
<select id="select">
<option value="url1">URL 1</option>
<option value="url2">URL 2</option>
</select>
<button onclick="go()">Go</button>
HTML Code:
<SELECT id="url">
<option id="url1" >url 1</option>
<option id="url2" >url 2</option>
</SELECT>
<button id = "button_go">GO</button>
Script:
$("#button_go").click(go);
function go() {
var value =$('#url').children("option:selected").attr('id');
alert("You have selected the ID- " + value);
// your ajax code
}
Check the jsfiddle working code : https://jsfiddle.net/1eq29w6a/4/
I have One Primary drop-down (Country) and second dependent dropdown. (State). This code works fine only when we select primary dropdown. but doesnt work if primary dropdown already selected on page load.
Primary Dropdown Country:
<select class="select4" name="country" id="country">
<option value="">Please Select</option>
#foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$profile_data->country == $country->country_id ? 'selected' : ''}}>{{$country->country_name}}</option>
#endforeach
</select>
Dependent Dropdown State:
<select class="select4" name="state" id="state">
<option value="">Please Select</option>
#foreach($state_data as $state)
<option value="{{$state->state_id}}" {{$profile_data->state == $state->state_id ? 'selected' : ''}}>{{$state->state_name}}</option>
#endforeach
</select>
Java Script code to fill dependent dropdown.
<script type="text/javascript">
$(document).ready(function() {
$('select[name="country"]').on('change', function() {
var countryID = $(this).val();
if(countryID) {
$.ajax({
url: 'family/state/'+countryID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="state"]').empty();
$.each(data, function(key, value) {
$('select[name="state"]').append('<option value="'+ value.state_id +'">'+ value.state_name +'</option>');
});
}
});
}else{
$('select[name="state"]').empty();
}
});
});
How Ajax code must work on page load also?
You're going to need to manually trigger the change event.
After your:
$('select[name="country"]').on('change', function() { ... }
Force trigger:
$('select[name="country"]').trigger('change');
That way when your document.ready function is about to wrap up, you can force trigger the event and if its set, it'll fire the ajax call
I have an update form in which the data is pre-populated by an ajax call. All the data is getting populated well except the select box. Im using jquery to populate data.
My select code:
<div class="test " id="test">
<select id="gender2" name="gender2" class="required">
<!-- <option value="" selected></option> -->
<option value="F">Female</option>
<option value="M">Male</option>
</select>
</div>
Ajax call:
$.ajax({
type: "POST",
url: 'fetchData',
data: {
'custId': custID,
},
success: function (paxUpdateData) {
var cust = jQuery.parseJSON(paxUpdateData);
$("#firstName").val(cust.firstName);
$("#middleName").val(cust.middleName);
$("#gender2").val(cust.gender);
},
error: function (e) {
alertify.error('Error in retreiving details');
}
});
I have tried these but none worked:
$('gender2 option[value='+cust.gender+']').attr('selected', 'selected');
$('#gender2 option[value='+cust.gender+']').prop('selected', true);
$("div.test select").val(cust.gender);
Note: im getting data from backed as cust.gender=M for male and cust.gender=F for female.
Try
$('#gender2').change(function() {var selectvalue =$('#aioConceptName').find(":selected").val(cust.gender);});
$("#gender2").change(function() {
//your ajax
});
Try this
When it comes to select box it requires change() event,
$.ajax({
type: "POST",
url: 'fetchData',
data: {
'custId': custID,
},
success: function (paxUpdateData) {
var cust = jQuery.parseJSON(paxUpdateData);
$("#firstName").val(cust.firstName).trigger('change');
$("#middleName").val(cust.middleName).trigger('change');
$("#gender2").val(cust.gender).trigger('change');
},
error: function (e) {
alertify.error('Error in retreiving details');
}
});
See This Demo is working , now u can put your ajax function inside document ready function , and please check in ajax Response console.log() value is same as your select option value.
$(document).ready(function(){
$('#gender2').val("O");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test " id="test">
<select id="gender2" name="gender2" class="required">
<option value="F">Female</option>
<option value="M">Male</option>
<option value="O">Other</option>
</select>
</div>
I'm looking for guidance on the following scenario:
Context: A page displays a dynamically generated list with X (changes based on the user) number of items, each formatted as follows:
<div class="dashboard_section_item">
<label for="add_listname_label">Assign to list</label>
<br/>
<select name="mod_list" class="mod_list">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</div>
I need to handle the user selection in the dropdown list in JQuery. The problem is the list is repeated x times on the page, so it will only work for the first item displayed.
$(document).ready(function () {
$(".mod_list").change(function () {
$.ajax({
type: 'POST',
url: 'mod.php',
data: 'prod_uid=' + $('.prod_uid').val() + '&mod_list=' + $(this).find(':selected').val(),
dataType: 'json',
success: function (response) {...
},
error: function () {...
}
});
return false;
});
});
I'm thinking about concatenating a UID to the list name tag like:
<select name="mod_list_34745727" class="mod_list">
but I'm unsure whether there is a better way to do this.
How can I uniquely identify each item list to select its dropdown value?
Supposing that there are a lot of selects with class mod_list you can use on() delegation:
$(document).ready(function () {
$(document).on("change", ".mod_list", function () {
// this is the select you changed the value
var $changedValueSelect = $(this);
// do stuff, ajax and so on
// print in console the selected value
console.log($changedValueSelect.val());
});
});
Why delegation? Because you have dynamically appended elements in your page.
JSFIDDLE
i'm using the source code for multiple selection
Dropdown check-list
Since, the example has been shown for the static values, i have edited as per my requirement, And i was trying to populate the values of the dropdown list using database, which means dynamically populating the values into the dropdown-list. But, i'm failed to do. Please help me. The dropdown list will be populated as per the option selected from the first dropdown
<select id="design" onmouseup="showOfficer()" >
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
<select id="officers" class="officers" multiple="multiple"><div id="show_officer"></div></select>
my javascript
<script language="javascript" >
function showOfficer(){
document.getElementById("msg4").style.display="block";
$.ajax({
url: 'getValues.jsp',
data: 'design_id='+ $('#design').val(),
type: 'post',
success: function(msg){document.getElementById("show_officer").innerHTML=msg;
document.getElementById("msg4").style.display="none";
}});
}
</script>
getValues.jsp
<%#include file="../dbconfig.jsp" %><%
String design=request.getParameter("design_id");
String buffer="";
try{
int count=0;
ResultSet rs = state.executeQuery("SELECT OFFICER_ID,FIRST_NAME,LAST_NAME FROM OFFICER WHERE STATUS_TYPE='UNASSIGN' AND DESIGN_ID='"+design+"'");//
while(rs.next()){
buffer=buffer+"<option value='"+rs.getString(1)+"'>"+rs.getString(2)+" "+rs.getString(1)+"</option>";
count++;
}
if(count==0)
{
buffer=buffer+"<option value='ERROR'>OFFICERS ASSIGNED ALREADY</option>";
}
}
catch(Exception e){
buffer=buffer+"<option value='ERROR'>OFFICERS ASSIGNED ALREADY</option>"+e;
}
buffer=buffer+"";
//out.print(buffer);
response.getWriter().print(buffer);
%>
Please help me !!
I think this is what you're looking for:
success: function(html){
$("#msg4").hide();
$("#officers").html(html);
$("#officers").dropdownchecklist();
}
replace your success function with this and take that div out of your select.
If you're loading jQuery why don't you use it for more than just the ajax call?
remove the onmouseup, and try this:
$('#design').mouseup(function(){
$("msg4").show();
$.ajax({
url: 'getValues.jsp',
data: 'design_id='+ $('#design').val(),
type: 'post',
success: function(html){
$("#msg4").hide();
$("#officers").dropdownchecklist("destroy");
$("#officers").html(html);
$("#officers").dropdownchecklist();
}
});
});