I've got a JS function that edits fill inputs' values.
I'm fetching the input's value by an ID that is the parameter of the function and the functions is called on click.
My problem is that when I click to edit the first input, it works, but then I want to edit the third one.. it edits the first and the third one?
How can I reset my functions to only edit the third ?
Here's my JS function
function editTicket(id) {
let toEdit = id;
document.getElementById("inputRow" + toEdit).style.backgroundColor = "#6C63FF";
document.getElementById("inputRow" + toEdit).style.color = "#fff";
$("#imgtoCenter").click(function (e) {
var offset = $("#imgtoCenter").offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
sessionStorage.removeItem('x' + toEdit);
sessionStorage.removeItem('y' + toEdit);
document.getElementById("inputRow" + toEdit).style.backgroundColor = "#fff";
document.getElementById("inputRow" + toEdit).style.color = "#000";
sessionStorage.setItem('x' + toEdit, Math.round(relativeX));
sessionStorage.setItem('y' + toEdit, Math.round(relativeY));
document.getElementById("x" + toEdit).value = sessionStorage.getItem('x' + toEdit);
document.getElementById("y" + toEdit).value = sessionStorage.getItem('y' + toEdit);
});
}
If I console.log(id), I've got the value of my last click and the new one.
Thanks.. !
From jQuery click documentation
Additional Notes:
As the .click() method is just a shorthand for .on( "click", handler ), detaching >is possible using .off( "click" ).
Each time you're calling editTicket method, you're attaching a click event on #imgtoCenter element. All theses click events accumulate on the element, and when you're clicking on #imgtoCenter, all the handlers are fired with the previous ids they kept.
Just $("#imgtoCenter").off('click') at the end of editTicket method.
Related
I have a div that I append with the following code:
function generateBall(){
var colors = ["fe0ba5", "00c0ff", "21f1a5", "f13e21", "e819fb", "3ae319", "ff9900", "512e5e", "284184"];
var width = $('.reaction_area').width() - 40;
var height = $('.reaction_area').height() - 40;
var a = Math.floor(Math.random()*(width - 40 + 1) + 40);
var b = Math.floor(Math.random()*(height - 40 + 1) + 40);
var size = Math.floor(Math.random()*(32 - 24 + 1) + 24);
var color = colors[Math.floor(Math.random() * colors.length)];
$('.reaction_area').append('<div class="ball_2" style="left: '+a+'px; top: '+b+'px; height: '+size+'px; width: '+size+'px; background: #'+color+'" data-id="'+wave+'"></div>');
}
And then I have this:
$('.ball_2').on('click', function(){
$(this).remove();
wave--;
});
And it's not working. I have other elements that I append like that and clicking them works, why this doesn't?
I've tried also with $('document').on('click', '.ball_2', function(){ //code }); and it didn't work either.
That would be $(document) (without the quotes).
$('.ball_2').on('click', ...) doesn't work because the element .ball_2 doesn't exist yet at the time of execution. However, $(document).on('click', '.ball_2', ...) works because it puts the handler on an ancestor element and takes advantage of a phenomenon called "event bubbling". In simple terms, an ancestor is considered clicked when a descendant is clicked.
Since element with class ball_2 is generated dynamically.
$(document).on('click','.ball_2', function(){
$(this).remove();
wave--;
});
add following line in generateBall() function. Because the div is created dynamically, so we should bind the function when it being create. And this statement can let every '.ball_2' got it own remove function, assume there may be more than one '.ball_2'.
$('.ball_2:last').on('click', function(){$(this).remove());});
use delegate :
$('.reaction_area').delegate('.ball_2', 'click', function (event) {
$(this).remove();
wave--;
});
What I am trying to do is to call a function every time a person scrolls that checks the current class of container and adds +1 to the current value of the current data attribute and then toggles the class relative to the data attribute it is currently changing the class on scroll but giving a "NaN. I am already running this function on click and it works fine.
here is a fiddle.
http://jsfiddle.net/kaL63/1/
This is my function on scroll
var timeout;
$(window).scroll(function() {
if(typeof timeout == "number") {
window.clearTimeout(timeout);
delete timeout;
}
timeout = window.setTimeout( check, 100);
});
My html Looks like this
<div class="container year-1987" data-year-index="1987">
Some Content
</div>
the function I am calling right now that I think should work..
function check(){
var
animationHolder = $('.container'),
currentClass = animationHolder.attr("class").match(/year[\w-]*\b/);
var goToYear = $('.container').data('year-index');
var goToYear2 = parseInt(goToYear,1000) + 1;
animationHolder.toggleClass(currentClass + ' year-' + goToYear2);
animationHolder.attr('data-year-index', goToYear2);
}
My working code on click
$("a").click(function (e) {
e.preventDefault();
var
animationHolder = $('.container'),
currentClass = animationHolder.attr("class").match(/year[\w-]*\b/);
var goToYear = $(this).data('year-index');
animationHolder.toggleClass(currentClass + ' year-' + goToYear);
animationHolder.attr('data-year-index', goToYear);
I rewrote your check method:
function check() {
var $container = $('.container'),
currentYear = $container.data('m-index'),
nextYear = 1 + currentYear;
$container.removeClass('m-' + currentYear).addClass('m-' + nextYear);
$container.data('m-index', nextYear);
}
I made the following changes:
There is no need for the regular expression since we can generate the class name ourselves.
I am not sure why you were originally using two separate data-attributes (m-index and year-index), but I switched them to both match. If you need both of them, some more logic is needed to use year-index after the initial call.
I am now updating m-index via .data() rather than setting a data attribute.
This method seemed to work fine for me.
The is(:focus) was the aproach. The final code is listed below:
setInterval(function(){
if($j("SELECT[name='cf20_field_7']").is(":focus")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").val();
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
hovered = true;
}
,100
);
Is there some possibility to fire function when there is no hover in SELECT field.
And also there may be aproach that to check is there is no hover on SELECT field.
It cause problemms. When you are trying to select another option cursor is begging while setInterval is working.
The best approach that i find is listed below:
//every 100 mil secconds update info
setInterval(function(){
$j("SELECT[name='cf20_field_7']").trigger('change');
if ( $j("SELECT[name='cf20_field_7']").on("change")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").attr("value");
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
}
,100
);
More information:
I can discribe situation more. So i had a form. onsubmit event didn`t work because there is another event is attachet. So i deside to update value of first field of form every 100 milisecs. The value is containing all dynamictly created "selects and inputs". But when i try to change value of the select by mouse. The function is fired and function check value of select and cause mouse begging. So i need somehow to check if that select is hovered to prevent firing of the function.
Invalid here:
if ( SELECT[name='cf20_field_7'].on("change"))
I guess you need this:
if ( $("SELECT[name='cf20_field_7']").on("change"))
But still, the above is invalid. You need some handler like:
$("SELECT[name='cf20_field_7']").on("change", function(){
return false;
});
if ($j("SELECT[name='cf20_field_7']").on("change")) return false
Not clear what should be checked here. I assume you want to run some function attached to onchange even of select. In that case you should use .trigger instead of .on. But in both cases return value will be jquery object (for chaining purposes) so basically your statement will always be true both with trigger and on If you want to test some value of select, you should do something like next:
if(someTestFunct($j("SELECT[name='cf20_field_7']"))) return false;
function someTestFunct(jObj) {
//some other code?
return jObj.val() == "some value to test";
}
Possibly some better approach may be used, but without more details it is hard to suggest something.
The function savefromtextarea() & varialbe globe is undefined wen called on click of save button...
This one part of my code...I need to access the save from texarea method when clicked on the save text button...when I try to invoke the saveFromTextArea method its throws globe is undefined but globe variable is global variable ...
ME.ZFP.annotaion.Text = function () { //function to annotate the text
var canvas = myscreen.getTempCanvas().ele;
var context = canvas[0].getContext('2d');
var global = this;
$(canvas).mousedown(function(e){ //on mouse down event
if ($('#textAreaPopUp').length === 0) {
var mouseX = e.pageX - this.offsetLeft + $(canvas).position().left;
var mouseY = e.pageY - this.offsetTop;
//append a text area box to the canvas where the user clicked to enter in a comment
var textArea = "<div id='textAreaPopUp' style='position:absolute;top:"+mouseY+"px;left:"+mouseX+"px;z-index:30;'><input type='text' id='textareaTest' ></input>";
//Click on save buttom global.saveTextFromArea undefined
var saveButton = "<input type='button' value='save' id='saveText' onclick='global.saveTextFromArea("+mouseY+","+mouseX+");'></div>";
var appendString = textArea + saveButton;
$("#container").append(appendString);
}
});
//Function to be called
this.saveTextFromArea = function(y,x){
//get the value of the textarea then destroy it and the save button
var text = $('textarea#textareaTest').val();
$('textarea#textareaTest').remove();
$('#saveText').remove();
$('#textAreaPopUp').remove();
}
}
Thanks
Ajain
An inline event handler like your onclick='...' can only reference globally scoped variables and functions, but if your variable named global is declared inside a function (inside a document.ready handler, for example) then it is not global and the inline attribute event handler can't see it.
Well your code has some errors, fixed in this fiddle.
You forgot }); at the very end of the code.
Lastly (nitpicking) I corrected:
if ($('#textAreaPopUp').length == 0) to
if ($('#textAreaPopUp').length === 0)
But.. does this corrected code fix your problem?
i am using this plugin
Now i am doing a way to clone the select dropdown. A button to add cloned divs.
So, an user have a initial dropdown, but he can add more. The div is cloned.
The main problem is that when i clone the div, the dropdown is associated to initial dropdown and no to the new, that is cloned. The result is: all dropdowns of the new cloned divs have the event to open the select associated to the first.
Script to call the plug in
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(".mydds").msDropDown();
})
</script>
script to clone
<script type="text/javascript">
$(document).ready(function() {
$('#adicionar').live('click', function(){
var num = $('.linguas').length;
var newNum = new Number(num + 1);
var newElem = $('#copiar' + num).clone(true).prop('id', 'copiar' + newNum);
newElem.children(':text').prop('name', "myformdata[languages" + newNum + "]").prop('languages', 'languages' + newNum).val('');
$('#copiar' + num).after(newElem);
$('#apagar').prop('disabled', '');
});
</script>
Any idea to solve the problem?
Basically i think the event associated to dropdown is not copied...
thanks
Assuming you have only one dropdown per cloned element, you can use
$('#adicionar').live('click', function(){
var num = $('.linguas').length;
var newNum = new Number(num + 1);
var newElem = $('#copiar' + num).clone(true, true).attr('id', 'copiar' + newNum);
var id = newElem.find('select').msDropDown().data('dd').get('id');
newElem.find('[id]').each(function(){
$(this).attr('id',this.id.replace(id,'customid_' + newNum,'g') );
});
$('#copiar' + num).after(newElem);
newElem.find('select').msDropDown();
});
The problem is that the plugin gives an id to the initial select element, and uses that id to create other elements and also to refer to its related select.
You will need to modify all those ids as well as the reference.. (the code above does just that..)
demo http://jsfiddle.net/gaby/CXBZR/3/
In your script you are calling .clone(true). This true parameter is cloning the events and data.
From the API
.clone( [ withDataAndEvents ] )
withDataAndEvents: A Boolean indicating
whether event handlers should be
copied along with the elements. As of
jQuery 1.4, element data will be
copied as well.
If you remove this, or set it to false, this will stop the events from being cloned onto your new divs.