javascript on change not working on mobile/tablet - javascript

I have the following which works perfectly in a browser but the onchange element fails to fire on Android, and maybe other, devices. I have searched for a solution to this but my understanding of javascript is not so good, as you may be about to tell me.
HTML:
<div class=" col-md-12 col-sm-8 col-xs-8 search-panel search">
<div class=" col-md-3 col-sm-8 col-xs-8 search-panel">
<form method="POST" action="/">
<select class="form-control home_cat_id" name="home_cat_id">
<option value='0'>Select Sales or Rentals</option>
<option value='12'>Sales</option>
<option value='1'>Rentals</option>
<option value='4'>Rentals2</option>
</select>
</form>
</div>
</div>
JAVASCRIPT:
$(document).ready( function(){
//Reset dropdown on page load
$('.home_cat_id').val(0);
// Check if value has changed //
$(".home_cat_id").on("change", function(){
// Pass the form values to the homepage_search.html file
$.post('/includes/homepage_search.html', $("select[name='home_cat_id']").serialize(), function(ret){
// Detect if values have been passed back
if(ret!=""){
$('.search').html(ret);
} else {
alert('ERROR');
}
});
// Stop the page refreshing
return false;
});
});
Thanks in advance for any advice given

Give the dropdown an id and use that id to select the element in you jQuery. Also, if you cache the select element, you get a small performance boost.
HTML
<div class=" col-md-12 col-sm-8 col-xs-8 search-panel search"></div>
<div class=" col-md-3 col-sm-8 col-xs-8 search-panel"></div>
<form method="POST" action="/">
<select id="home_cat_id" class="form-control home_cat_id" name="home_cat_id">
<option value='0'>Select Sales or Rentals</option>
<option value='12'>Sales</option>
<option value='1'>Rentals</option>
<option value='4'>Rentals2</option>
</select>
</form>
Javascript
$(document).ready( function(){
// Cache the select element for performance
$home_cat_id = $('#home_cat_id');
//Reset dropdown on page load
$home_cat_id.val(0);
// Check if value has changed //
$home_cat_id.on("change", function(){
// Pass the form values to the homepage_search.html file
$.post(
'/includes/homepage_search.html',
$home_cat_id.serialize(),
function(ret){
// Detect if values have been passed back
if(ret!=""){
$('.search').html(ret);
} else {
alert('ERROR');
}
});
// Stop the page refreshing
return false;
});
});

Related

Dropdown Data is overlapped with some default elements

I have created a dropdown as below:
<div class="col s4">
<label class="control-label flabels">Name</label>
<div class="asteRisk">*</div>
<div class="row d-flex align-items-center">
<div id="FLevelRow" class="row">
<div class="select-wrapper">
<div class="form-group">
<div class="multipleSelection" id="TaskName">
<select required class="dynamic_Time form-control" id="TaskSKAdd">
<option value="">--Select--</option>
</select>
<div class="overSelect"></div>
</div>
</div>
</div>
</div>
</div>
</div>
and I have written below ajax success method in Js file to append ajax response to this dropdown options.
success: function (response) {
console.log("Lookupresponse", response)
for (var application of response) {
var value = application.NAME.toLowerCase();
$('#TaskName .dynamic_Time')
.append(`<option value="${application.id}" name="${value}">${value} </option>`)
}
},
But while running this code, by default some extra html elements and a select option appears before the above appended options and hence it hides appended options with ajax data from the dropdown list as shown in the below image. Because of that, original content are not visible while clicking on the dropdown. There is no error in the console also.

Show a hidden div using jQuery show() not working [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
I have a hidden div called recipeDetailsDiv inside a form as below
$("#recipes").change(function() {
var selectedVal = $("#recipes").val();
if (selectedVal != "") {
$("#recipeDetailsDiv").show();
}
});
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<form>
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="recipes">Recipes</label>
<select class="form-control" id="recipes" name="recipes" required>
<option></option>
<option>1</option>
<option>2</option>
</select>
</div>
</div>
</div>
<div class="card" style="margin-top: 10px;" id="recipeDetailsDiv" hidden>
<ul class="list-group list-group-flush">
<div id="populateRecipeDetails">Recipe Details</div>
</ul>
</div>
</form>
I am trying to show the hidden div when someone changed the drop down box
I included jQuery CDN too. But it is not showing on change of drop down box. This could be a simple problem. But I cannot figure out how to solve. Can someone help?
Edit 1
I have the following codes included in the following order
<?php include "commonFiles/assignModal.php"; ?>
<?php include "../commonFilesForAll/jsLibraries.php"; ?>
jsLibraries.php contain CDN.
assignModal.php is the same HTML codes I showed above
Your code is working fine. So as #Phil's comment, you should show us the side effect rendering code. Because it may be this problem: Event handler not working on dynamic content
Besides, I would suggest enhancement your logic code.
There are 2 ways to resolve:
Using toggle to handle the case empty select.
If the selected item is diff empty then use show, else then use hide
$("#recipes").change(function() {
const isToggle = $("#recipes").val() !== "";
$("#recipeDetailsDiv").toggle(isToggle);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="recipes">Recipes</label>
<select class="form-control" id="recipes" name="recipes" required>
<option></option>
<option >1</option>
<option>2</option>
</select>
</div>
</div>
</div>
<div class="card" style="margin-top: 10px;" id="recipeDetailsDiv" hidden>
<ul class="list-group list-group-flush">
<div id="populateRecipeDetails">Recipe Details</div>
</ul>
</div>
</form>
If recipes are optional and empty option are selected, you only need show div when an option are selected.
$("#recipes").change(function() {
$("#recipeDetailsDiv").show();
});
The show problem, you can refactor it for class. Creating a class which hides your div and use jQuery.removeClass().

How to reset dropdown box in jquery (select2)?

I have the following code:
https://jsfiddle.net/rmxpq2z0/
<div class="swiper-pagination"></div>
<div id="quote-form" class="quote-form">
<div class="container">
<div class="range range-xs-center range-lg-right">
<div class="cell-xs-10 cell-sm-8 cell-lg-5 text-left offset-top-0">
<div class="inset-lg-left-70">
<div class="quote-form-body">
<div>
<h3 class="text-bold">Get a FREE Quote!</h3>
</div>
<div class="offset-top-25">
<p>Please select your repair from the drop down boxes for an instant quote.</p>
</div>
<div class="offset-top-20">
<div class="form-group">
<select data-minimum-results-for-search="Infinity" class="form-control select-filter" id="console">
<option value="selectconsole">Select My Console</option>
<option value="ps4">PS4</option>
<option value="xboxone">Xbox One</option>
</select>
</div>
<div class="form-group">
<select data-minimum-results-for-search="Infinity" class="form-control select-filter" id="model">
</select>
</div>
Get My Quote
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
ps4models = new Array("Select My Model", "PS4 (Release Model)", "PS4 Slim", "PS4 Pro");
xboxonemodels = new Array("Select My Model", "Xbox One (Release Model)", "Xbox One Slim", "Xbox One Scorpio");
populateSelect();
$(function() {
$('#console').change(function() {
populateSelect();
});
});
function populateSelect() {
console = $('#console').val();
$('#model').empty();
$('#model').html('');
if (console == 'ps4') {
ps4models.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
$('#model').trigger("chosen:updated");
$('#model').find('option:first').attr('selected', 'selected');
});
}
if (console == 'xboxone') {
xboxonemodels.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
$('#model').trigger("chosen:updated");
$('#model').find('option:first').attr('selected', 'selected');
});
}
</script>
It works perfectly in the jsfiddle, but when I post the code to the website, it doesn't work.
It DOES populate the dropdown box, but it won't auto select the first option in the second box, and it won't remove any previous option that was selected.
For example, if I select an option in the first box, the second box stays empty until I select something. The first option should be auto selected. Also if I select something in the second box, and then change the selection in the first box, the second box option stays there, instead of being reset.
It is the EXACT same code, no changes at all. Is it possible the CSS is interfering with it?
Any help would be greatly appreciated.
UPDATE
Thanks to DanielH! It turns out the template was using Select2 jquery plugin. His code worked perfectly.
Solution 1:
Since you are using select2, add $('#model').change(); at the end of your console dropdown's select2 config should trigger the update every time you update the model dropdown list.
Solution 2:
If you have no control over the select2 or not sure where to find it, the following also gonna work, add a onchange event to the parent dropdown console:
$( document ).ready(function() {
$('#console').on('change', function(){
$('#model').val('selectmodel');
$('#model').change();
})
});

Clear text field

Problem: Hello, I would like to be able to clear a field when a value is entered.
The following is the form:
Currently, when the user selects a city. If there is value in the zip code field, the zip code field value will be removed and vice versa. However, when I try to apply the same logic for the same Hospital Name field, instead of leaving the value blank, the value remains there.
The following is what I have done when the user enters a zip code, the city drop down will be blanked and vice versa:
$(document).ready(function(){
$('#zip').on("change",function(){
$('#city option[value=""]').prop('selected',true).trigger('input');
/*console.log('input');*/
});
$('#city').on("change",function(){
$('#zip').val('').trigger('input');
/*console.log('change');*/
});
});
and works fine.
However, I tried to use the same logic to be applied when a user enters a name of a hospital followed by the city. It does remove the city dropdown but not the hospital name field. When I enter a Hospital Name and enter a city, the zip code field will not be blank but remains:
$(document).ready(function(){
$('#zip').on("change",function(){
$('#city option[value=""]').prop('selected',true).trigger('input');
/*console.log('input');*/
});
$('#city').on("change",function(){
$('#zip').val('').trigger('input');
/*console.log('change');*/
});
});
$(document).ready(function(){
$('#zip').on("change",function(){
$('#hospital option[value=""]').prop('selected',true).trigger('input');
/*console.log('input');*/
});
$('#hospital').on("change",function(){
$('#zip').val('').trigger('input');
/*console.log('change');*/
});
});
Here is the form I am using:
<cfset name_list1 = "Hosp">
<cfset name_list2 = "MMG,MG,RG">
<cfquery name="HospCityFind" datasource="Source">
SELECT Distinct officecity FROM UrgHosp
where utilizedspecialty in (<cfqueryparam value="#name_list1#" list="true" cfsqltype="cf_sql_varchar">)
and Company in (<cfqueryparam value="#name_list2#" list="true" cfsqltype="cf_sql_varchar">)
order by officecity
</cfquery>
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate="" role="form">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group"><select class="form-control" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles"></select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
</div>
The hospital field is a text field, but you are trying to clear it the way you cleared the drop down field. Updated:
$(document).ready(function(){
var $zip = $('#zip');
var $city = $('#city');
var $hospital = $('#hospital');
$zip.on("change",function(){
$('#city option[value=""]').prop('selected',true).trigger('input');
$hospital.val('').trigger('input');
});
$city.on("change",function(){
$zip.val('').trigger('input');
});
$hospital.on("change",function(){
$zip.val('').trigger('input');
});
});
I haven't checked this actually runs, but you get the idea.
Other changes I made:
Only one $(document).ready() is ideal.
jQuery is expensive, so I saved jQuery objects to variables and called the variables when possible.
Consolidated both zip changes into the same function.
I was able to resolve my own problem. Just tried to get fancy with the code instead of just going the simple approach. I did the following to resolve my problem:
$(document).ready(function(){
$('#zip').on("change",function(){
$('#city option[value=""]').prop('selected',true).trigger('input');
/*console.log('input');*/
});
$('#city').on("change",function(){
$('#zip').val('').trigger('input');
/*console.log('change');*/
});
$('#hospital').on("change",function(){
$('#zip').val('').trigger('input');
/*console.log('change');*/
});
$('#zip').on("change",function(){
$('#hospital').val('').trigger('input');
/*console.log('change');*/
});
});

How can I append something to input based on dropdown?

I have a dropdown (Which says, URL or SSH).
Whenever the user enters something for example: 192.168.2.1
If URL is selected, I wanted to append http:// and when SSH is selected, ssh:// should be "appended" to the IP address.
My code:
<div class="form-group">
<label for="name-in" class="col-md-3 label-heading">
<select name="urloption" style="width: 100px;">
<option value="URL">URL</option>
<option value="URL">SSH</option>
</select>
</label>
<div class="col-md-6">
<input type="text" class="form-control" id="name-in" name="urldata" value="" placeholder="Enter your Lab info">
</div>
</div>
My Attempt:
I have created a class and based on click, can I do this?
$("input").keyup(function() {
$(".dynamic").html(this.value);
});
How can I do this with HTML?
What you need to do is capture an event on both input elements, and then change the text based on each selection and event.
$("input").keyup(function() {
$(".dynamic").html($('select').val().toLowerCase() +'://' + this.value);
});
$('select').on('change', function(){
$(".dynamic").html(this.value.toLowerCase() +'://'+ $('input').val());
});
Here's the jsFiddle

Categories