I set field value w/ javascript, onchange not triggered. Alternative solution? - javascript

I have read some solutions to this, none of which are hassle free, so I thought maybe some modern solution now exist to remedy this. It should anyways, since the problem has been around for a while. Something in the more recent jQuery updates perhaaps?
I set my form field like this:
parent.window.document.getElementById(parent.window.imageInputField).value = '{{ path }}'+image;
and I have an onchange event like this that I would like to fire upon my field update as of above.
$('#data_1').change(function(){
img = "url(" + $('#data_1').val() + ")"
$('#slide_bg').css("backgroundImage", img );
});
UPDATE
so this code works fine:
alert( $('#'+parent.window.imageInputField, window.parent.document).val() );
while this doesn't do anything, no error or nothing
$('#'+parent.window.imageInputField, window.parent.document).change();
The change event is defined here
$('#data_1').change(function(){
alert('change event called');
img = "url(" + $('#data_1').val() + ")"
$('#slide_bg').css("backgroundImage", img );
});
and this works perfect:
<input type='button' value='Uppdatera förhandsgr.' onclick="$('#data_1').change()" />
All I want is to trigger what this button does, but by code... anyone see where I went wrong?

you need to trigger the change handler with your code. Updating a value with script will not trigger change event
parent.window.document.getElementById(parent.window.imageInputField).value = '{{ path }}'+image;
$('#data_1').change()

Related

blur event doesn't trigger at first attempt

I'm trying to update the DOM based on the value entered in a text box.
HTML:
<input id="event-name" type="text"/>
JQUERY:
$('#event-name').on('blur',function(){
$.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
//my code here
});
});
this works on the first blur in Chrome. When I tried it in opera, mozilla and edge it doesn't worked on the first attempt.
It worked when I added this before the jquery.
$("#event-name").focus();
$("#event-name").blur();
$("#event-name").focus();
I did this to make the first $.post call to occur when the page opens.
Why is this problem happening?
How to solve this in a proper way?
Please help!
You can try this code:
var lazyTriggerEvent = function(id,event,callback){
var searchTrigger=null;
$("#"+id).bind(event,function(){
var text = $.trim($(this).val());
clearTimeout(searchTrigger);
searchTrigger = setTimeout(function(){
callback(text);
},500);
})
};
//use keyup event
lazyTriggerEvent("event-name","keyup",function(){})
It often happens with elements across browsers that consequent events do not work when binding an event to them through ID or class. The following solution should help you:
$(document).on('blur','#event-name', function(){
$.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
//my code here
});
});
Alternatively, you could use keyup event. You can do so following:
$(document).on('keyup','#event-name', function(){
var eventName = $(this).val();
$.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
//my code here
});
});
Also, using - in IDs is not a good approach. Rather, either stick to camelCase or underscore_format of naming convention.

Change event action based on other event

Is there a generally accepted method to change the action of a JavaScript event?
The following seems clean, but doesn't work as the first event is bound to #link when the page is rendered, and nothing changes when the class changes. Does it sound like I understand this correctly?
$('#change-to-option-1').click(function(){$('#link').attr('class','option-1');});
$('#change-to-option-2').click(function(){$('#link').attr('class','option-2');});
$('.option-1').click(function(){alert('option 1');});
$('.option-2').click(function(){alert('option 2');});
Option 1
Option 2
Click Me
Or should I have one event, and put logic in it based on the element's class (or maybe data()) instead as shown?
$('#link').click(function(){
if( ('#link').attr('class')=='option-1') {alert('option 1');}
else{alert('option 2');}
});
Or is there a generally more accepted approach?
If you want to make an event trigger for an element after changing its class/any identity that you used to bind the event initially. Then you have to go for event delegation.
$(document).on("click", ".option-1", function(){ alert('option 1'); });
You can expect the code to be optimized if you use any closest static parent of .option-1 instead of document
I would not recommend and prefer hardcoding anything. So here's a solution which would take care of what you are trying to do.
$('#change-to-option-1,#change-to-option-2').click(function(){
$('#link').attr('class',this.id.split('-')[2] + '-' + this.id.split('-')[3]);
});
$('#link').on('click',$(this).attr("class"), function()
{
alert($(this).attr("class"));
});
Working example : https://jsfiddle.net/DinoMyte/39fvpstq/
If you plan to introduce more anchor links with a similar id structure :
$('[id^=change-to-option-]').click(function(){
$('#link').attr('class',this.id.split('-')[2] + '-' + this.id.split('-')[3]);
});
$('#link').on('click',$(this).attr("class"), function()
{
alert($(this).attr("class"));
});
Working example : https://jsfiddle.net/DinoMyte/39fvpstq/1/
If you wish to put everything in one event block :
$('#change-to-option-1,#change-to-option-2').click(function(){
$('#link').unbind('click');
$('#link').attr('class',this.id.split('-')[2] + '-' + this.id.split('-')[3]).on('click',$(this).attr("class"), function()
{ alert($(this).attr("class"));
});
});
Example : https://jsfiddle.net/DinoMyte/39fvpstq/2/

Google Polymer listening for fire event never happens

Putting together the not fully working examples from here https://www.polymer-project.org/articles/communication.html#events
I am trying to get the addEventListener to work on a different component or dom element.
If I put the listener on the submitting component it will work but going from the example if I put it on a dom element nothing happens.
Having the listener on the sending element seems redundant.
I looked at data binding but I want to pass more data and really just want to build a library of working small demo bits I can reference when I need the different methods.
Thank you.
<body unresolved id="body">
<polymer-element name="say-hello" attributes="name" on-click="{{sayHi}}">
<template>Hello {{name}}!</template>
<script>
Polymer('say-hello', {
sayHi: function() {
console.log("sklngh");
this.fire('said-hello', {name: this.name});
}
});
</script>
</polymer-element>
<say-hello></say-hello>
<div id="container">zzz</div>
<script>
var container = document.querySelector('#container');
// var container = document.querySelector('say-hello');
container.addEventListener('said-hello', function(e) {
alert('outside: Said hi to ' + e.detail.name + ' from ' + e.target.localName);
});
</script>
</body>
Edit
Ah it bubbles! Needed to wrap the component.
<div id="container">
<say-hello></say-hello>
</div>
See edit above. That seems to be the answer. Kazam.
To fire a custom event from the host element use the fire method. You can also pass in data to event handlers as an argument to fire.
Use this link:
https://www.polymer-project.org/1.0/docs/devguide/events

Onclick event on dynamic created anchor tag

I have an anchor tag which created dynamically and this anchor tag has an onclick event like this:
$('#'+educationHistoryId).append("<span>"+degreeTitle+"</span>" + "<a href='javascript:void(0)' onclick='deleteEducationLevel(" + educationHistoryId + ");'>Delete</a>");
when I click on this anchor I got js error saying:
TypeError: 'click' called on an object that does not implement interface HTMLElement.
I suspect some character escaping issue but unable to resolve.
Added
generated html:
<div id="ff8081814734be020147357beda5002b"><span>A Level</span><a onclick="deleteEducationLevel(ff8081814734be020147357beda5002b);" href="#">Delete</a></div>
Try replacing that line with the following, so that the event is bound like this:
var $link = $("<a href='javascript:void(0)'>Delete</a>");
$link.on("click", function() {
deleteEducationLevel(educationHistoryId);
});
$('#'+educationHistoryId).append("<span>"+degreeTitle+"</span>").append($link);
In my (very reduced) test, this seems to work: http://jsfiddle.net/E7LRt/
Is there an actual need to do this with just one line?
I'd suggest the following solution:
var $anchor = $(document.createElement("a")).attr("href","javascript:").text("Delete").on("click",function() {
alert("clicked!");
alert("educationHistoryId: " + educationHistoryId);
});
$("body").append("<span>" + degreeTitle + "</span> ",$anchor);
This works great: Fiddle
I always try to prevent using inline eventhandlers. It's bad practise in my opinion.
Give the span a class and use event delegation.
You can then bind the click event to a existing parent(I am assuming element with id= "#"+educationHistoryId is existing when the event handler attachment takes place) and then delegate the event to the newly added link.
$("#"+educationHistoryId).on("click", <class>, function(){
deleteEducationLevel(educationHistoryId);
});

Javascript: Receiving onClick on top of image inside a div, can it be done?

I basically have a div set up with an onClick action like so:
myDiv.setAttribute("onclick", myAction);
And later on, I place an image inside the div like this:
myDiv.innerHTML = '<img src="' + myImage + '" height="' + myDiv.height + '" width="' + myDiv.width + '">';
.width and . height are properties I have created for myDiv.
So my problem is that when I place the image inside the div, myDiv's onClick is not responding, is there anyway to solve this. I know of the div property backgroundImage, but that one does not support customizing of size in all browsers. I tried to give the image the same onClick action that the div has but that just got messy, is there any way to make javascript ignore the image and register a click in the div even though the click is in the image inside the div?
Visual explanation of the problem:
http://bildr.no/view/860258
Thank you.
Rather than overwriting the innerHTML of the div, why not do something like this?
var img = document.createElement('img');
img.setAttribute('src', myImage);
img.setAttribute('width', myDiv.width);
img.setAttribute('height', myDiv.height);
myDiv.appendChild(img);
First thing I thought of was Don't events bubble up? I started searching and turned up this. I think that might be an interresting read.
Yes, and what you're looking for is event propagation. A JS library like jQuery might be really helpful for something like this. jQuery uses a .live() function to accomplish event propagation.
For the given HTML:
<div class="imageWrap">
<img src="someimage.jpg">
</div>
You would use something like:
$(".imageWrap").live("click", function (event) {
// Do something awesome here
$(event.target).addClass("clicked");
});
The click on the image should "propagate" or bubble up to the div, where it can be caught and processed. Event bubbling is incredibly useful once you get the hang of how it works.
I found your issue.
Here is the fiddle: http://jsfiddle.net/maniator/gN4e9/
The issue is on this line: myDiv.setAttribute("onclick", myAction);
That is placing the whole myAction function into the onclick which you don't want.
Change it to: myDiv.setAttribute("onclick", 'myAction()'); and it should work fine.

Categories

Resources