I have a select field in a form, and wish to execute some jQuery when the field is changed or when the page is reloaded on form submit.
<select name="emp_status_id" class="emp-status-id" >
<option value=""></option>
<option value="1">Full-Time Employment</option>
<option value="2">Part-Time Employment</option>
<option value="3">Casual</option>
<option value="4">Self Employed</option>
</select>
My jQuery is below
function employmentGroups(id){
var emp_status_id = id.val();
// Do more stuff here
};
$( ".emp-status-id" ).change(function() {
employmentGroups($(this));
});
Not: I am passing $(this) into the function rather than getting $(this) inside the function for another reason which isn't relevant to the current question.
This works perfectly well on change.
I would also like to execute the function on page load,
My problem is that I do not understand which jQuery method to use to execute this function on load.
I have tried this...
$( ".emp-status-id" ).ready(function() {
employmentGroups($(this));
});
However this does not work.
Better way to access this selectbox value by id.
Here is working code:
<select id="emp_status_id" name="emp_status_id" class="emp-status-id" >
<option value=""></option>
<option value="1">Full-Time Employment</option>
<option value="2">Part-Time Employment</option>
<option value="3">Casual</option>
<option value="4">Self Employed</option>
</select>
function employmentGroups(selector_id){
var emp_status_id = $(selector_id).val();
// Do more stuff here
};
// on page loaded
$(function() {
// set onchange handler
$("#emp-status-id").change(function() {
employmentGroups('#emp-status-id');
});
// just execute
employmentGroups('#emp-status-id');
});
$(document).ready(function(){ employmentGroups($( ".emp-status-id" )); })
Looking for this?
there's two ways to do such a thing like this
1- using load() but this will fire whatever the code inside every time page reload even when the use open the page for the first time
$(window).load(function() {
// do whatever you want
});
2- using built-in PerformanceNavigation interface ... i didn't test such a case to use it but it exactly for detecting navigation behavior
if (performance.navigation.type === 1) {
console.log('page reloaded');
}
or (is the same as above but with different syntax)
if (performance.navigation.type === PerformanceNavigation.TYPE_RELOAD){
console.log('page reloaded');
}
for further reading W3 and MDN
Related
I have the following function:
$('#borderColor').on('change', function() {
// update inventory
updateInventory(this.options[this.selectedIndex].text);
});
How can I automaticcally trigger this function when the page loads?
Just trigger the change event on the select on page load. This way you don't need to write duplicate code, and everything is handled at one place.
with $('#selector').trigger() you can trigger any event, like change, click, input, etc... you're listening to.
With $(document).ready(function() { /** your code here **/}) you can set code you wish to run after the page has finished loading and rendering.
function updateInventory(value) {
$('#inventory').text(value);
}
$('#borderColor').on('change', function() {
// update inventory
updateInventory(this.options[this.selectedIndex].text);
});
$(document).ready(function() {
$('#borderColor').trigger('change');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="borderColor">
<option value="red">red</option>
<option value="blue" selected="selected">blue</option>
</select>
<div id="inventory">
</div>
Did you heard the jquery trigger?
$(function() {
$('#borderColor').trigger('change')
});
I try to call a function when a value from the select box is chosen. I would also have a default value selected and a button appear for that value on the page.
This is my select box:
<select id="messagingMode" class="bootstrap-select" >
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>
This is the js:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this));
And the function just prints the selected value for the moment:
function showCorrespondingAuthorizationBtn(select) {
console.log(select.val());
}
Nothing is printed in the console, why doesn't this work?
Try with direct call function name not with function() .Default bind with this in change function
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn() {
console.log($(this).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="messagingMode" class="bootstrap-select">
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>
You are invoking the function, not passing it as reference. Also this is not what you think it is in that context.
Try:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn(event) {
console.log($(this).val());
// or
console.log(this.value);
}
Use the jQuery event delegation:
$('#messagingMode').on('change',function(){
console.log($(this).val());
});
Here is a working fiddle.
$('#messagingMode').change(function () {
showCorrespondingAuthorizationBtn($(this).val());
});
It is not triggering because your are invoking the method on your event attachment logic.
// calling the invocation operator () triggers the method
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this));
In order to solve this, try the following code.
function onDropdownChanged() {
var sender = $(this);
console.log(sender.val());
}
$(document).ready(function() {
$('#messagingMode').on("change", onDropdownChanged);
})
I have the following HTML select:
<select class="form-control" id="band_id" name="band_id">
<option selected="selected" value="">Choose a band...</option>
<option value="66">Adolfo Little</option>
<option value="96">Aisha Bosco</option>
<option value="90">Alize Glover</option>
</select>
I need to build a filter where the condition is the #band_id selected so I made this jQuery code:
$("select#band_id").change(function (ev) {
ev.preventDefault();
var band_id = $('select#band_id');
if (band_id.val() != undefined) {
band_id.attr('selected', 'selected');
}
location.href = '/albums/bands/' + band_id.val();
});
Because the location.href the page gets reloaded and the URL changes so the SELECT is reset and I "loose" the selected value.
I can think in two ways to fix this:
Using AJAX which I don't want because is over complicate something easy
Grab the band_id from the URL and then set the selected property which I don't know how to achieve.
I don't know is there any other way to achieve this. Do you have any other idea? (if it's with an example better)
You can use localStorage for that:
if (localStorage.getItem("band_id")) {
$("select#band_id").val(localStorage.getItem("band_id"))
}
$("select#band_id").change(function (ev) {
ev.preventDefault();
if ($(this).val() != undefined) {
$(this).attr('selected', 'selected');
localStorage.setItem("band_id", $(this).val());
}
location.href = '/albums/bands/' + $(this).val();
});
If we have the value saved - set the value of the select element to that values.
Once we change the value in the select element - save the new value in the localStorage.
Note that I removed the usage of the band_id from this example as it's not needed. You have this you can use inside the change function.
I'm also not sure why you change the selected attribute - you redirect the user immediately to a new page (this change will have no effect at all).
I put selected="selected" for mail option. When the page is rendered, it should call the setImage function and display the image. But it is not happening, why?
JSFiddle
function setImage(select){
var image = document.getElementsByName("image-swap")[0];
image.src = select.options[select.selectedIndex].value;
}
<select name="kitchen_color" id="kitchen_color" onchange="setImage(this);">
<option value="https://www.google.ru/images/srpr/logo4w.png">Google</option>
<option value="http://yandex.st/www/1.645/yaru/i/logo.png">Yandex</option>
<option value="http://limg.imgsmail.ru/s/images/logo/logo.v2.png" selected="selected">Mail</option>
</select><br />
<img src="" name="image-swap" />
The answer is NO, the event you listen to is 'CHANGE' and there is no change since the page is loaded.
So, you will need to 'trigger' change event by yourself.
See example how to get what you want:
window.onload = function(){
var kitchen_color = document.getElementById('kitchen_color');
kitchen_color.onchange();
};
Or if you use jQuery:
$(document).ready(function(){
$('#kitchen_color').trigger('change');
});
http://jsfiddle.net/z2y24thk/
try this one after function declaration
$(document).ready(function(){
$('#kitchen_color').trigger('change');
});
here is updated jsfiddle
http://jsfiddle.net/NWbsj/76/
ok so i have some select tags of cities
<select onchange="storeCity(this.value, false)" name="search[city]" id="search_city" class="left">
<option value="">== Select City ==</option>
<optgroup label="Florida"><option selected="selected" value="ft-myers-sarasota-fl">Ft. Myers / Sarasota </option>
<option value="jacksonville-fl">Jacksonville</option>
<option value="miami-fl">Miami / Ft. Lauderdale </option>
<option value="orlando-fl">Orlando</option>
<option value="tampa-fl">Tampa</option></optgroup></select>
Some cities are not available now so i needed a lightbox to popup when they are clicked...which i have working with this code
$('#search_city').change(function(e) {
e.preventDefault();
if ($(this).val() == 'jacksonville-fl' || $(this).val() == 'miami-fl' || $(this).val() == 'tampa-fl' || $(this).val() == 'ft-myers-sarasota-fl') {
}
The problem I have is that it goes to the link anyways and i need it to get rid of the link or the onchange on the select...something is getting the page to refresh...but i dont know what
storeCity(this.value, false) might have caused the refresh
BTW, you can merge the code like this:
$('#search_city').change(function(e) {
storeCity(this.value, false);
if (this.value.match(/(jacksonville-fl|miami-fl|tampa-fl|ft-myers-sarasota-fl)/i)) {
//do some stuff
}
e.preventDefault();
});
You could probably use jQuery's .one() function for this. E.g.
$('#search_city').one('change', function() {
/* Your code */
});
The change event will only execute once.
you have a method called
storeCity(this.value, false)
on change event , this might be refreshing the page. check that out.
Also a word of warning - I'd not use e.preventDefault() on a CHANGE event (unless you really need to), as it can have some weird behaviour in some browsers. Usually that's just for CLICK events.