I have a html- input type="text", and I want to add this tag an event handler that will work when the text is changes. The problem is that this input is getting his value from antoher javascript function and then the event handler isn't working.
For example
This is the event:
$("#inputid").change(function(){
alert('bla bla')
}
And this what need to raise the event
function inputvalue(){
$("#inputid").val="bla"
}
Unfortunately when the value of the input is changing (from the function inputvalue),it doesn't raise the event. If I put the value of the input manually the event is working
Any idea why the javascript doesn't reconize the text change from a script?
You can trigger the change event yourself in the inputvalue function:
function inputvalue(){
$("#inputid").val("bla").change();
}
Also notice the correction of your syntax... in jQuery, val is a function that takes a string as a parameter. You can't assign to it as you are doing.
Here is an example fiddle showing the above in action.
Your function has an error. Try this:
function inputvalue(){
$("#inputid").val()="bla"
}
EDIT
My function is also wrong as pointed in comments.
The correct is:
Using pure javascript
function inputvalue(){
document.getElementById("inputid").value ="bla";
}
Using jQuery
function inputvalue(){
$("#inputid").val("bla");
}
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 have an input text and I want to run my function after the default event handler
<input type="text" onkeypress="myfunction()"></input>
the function
function myfunction(){alert($("input")[0].value)}
because myfunction() is using the input value and this property will be changed after the default handler runs and change it.
Example: if the text field has value "1234" , and I pressed the key "5", the function will alert "1234" not "12345"
So, I want the default function runs first to change the value property , then I can use it in myfunction()
can I do something like this ?!
onkeypress="default();myfunction()"
I did a work around by putting myfunction() in the onkeyup event, but I don't want that.
Thanks, and please consider I'm very newbie.
TRIVIAL SOLUTION:
You should use oninput instead of onkeypress. Like so:
<input type="text" oninput="myfunction(event)" />
The keypress event is emitted when a key gets pressed, i.e., before the DOM is modified with the pressed key's value. This is why you never got the value of the last key pressed.
The input event is emitted when data is entered into the input element. So we can access the data by reading the value of the element.
USING EVENT-BINDING:
HTML
<input id="input_field" type="text" />
jQuery
$(document).ready(function() {
$("#input_field").on("input", function() {
console.log($(this).val());
});
});
Pure JS
var input_field = document.getElementById("input_field");
input_field.addEventListener("input", function(event) {
console.log(event.target.value);
});
NOTE: Add this in a script tag after the HTML or use window.onload to simulate the behaviour of $(document).ready.
See this SO answer for more information about how event-binding works.
Is there some way to run a function when a input is disabled/enabled from another part of the code, for example when this code is run:
$('#myinput').prop('disabled', true);
I want another part of the code to be notified about this, but without making it dependent on the other part. Something similar to how "change" event works. But there's no "disabled" event...
You can call notification trigger in the next line with an if statement
document.getElementById("email").disabled=true;
if(document.getElementById("email").disabled == true)
{
alert("Notifying..");
//call the trigger function
}
There is no event that will trigger when those properties are changed.
You can do this some other way.
Set hidden field for this enable disabled value like 1 / 0
$("#hiddenid").trigger("hiddenidchange");
$("#hiddenid").on("hiddenidchange", function () {
});
refer How do I trigger an onChange event for a hidden field?
I can't seem to make onchange fire for an input type of file. If I directly call an alert (like onchange="alert('a')"), it fires but if I call a user-defined function with only an alert inside, it doesn't. see below:
the html:
<input type='file' value='C:\fakepath' onchange="previewFile()"/>
the script:
function previewFile() {
alert("a");
}
http://jsfiddle.net/vDQxj/276/
The reason that's not working is kind of an artifact of using JSFiddle. In the left panel, you specified to execute the JavaScript onLoad. You need to use the option No wrap - in < head > which is normally where you would place JS in a real HTML file. Change that option / check out this version of your fiddle with the option changed.
http://jsfiddle.net/pxsjjgx5/
Here is the answer for your question. Use jQuery for this and write your code in place of alert in my code.
$("input[type=file]").bind("change", function() {
alert();
});
I have a bit of JavaScript that builds some HTML for me and inserts it into a div. I am using jQuery 1.7.2 for this test.
I'm interested in attaching a custom change or keyup event handler on an input text field called gene_autocomplete_field.
Here's what I have tried so far.
The following function builds the HTML, which is inserted into a div called gene_container:
function buildGeneContainerHTML(count, arr) {
var html = "";
// ...
html += "<input type='text' size='20' value='' id='gene_autocomplete_field' name='gene_autocomplete_field' placeholder='Enter gene name...' /><br/>";
// ...
return html;
}
// ...
$('#gene_container').html( buildGeneContainerHTML(count, geneNameArr) );
In my calling HTML, I grab the gene_autocomplete_field from the gene_container element, and then I override the keyup event handler for gene_autocomplete_field:
<script>
$(document).ready(function() {
$("#gene_container input:[name=gene_autocomplete_field]").live('keyup', function(event) {
refreshGenePicker($("#gene_container input:[name=gene_autocomplete_field]").val());
});
});
</script>
When I change the text in gene_autocomplete_field, the refreshGenePicker() function just sends an alert:
function refreshGenePicker(val) {
alert(val);
}
Result
If I type any letter into the gene_autocomplete_field element, the event handler seems to call alert(val) an infinite number of times. I get one alert after another and the browser gets taken over by the dialog boxes. The value returned is correct, but I worry that refreshGenePicker() gets called over and over again. This is not correct behavior, I don't think.
Questions
How do I properly capture the keyup event once, so that I only handle a content change to the autocomplete field the one time?
Is there a different event I should use for this purpose?
UPDATE
It turns out that more than just a keyCode of 13 (Return/Enter) can be an issue — pressing Control, Alt, Esc or other special characters will trigger an event (but will be asymptomatic, as far as the infinite loop issue goes). The gene names I am filtering on do not have metacharacters in them. So I made use of an alphanumeric detection test to filter out non-alphanumeric characters from further event handling, which includes the Return key:
if (!alphaNumericCheck(event.keyCode)) return;
alert is called infinite times because you use the 'Enter' key to confirm/dismiss the alert. Use .on('change') instead. This will prevent refreshGenePicker from being called when you use enter in an alert.
JSFiddle demonstration using keyup (Click on OK to prevent infinite alerts).
JSFiddle demonstration using change
However, the 'change' event will only trigger if the input element looses focus. If you want to use refreshGenePicker on every key, use the following approach instead:
$("#gene_container input:[name=gene_autocomplete_field]").live('keyup', function(event) {
if(event.keyCode === 13) // filter ENTER
return;
refreshGenePicker($("#gene_container input:[name=gene_autocomplete_field]").val());
});
This will filter any incoming enter keyup events (jsFiddle demo). Also switch to .on and drop .live.
EDIT: Note that there are more possibilities to dismiss an alert modal, such as the escape or space key. You should add a check inside your refreshGenePicker whether the value has actually changed.
You should really use .on() if you are using jQuery > 1.7.
Check out the perftest.
And also check out my some what related question.
Also when testing equal you should really add quotes around it:
input:[name='gene_autocomplete_field']
To answer you real question :). It shouldn;t behave like that with the code you have presented. Maybe something else is wrong. Can you setup a jsfiddle with the issue?
Check out my demo and perhaps you see what's wrong with your code:
function refreshGenePicker(value) {
console.log('keyup! Value is now: ' + value);
}
(function($) {
var someHtml = '<input type="text" name="gene_autocomplete_field">';
$('body').append(someHtml);
$('body').on('keyup', 'input[name="gene_autocomplete_field"]', function(e) {
refreshGenePicker($(this).val());
});
})(jQuery);
$(document).ready(function() {
$('#test').html('<input id="text" />');
$('#text').keyup(function() {
console.log($(this).val());
});
});
This works just fine. Since you've got our second code block in <script> tags, you might be running it more than once - which would cause it to bind more than once and produce more than one alert each time it is bound. You could of course use .unbind() on that input before adding the keyup, but I think a much better solution would be to group all the code in a single $(document).ready(); to ensure you're only binding the object once.
http://jsfiddle.net/Ka7Ty/2/