HTML Input field value set by AJAX and catch that event - javascript

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

Related

Data In Input Box Not Going to JavaScript var

Good day! I want to write an ajax request passing two variables to the controller. The problem is that I cannot get the values from the textboxes to my JavaScript
This is the JavaScript and the HTML code.
When I alert the day variable I get nothing it shows that the field is empty. I am very new to programming
$('#historic_form').submit(function(e) {
e.preventDefault();
var fund_id = $(this).val();
var day = $(this).val();
//data = $('#historic_form').serialize();
$.ajax({
url:'Search/Searchday',
type: 'POST',
dataType:'json',
data: {fund_id: fund_id, day: day},
error: function() {
alert(day);},
success: function(response) {
$("tbody").append("<tr><td>"+title+"</td><td>"+description+"</td></tr>");
}
});
});
And below are my HTML Codes
<select required id="member_id" name="member_id" class="form-control">
<option selected disabled>Select Member</option>
<?php for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->id."'>".$fMembers->row($i)->member_name."</option>";}?>
</select>
<select required class="form-control" id="fund_id" name="fund_id">
<option selected disabled>Select Fund</option>
</select>
<input type="date" required name="day" placeholder="Select a date" class="form-control datepicker hasDatepicker" data-dateformat="dd/mm/yy" id="histDate">
$('#historic_form').submit(function(e) {
Your event handler is triggered by a form submission, so inside the function this will refer to the <form>.
var fund_id = $(this).val();
var day = $(this).val();
<form> elements don't have values. You need to find() the <select> element you want to read the value from and call val() on that.

Access the label text of a datalist option using jquery

I am filling a data-list in html using data from a Json . The options are being appended to the data-list with the value and label text . on click of an option , I want the value and the text to be inserted into a form text field .
The value of the option can be accessed and is successfully inserted into the text field. But I am not able to access the label of the option to insert it.
I have tried using $(this).innerhtml(); , $(this).text(); , $(this).label(); , $(this).innerhtml(); and so on..
all of which turned out to return null value (undefined) instead of the required string.
$(document).ready(function ()
{
$.ajax({
type: 'POST',
url: '#Url.Action("MyJsonFunction")',
datatype: 'json',
success: function (data) {
$.each(data, function (index, data) { $("#myid1").append("<option value='"+data.Value+"'label='"+data.Text+"'></option > ");})},
error: function ()
{
alert("Something went wrong!");}});
$("#myid2").change(function ()
{
var s = $(this).val();
var d = $(this).html();
alert(d);
$("#input1").val(s);
$("#input2").val(d);
});
});
The value of the option is being inserted to the input text field but the label of the option is null when i try to access it .
when i alert it , it displays either an empty string or "undefined" .
$('body').on('change','#myid1',function(){ alert( $(this).find(':selected').attr('label') ) });
Please try this code. I am sure this will work
Try this solution.you have to make any one option as selected, because on form load,none of your options are selected and it will surely alert as undefined.
$(document).ready(function ()
{
$("#colors").trigger('change');
});
$("#colors").change(function () {
var d = $('#colors').find("option:selected").val();
alert(d);
$('#selvalue').val(d);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<label for="color">Favorite Color</label>
<input list="colors" name="color">
<datalist id="colors">
<option selected=selected value="Green">
<option value="Red">
<option value="Blue">
<option value="Yellow">
<option value="Orange">
</datalist>
<input type='text' id='selvalue' placeholder='Display seleted value'/>

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

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>

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

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/

Categories