Select box options not getting selected by jquery with ajax response data - javascript

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>

Related

Fetching data through ajax and then apply filter using select

I have 3 different select menu: 1.Category 2.State 3.City
I am using ajax to fetch the data on "#searchresult" by using jquery on change method that send data on PHP.
Fetching is going properly but only for one "select" option.
What I want is when user change another "select" option, it will update the current "#searchresult" fetched data.
Like: Suppose, on changing "category" to "car", it fetch all the data of "cars" on "#searchresult" and now on "state" change to "new york", it update the "#searchresult" that are in new york.
I tried many different approches like using multiple if statements to find whether the select is choosen or not, but reached no where.
Thanks in advance.
My code is:
$(document).ready(function() {
$("#category").change(function() {
var data = $("#category option:selected").val();
var category = $("#category option:selected").text();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "category",
data: {
data: data
},
dataType: 'json',
cache: false,
success: function(response) {
$("#searchresult").html("");
for (var i = 0; i <= 5; i++) {
$("#searchresult").append('<div class="col-12 col-sm-10 col-md-4 col-lg-3 col-xl-2 merchant" style="background-image: url(https://im.proptiger.com/1/1543935/6/green-villa-elevation-7990949.jpeg?width=380&height=285);"> <div class="filter"></div> <span class="category">' + category + '</span> <div class="col align-self-end"> <p>' + response.contractor[i].first_name + '</p> <span>' + response.contractor[i].city_name + ',' + response.contractor[i].state_name + '</span> </div> <div class="slideup"> <p>More info?</p> Profile </div> </div>');
}
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category" id="category" class="chosen">
<option value="0" default>category</option>
<option value="1">Car</option>
<option value="2">Van</option>
</select>
<select name="state" id="state" class="chosen">
<option value="0" default>state</option>
<option value="1">Any</option>
<option value="2">other</option>
</select>
<select name="city" id="city" class="chosen">
<option value="0" default>city</option>
<option value="1">New york</option>
<option value="2">Chicago</option>
</select>
<div id="searchresult"></div>
and PHP is sending data in the form of json.
Thanks
#user5745970 here is sample fiddle I created to give you an idea on what needs to be done. Link to the fiddle is below
The idea is to have 3 different change events for each of your select and trigger a call to your server. What you need to do is send the other select values as data if selected. For example, if you're changing the City when the category is already selected, you need to send both category and city to your server to get you the response. If all 3 server side calls return the same JSON structure, then you can have only 1 success and error callback.
Do change the urls, method types and callbacks accordingly to match what you need.
$(document).ready(function() {
var category = '';
var state = '';
var city = '';
$("#category").on('change', function() {
category = $("#category option:selected").text();
// here you need to check if state or city is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', category, handleCategorySuccess, handleCategoryError)
});
$("#state").on('change', function() {
state = $("#state option:selected").text();
// here you need to check if category or city is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', state, handleStateSuccess, handleStateError)
});
$("#city").on('change', function() {
city = $("#city option:selected").text();
// here you need to check if state or category is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', city, handleCitySuccess, handleCityError)
});
});
var ajax = function(url, method, data, successCallBack, errorCallBack) {
$.ajax({
type: method,
url: url,
data: data,
dataType: 'json',
cache: false,
success: successCallBack,
error: errorCallBack
});
}
function handleCategorySuccess(response) {
alert(response);
}
function handleCategoryError() {
alert('error');
}
function handleStateSuccess(response) {
alert(response);
}
function handleStateError() {
alert('error');
}
function handleCitySuccess(response) {
alert(response);
}
function handleCityError() {
alert('error');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category" id="category" class="chosen">
<option value="0" default>category</option>
<option value="1">Car</option>
<option value="2">Van</option>
</select>
<select name="state" id="state" class="chosen">
<option value="0" default>state</option>
<option value="1">Any</option>
<option value="2">other</option>
</select>
<select name="city" id="city" class="chosen">
<option value="0" default>city</option>
<option value="1">New york</option>
<option value="2">Chicago</option>
</select>
<div id="searchresult"></div>
JSFiddle

ajax not working for multiple select box

I have multiple select box by click to add button and all select box have ajax call on change event, but it is not working. Only work s for first.
code is given below.
Following code call ajax for default select box, but not working for next dynamically inserted select box..
$(document).ready(function () {
$(".one").change(function () {
var one = $('.one').val();
var company = $('.one').next();
$.ajax({
url: 'https://champbaba.tk/demo/two.php',
data: {'one': one},
type: 'POST',
success: function (data) {
$(company).html(data);
}
});
});
});
$(document).ready(function () {
var companyhtml = $(".one").html();
$(".add").click(function (e) { //on add input button click
e.preventDefault();
$('<select class="one">' + companyhtml + '</select><select class="two"></select>').insertAfter($('.wrap'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<select class="one">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select class="two">
</select>
</div>
<button class="add">Add</button>
It's working but I thought it's not a good way to work like that you need to search about that how to reinitialize event.
$(document).ready(function () {
var companyhtml = $(".one").html();
$(".add").click(function (e) { //on add input button click
e.preventDefault();
$('<select class="one">' + companyhtml + '</select><select class="two"></select> <br>').insertAfter($('.wrap'));
$("select").change(function () {
var one = $(this).html();
var company = $(this).next('select').html(one)
$(this).next('select').val(1);
});
});
$("select").change(function () {
var one = $(this).html();
var company = $(this).next('select').html(one)
$(this).next('select').val(1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<select class="one">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select class="two">
</select>
</div>
<button class="add">Add</button>
try it now.
The problem you have is one of event delegation.
You're attempting to affix an event handler to an element that doesn't actually exist in the DOM at the time the handler is attached. Adding $(document).ready() won't resolve this, because the element is generated dynamically, after page load.
To work around this, you have to hoist the scope and attach the event handler to an element that will exist on page load, such as document. You're looking for $(document).on("change", ".one", function() {} ) instead of $(".one").change(function() {} ):
$(document).ready(function() {
/* Ajax Call... */
$(document).on("change", ".one", function() {
var one = $('.one').val();
var company = $('.one').next();
$.ajax({
url: 'two.php',
data: {
'one': one
},
type: 'POST',
success: function(data) {
$(company).html(data);
}
});
});
/* To add more select boxes.. */
var companyhtml = $(".one").html();
$(".add").click(function(e) { //on add input button click
e.preventDefault();
$('<select class="one">' + companyhtml + '</select><select class="two"></select>').insertAfter($('.wrap'));
});
});
Hope this helps! :)
$(".wrap").live('change','.one'function () {
var one = $('.one').val();
var company = $('.one').next();
$.ajax({
url: 'two.php',
data: {'one': one},
type: 'POST',
success: function (data) {
$(company).html(data);
}
});
});

HTML Input field value set by AJAX and catch that event

I have field in my html, and some third-party service will set it's value.
How could I catch that event when the field value is changing?
<input data-val="true" data-val-length="City cannot be longer than 30 characters." data-val-length-max="30" data-val-required="City is required." id="Address_City" maxlength="30" name="Address.City" type="text" value="">
How could I catch the value change of this field,
I've tried .change event also,
$('#Address_City').on('change', function() {
console.log("Changed");
});
Use change event.
$("#myTextBox").on("change", function() {
//alert($(this).val());
});
<select name="user_id" id="user_id" class="form-control" onchange=get_contact(this.value)>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control" name = "contact_mob" id="contact_mob" placeholder="Contact Number" value="" />
function get_contact(user_id) {
$.ajax({
type: "POST",
url: "search.php",
data: {
"user_id": user_id
},
dataType:'json',
success: function(data) {
// console.log(data.user_mobile);
$("#contact_mob").val(data.user_mobile);
// $("#replaceThis").append(responseData);
}
});
}
Please specify which control your using in your code.
You Can use change or keydown Event.
FOr Client Control
$("#TextBOXID").bind("keydown", function() {
if($("#TextBOXID")[0].value!="" && $("#TextBOXID")[0].value.length>0)
{}
});
For Server Control
$("#<%=TextBOXID.ClientID%>").bind("keydown", function() {
if($("#TextBOXID")[0].value!="" && $("#TextBOXID")[0].value.length>0)
{}
});
We are going to retrieve a value and set that value in an HTML form. First, let's create the form.
Form
<form method="POST" action="">
<select name="user_id" id="user_id" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control" name = "contact_mob" id="contact_mob" placeholder="Contact Number" value="" />
</form>
Now that we have a form, we will do the technical part using javascript and jQuery
Javascript/jQuery
// Wait for the dom to load before we start doing stuff
$(document).ready(function ($) {
// append value to input on change of the dropdown
$(document).on('change', '#user_id' , function () {
// Get selected value
var user_id = $(this).val();
$.ajax({
type: "POST", // Set ajax call type
url: "search.php", // Set url
data: {"user_id": user_id}, // Set an array of data
dataType:'json', // Set the data type
success: function(data) {
// Log response to console
console.log(data);
// Append data to input
$("#contact_mob").val(data.user_mobile);
}
});
});
});
That's all
I think I found some solution, I'm going to use a timer here, there will be some permanence issues.. but I couldn't find anything be
$('#Address_Address').on('change keyup paste click', function () {
$('.pcaautocomplete .pcaselected').click(function () {
var refreshInterval = setInterval(function () {
if ($('#State').val() != "") {
var statusVal = $('#State').val();
clearInterval(refreshInterval);
}
}, 100);
});
});

Show/Hide div send all data to database

I have this show/hide div. And I am running into couple issues. I am using CodeIgniter by the way.
First : When I select real-estate the div shows. But if I select Service, the real-estate div won't hide. (Service has no div).
Second : If I select real-estate and fill out the form, and I change my mind and select automobile and fill out the form then send to database, I get all the fields from real-estate and automobile into my database. Which is not what I want.
Third : Is there a different approach if I wanna add more categories and more divs show/hide?
<select id="catid_1" name="catid_1">
<option value=""></option>
<option value="5">Real-Estate</option>
<option value="8">Automobile</option>
<option value="10">Service</option>
</select>
<!--Auto-->
<div id="8" class="forms">
Energie :
<select name="energy">
<option></option>
<option value="Gasoline">Gasoline</option>
<option value="Diesel">Diesel</option>
<option value="GPL">GPL</option>
<option value="Electric">Electric</option>
<option value="Hybrid">Hybrid</option>
</select><br />
Transmission :
<select name="tans">
<option></option>
<option value="Manuel">Manuel</option>
<option value="Automatic">Automatic</option>
</select><br />
Miles :
<input type="text" name="mile"/><br />
Year :
<input type="text" name="year"/><br />
</div>
<!--Realestate-->
<div id="5" class="forms">
Room :
<input type="text" name="room"/><br />
Surface :
<input type="text" name="surface"/><br />
</div>
<!--End Tech-->
$(function() {
$(".forms").hide();
$("#catid_1").change(function() {
var e = $(this).val();
if(e == '8' || e == '5') {
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
});
// Bind to the submit
$('#submit').click(function(e){
e.preventDefault();
// Parse the data only for the displayed div.
var resolve_data = function() {
var output = {};
// Here you place the acceptable fields.
$('.form-active input, .default input').each(function() {
output[$(this).attr('name')] = $(this).val();
});
return output;
};
// Submit the form here.
$.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: resolve_data(),
beforeSend: function(xhr, settings){
// Before sending, check the data.
alert(settings.data);
},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
});
});
first: service show/hide is not working because you're putting a conditional on the ID:
if(e == '8' || e == '5') { // <<-- remove this conditional
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
second: When you're doing your update, check the value of the drop down box and only update the fields that belong to that choice. Your form should be sending along the value of the option, so that's not to hard to do. For instance, if the select value is 5, only update the room and surface fields in your database. Don't try to clear the form when switching choices, it's safer to do this in the back end.
If you insist on doing it front end, put an actual form in there and .reset() it when changing options.
third: probably, but this seems OK no? Are you not happy with it?
http://jsfiddle.net/zf9BN/1/

append value into dropdown-list

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();
}
});
});

Categories