I'm working with Sharepoint and am creating a list with injected Javascript and JQuery. I'm trying to keep a field hidden unless the user selects "Deferred" or "Removed" from a field above with a dropdown. I want this to happen with an OnChange event, however, I believe this OnChange event should be within the OnLoad event.
Here's the code so far:
_spBodyOnLoadFunctionNames.push("myFunction");
function myFunction(){
$("h3.ms-standardheader:contains('Status Justification')".closest("tr").hide();
var StatusVal = $('select[id*=Status]').val();
if (StatusVal == 'Not Started' || StatusVal == 'Deferred'){
$("h3.ms-standardheader:contains('Status Justification')".closest("tr").show();
---THIS SHOULD ONLY HAPPEN ONCHANGE FOR STATUS DROPDOWN---
)
};
How can I use something like:
$('select'.on('change', function() {
alert($(this).find(":selected").val());
});
to make Status Justification only show when Status is changed to "deferred" or "removed"?
$('select').on('change', function() { // whenever values are changed in dropdown, this will be called.
if($(this).val() == 'deferred') { // example: run some code when value selected is 'deferred'
// code goes here...
}
});
And you need not have above code inside $(document).ready(function(){ ..
Related
The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse. Why is this?
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<script>
$(function() {
$(":input#single").change(function() {
/* Logic here does not execute when val() is used */
});
});
$("#single").val("Single2");
</script>
Because the change event requires an actual browser event initiated by the user instead of via javascript code.
Do this instead:
$("#single").val("Single2").trigger('change');
or
$("#single").val("Single2").change();
I believe you can manually trigger the change event with trigger():
$("#single").val("Single2").trigger('change');
Though why it doesn't fire automatically, I have no idea.
Adding this piece of code after the val() seems to work:
$(":input#single").trigger('change');
As far as I can read in API's. The event is only fired when the user clicks on an option.
http://api.jquery.com/change/
For select boxes, checkboxes, and
radio buttons, the event is fired
immediately when the user makes a
selection with the mouse, but for the
other element types the event is
deferred until the element loses
focus.
To make it easier, add a custom function and call it whenever you want to change the value and also trigger a change:
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTrigger("NewValue");
Or you can override the val() function to always call the change when val() is called:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
In case you don't want to mix up with default change event you can provide your custom event
$('input.test').on('value_changed', function(e){
console.log('value changed to '+$(this).val());
});
to trigger the event on value set, you can do
$('input.test').val('I am a new value').trigger('value_changed');
If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:
window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);
I ran into the same issue while using CMB2 with Wordpress and wanted to hook into the change event of a file upload metabox.
So in case you're not able to modify the code that invokes the change (in this case the CMB2 script), use the code below.
The trigger is being invoked AFTER the value is set, otherwise your change eventHandler will work, but the value will be the previous one, not the one being set.
Here's the code i use:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
if (arguments.length >= 1) {
// setter invoked, do processing
return originalVal.call(this, value).trigger('change');
}
//getter invoked do processing
return originalVal.call(this);
};
})(jQuery);
$(":input#single").trigger('change');
This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this
$('#machineMake').val('<?php echo $_GET['headMake']; ?>').trigger('change');
And the first event worked.
To change the value
$("#single").val("Single2");
Also to trigger a change event
$("#single").val("Single2").change();
this logic is instrumental when multiple select options are on a page.
one changes and other select options have to change but do not trigger a change event.
I used two dropdown list
I wish that when the user selects 2 in the first list then the following script is executed:
$('select[name="service"]').change(function(){
$('#modal-hs').show();
});
JSFiddle
I tried to execute several things like:
$('select[name="service"]').on('change', function (e){...});
or
$('select[name="service"]').trigger('change', function() { .. });
But it is not working.
Modify your $('select[name="reason"]').change handler like this:
// ...
if ($(this).val() == "2") {
$('#add-status').show();
$('select[name="service"]>option:eq(1)').prop('selected', true);
$('select[name="service"]').prop('disabled', true);
// Trigger the change event
$('select[name="service"]').trigger('change');
}
Here is updated JSFiddle: https://jsfiddle.net/6gerwaf8/2/
The reason why you have to trigger the change event manually is because the change event requires an actual browser event initiated by the user.
Do you mean this?
if ($(this).val() == "2") {
$('#add-status').show();
$('select[name="service"]>option:eq(1)').prop('selected', true);
$('select[name="service"]').prop('disabled', true);
$('select[name="service"]').trigger("change");
}
Is there any event, to append to the following listener, that will tell me if a radio button is already clicked?
var budgetType;
$(document).on('change', 'input[name="import_export"]', function() {
console.log($(this))
budgetType = $(this).val();
});
My problem is that, on page reload, if the radio box is already checked, the change listener won't work, and I didn't find any listener that will help me with that issue.
Any ideas?
Update
I'm aware that I could write an if/else syntax and see which is checked, but I was wondering if there is any other listener that I could append to change one, and avoid writing that extra syntax.
http://jsfiddle.net/S93XB/1/
$('input[type=radio]').is(':checked')
Try this code here: http://jsfiddle.net/afzaal_ahmad_zeeshan/rU2Fc/
or try this one
$('input[type=radio]').prop('checked', true);
Try this code here: http://jsfiddle.net/afzaal_ahmad_zeeshan/rU2Fc/1/
It will work, you can execute this onload to get the first value and use it in an if else block.
Trigger the change event on load:
var budgetType;
$(document).on('change', 'input[name="import_export"]', function() {
var isChecked = $(this).is(":checked");
console.log($(this).val()+" "+isChecked);
budgetType = $(this).val();
});
$('input[name="import_export"]:checked').trigger('change');
http://jsfiddle.net/eLGaB/
Try this :
$('input[type=radio]').is(':checked')
Or
$('input[type=radio]').prop('checked') === true;
Or
$('input[type=radio]').attr('checked') === 'checked';
I have this jQuery script that works fine:
$("select").change(function () {
var finalPrice = 0;
$("select option:selected").each(function () {
if ($.cookie('descuentoGen') != null){
finalPrice = Math.floor(precios[$(this).index()]*$.cookie('descuentoGen'));
} else{
finalPrice = precios[$(this).index()];
}
});
$("#precioFinal").text(finalPrice);
})
.trigger('change');
As you can see, it simply does some action when the user selects another option in the select.
Now, in a different script I'm calling this:
document.getElementById('selectFoods').selectedIndex = t;
This works as it should since it actually changes the selected option, the problem is, that why I change the selected option this way, the actions from the initial jQuery script are not executed.
Is there any way around this or will I have to duplicate the jQuery script behaviour in the other script?
Just try this
$('#selectFoods').prop('selectedIndex', t).change();
DEMO
Using selectedIndex will not trigger a change event. You've to trigger it by yourself.
I think you will have to trigger the event yourself, as i could know there's no a listener that tracks every select box's selectedIndex so that when selectedIndex changes the js engine could trigger the event. that is to say, it is the default change() behavior that changes the selectedIndex, but not contrary.
This seems like a simple thing but google hasn't turned up anything for me:
How can I bind to a text / value change event only, excluding an input gaining focus? Ie, given the following:
$(function(){
$('input#target').on('keyup', function(){
alert('Typed something in the input.');
});
});
...the alert would be triggered when the user tabs in and out of an element, whether they actually input text or not. How can you allow a user to keyboard navigate through the form without triggering the event unless they input/change the text in the text field?
Note: I'm showing a simplified version of a script, the reason for not using the change event is that in my real code I have a delay timer so that the event happens after the user stops typing for a second, without them having to change focus to trigger the event.
Store the value, and on any key event check if it's changed, like so:
$(function(){
$('input#target').on('keyup', function(){
if ($(this).data('val')!=this.value) {
alert('Typed something in the input.');
}
$(this).data('val', this.value);
});
});
FIDDLE
Simply use the .change event.
Update: If you want live change notifications then do you have to go through the keyup event, which means that you need to program your handler to ignore those keys that will not result in the value being modified.
You can implement this with a whitelist of key codes that are ignored, but it could get ugly: pressing Del results in the value being changed, unless the cursor is positioned at the end of the input in which case it does not, unless there happens to be a selected range in the input in which case it does.
Another way which I personally find more sane if not as "pure" is to program your handler to remember the old value of the element and only react if it has changed.
$(function() {
// for each input element we are interested in
$("input").each(function () {
// set a property on the element to remember the old value,
// which is initially unknown
this.oldValue = null;
}).focus(function() {
// this condition is true just once, at the time we
// initialize oldValue to start tracking changes
if (this.oldValue === null) {
this.oldValue = this.value;
}
}).keyup(function() {
// if no change, nothing to do
if (this.oldValue == this.value) {
return;
}
// update the cached old value and do your stuff
this.oldValue = this.value;
alert("value changed on " + this.className);
});
});
If you do not want to set properties directly on the DOM element (really, there's nothing wrong with it) then you could substitute $(this).data("oldValue") for this.oldValue whenever it appears. This will technically have the drawback of making the code slower, but I don't believe anyone will notice.
See it in action.
This will do it, set a custom attribute and check against that:
$('input').focus(function(){
$(this).attr('originalvalue',$(this).val());
});
$('input').on('keyup',function(){
if($(this).val()===$(this).attr('originalvalue')) return;
alert('he must\'ve typed something.');
});
Be wary of events firing multiple times.
Here is another version that plainly tests if the input field is empty.
If the input is empty then the action is not performed.
$(function(){
$(selector).on('keyup', function(){
if ($(this).val()!='') {
alert('char was entered');
}
})
});