how to fire event on label text change - javascript

I'm trying to fire a function when the label text changes. This is my code
$("#frameItemCode").change(function (e) {
alert("Changed");
});
#frameItemCode is my label id, but the event isn't firing. I have tried examples given before but they hasn't helped me.This is my html
<div class="input-group">
<span class="input-group-addon" #*style="width: 120px;"*#>Item Group</span>
<label class="input-group-addon" #*style="width: 120px;"*# id="frameGroupCode"></label>
<input class="form-control" type="text" id="frameGroupName" style="">
</div>

Take a look at the documentation for the change event. It only fires for specific types of elements:
The change event is fired for <input>, <select>, and <textarea> elements when a change to the element's value is committed by the user...
You won't be able to use the change event for an element that is not one of the previously mentioned types.
If you have some other way of knowing that editing has finished of a specific element, you'll have to fire your own event - possibly using the blur event on the element that was used to change the value. The blur event is triggered when the selected element looses focus such as when a user clicks (or tabs) out of an input element.

For label .change() will not work, So you can try something like this by using trigger() which call our custom event, here fnLabelChanged is my custom event
.change() event worked for <input> , <textarea> ,<select> .i.e
$("button").on('click',function(){
$("#frameGroupCode").text("Hello").trigger("fnLabelChanged");
});
$("#frameGroupCode").on('fnLabelChanged', function(){
console.log('changed');
})
Working Demo

You can get the current text of the label and check if the value is different on keyup or when pressing a button. The change event doesn't work for non form elements.

If you use, $("#frameItemCode").text('abc') to change the lable (as you commented), just call the alert("changed") after that. No need to define an event listener..
$("#frameItemCode").text('abc');
alert("changed");
If the label changes in several ways, define a timeInterval to check if the label has changed,
function inspectLabel(callback){
var label = $("#frameItemCode").text();
setInterval(function(){
var newlabel = $("#frameItemCode").text();
if (newlabel != label){
callback();
label = newlabel;
}
}, 100);
}
inspectLabel(function(){
alert('changed');
});

Depending on which browsers you need to support, you can use MutationObserver:
var observer = new MutationObserver(
function (mutations) {
alert('Label was changed!');
}
);
observer.observe(document.querySelector('#frameGroupCode'), { childList: true });
Example jsFiddle

I don't think label has change() event associated with it, if you want to achive it, then it can be done through JQuery or JS. Because changing label text dynamically is done through Jquery or JS.
Instead, you can create a function and call it when the label is being changed from your function where the lable text change takes place.

Related

How to undetect/ignore javascript events in a certain html element?

I have this line of code $('#tbl-purchase-list').on( 'keyup change', 'input[type="text"]' that detects the input of all input[type="text"] field. However, I have an input field that I dont want to be detected when inputting a text on the keyboard or make any changes on it.<input type="text" class="form-control purchase-freight-charge" id="purchase-freight-charge" value="" />. Is there a way in javascript that ignores certain events for a certain element? Something like this $("#purchase-freight-charge").ignoreEvents();? Please help. Thanks a lot.
Ofcourse there is a :not() Pseudo selector:
$('#tbl-purchase-list').on('keyup change',
'input[type="text"]:not(#purchase-freight-charge)',
...);
It will not add the target element in the matched set of selectors. So, there won't be any event for that element which is inside :not().
Event this can also be done:
$('#tbl-purchase-list').on('keyup change', 'input[type="text"]',function(ev){
if(this.id === "purchase-freight-charge"){
this.value = "";
}
});
You can use jQuery's event.stopImmediatePropagation():
$("#purchase-freight-charge").on('keyup change', function( event ) {
event.stopImmediatePropagation();
});
// Future event bindings won't be executed for #purchase-freight-charge
// ...

Why is jQuery select event listener triggering multiple times?

Please run this sample in Google Chrome browser.
Stack Snippet
$(function() {
$(":input").select(function() {
$("div").text("Something was selected").show().fadeOut(1000);
alert("Selected");
});
$("button").click(function() {
$(":input").select();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button>Click To Select</button>
<input type="text" value="Some text">
<div></div>
Here why jQuery select event listener is triggering multiple times? Does anyone know the reason behind this? And is there any workaround solution for this without using timeout?
The $(":input") selector is selecting the button too, so it causes recursion. Either use just $("input"), or $(":input:not(button)").
I noticed when the three events are fired, the first doesn't have originalEvent property, so we definitely can dismiss it, and the second two has very similar (however not identical) timestamp. You can store the last timestamp in some variable and in event listener compare it with the event's timestamp. If the rounded values of these two are the same, you can dismiss this event.
$(function() {
var lastTimeStamp;
$("input").select(function(event) {
if (!event.originalEvent ||
lastTimeStamp === Math.round(event.timeStamp)) return;
lastTimeStamp = Math.round(event.timeStamp);
$("div").text("Something was selected").show().fadeOut(1000);
alert("Selected");
});
$("button").click(function() {
$("input").select();
});
});
See updated JS Fiddle.
It appears the issue is a combination of:
the :input selector gets the input and the button, hence multiple events triggered.
even when using just input as the selector there is some odd event propagation being triggered on related elements which is raising the select event handler multiple times.
To avoid both of the above, use input as the selector and also use preventDefault() in the event handler. stopPropagation() may also be required, depending on your HTML stucture.
$(function() {
$('input').select(function(e) {
// e.stopPropagation(); // optional
e.preventDefault();
$('#message').text("Something was selected").show().fadeOut(1000);
console.log('Selected');
});
$('button').click(function() {
$('input').select();
});
});
Working example
UPDATE: We were all fooled. The select() function needs a prevent default.
Rory McCrossan figured it out. Well done mate.
Incidentally, I'm not sure what the benefit of select() actually is! Something like focus() or on('focus',) might make more sense. Not Sure what the context is however. The below still follows:
Why waste time using generalised tag/type selectors which may change? Use an ID, and pick out only the one you want.
If you want to detect multiple, use a class. If you want to use multiple, but figure out which one you clicked, use a class and an ID. Bind with the class, and identify using $this.attr('id').
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button>Click To Select</button>
<input type="text" value="Some text" id="pick-me">
<div></div>
$(function() {
$("#pick-me").select(function(event) {
event.preventDefault();
$("div").text("Something was selected").show().fadeOut(1000);
alert("Selected");
});
$("button").click(function() {
$("#pick-me").select();
});
});

Fire an event only when an focused element looses focus

This is my Fiddle JsFiddle
$(function() {
$('.glyphicon-edit').click(function () {
$(this).parent().find('.form-control').removeAttr("readonly").focus();
});
$('.form-control:focus').blur(function() {
$(this).addAttr("readonly");
});
});
What I am trying to do?
I am trying to create a dynamically editable form.It should have
When someone click on edit icon, the corresponding Input field should get focussed and become editable. (I completed this part).
Next i want is when an element is in focus state and it looses focus then i want to add readonly attribute again to that element. This part in not working. can somebody explain me why. and give a solution for it
EDIT:
In the later part i was trying alert("some msg") to check whether the event is getting fired or not. while posting i just replaced it with addAttr. it was a typo
You could use instead:
--DEMO--
$(function () {
$('.glyphicon-edit').click(function () {
$(this).parent().find('.form-control').prop("readonly", false).focus().one('blur', function () {
$(this).prop('readonly', true);
});
});
});
There is no addAttr() function. The setter for attr looks like this:
$('.form-control').blur(function() {
$(this).attr("readonly", true);
});
Also, the :focus psuedo selector here is redundant, as to fire the blur event the element has to have focus in the first place.

Toggle state of textbox with javascript using a button

I have a form as follows:
<form>
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock" onMouseDown="toggleInput()"></button>
</form>
And javascript code:
function toggleInput(){
if ($("#input").disabled){
$("#input").disabled = false;
}
else {
$("#input").disabled = true;
};
}
What I basically want to do is to check what state (enabled/disabled) the textbox is in, and then toggle the state accordingly. I don't know if the javascript portion even uses the correct syntax to check if the textbox is disabled, but it's what I could think of.
Thanks in advance!
EDIT: Reason as to why I've chosen to use onmousedown instead of onclick to execute the event with the button:
I have chosen to use onmousedown instead of onclick as it makes the app I'm building feel less clunky due to the presence of this feature with onclick: When you click on a button and then drag the cursor away from the button while holding the mouse button down, and subsequently lift your finger off the mouse button when the cursor is in an area away from the button on the webpage, the event will not be executed. Hence, I've chosen to use onmousedown as this is overcome.
Use .prop(), Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element
$("#input").prop('disabled',!$("#input").prop('disabled'))
DEMO
I am not sure why you are using onMouseDown. Use click instead
$("#lock").on("click", function() {
$("#input").prop('disabled',!$("#input").prop('disabled'))
});
DEMO with click
To do it with jQuery try this:
$("#input").prop("disabled", function(i, v) { return !v; });
Your existing code doesn't work because DOM elements have a .disabled property, but jQuery objects do not.
I'm not sure why you're using onmousedown instead of onclick for the button, but either way if you're going to use jQuery I'd recommend removing the inline event attribute in favour of binding the handler with jQuery:
$("#lock").on("click", function() {
$("#input").prop("disabled", function(i, v) { return !v; });
});
(You'd need to include that code either in a script block at the end of the body or in a document ready handler.)
Demo: http://jsfiddle.net/a7f8v/
You should append the event handler with jQuery instead of an onMouseDown event. The syntax could look like this:
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock"></button>
JavaScript:
$(document).ready(function() {
$("#lock").click(function() {
var input = $("#input");
input.prop('disabled',!input.is(':disabled'))
});
});
Example

Input:Checked jQuery vs CSS?

Unless I am mistaken. jQuery and CSS handle the :checked selector very differently. In CSS when I use :checked, styles are applied appropriately as I click around, but in jQuery it only seems to recognize what was originally in the DOM on page-load. Am I missing something?
Here is my Fiddle
In jQuery:
$('input:checked').click(function () {
$('input:checked').css('background','#FF0000');
$('input:checked+label').css('background','#ff0000');
});
In CSS:
input:checked+label {font-weight:bold;color:#5EAF1E}
UPDATE:
I should clarify that what I am looking to do is trigger behavior if a user clicks an already selected radio button.
Try setting up the handler this way:
$('body').on('click', 'input:checked', function() {
// ...
});
The way you have it, you're finding all the elements that are checked when that code runs. The above uses event bubbling so that the test is made when each "click" happens.
Inside your handler, you're updating the style for all checked elements, even though any particular click will only change one. That's not a huge deal if the number of checkboxes isn't too big.
edit — some further thought, and a helpful followup question, makes me realize that inside an event handler for a radio button "click" event, the button will always be ":checked". The value of the "checked" property is updated by the browser before the event is dispatched. (That'll be reversed if the default action of the event is prevented.)
I think it'll be necessary to add a class or use .data() to keep track of a shadow for the "checked" property. When a button is clicked, you'd see if your own flag is set; if so, that means the button was set before being clicked. If not, you set the flag. You'll also want to clear the flag of all like-named radio buttons.
You bound the event only to the inputs that were initially checked. Remove :checked from the first selector and it works as intended (but ugly.)
http://jsfiddle.net/8rDXd/19/
$('input').click(function () {
$('input:checked').css('background','#FF0000');
$('input:checked+label').css('background','#ff0000');
});
you would of course need to "undo" the css change you made with jQuery to make it go away when the input is unchecked.
$('input').click(function () {
$('input').css('background','').filter(":checked").css('background','#FF0000');
$('input+label').css('background','');
$('input:checked+label').css('background','#ff0000');
});
http://jsfiddle.net/8rDXd/20/
AFTER UPDATE
Keep track of the status of the radio buttons. For example, use .data() to keep an in-memory state of the radio buttons.
$(function () {
var $radio = $(":radio");
$radio.filter(":checked").data("checked", true);
$radio.on("click", function () {
if ($(this).data("checked")) {
alert("Already selected");
}
$radio.data("checked", false).filter(":checked").data("checked", true);
});
});
See it live here.
BEFORE UPDATE
I think you want to use .change() here.
$('input:radio').change(function () {
$('input, input+label').css('background', '');
$('input:checked, input:checked+label').css('background', '#f00');
}).change();
See it live here.

Categories

Resources