How to generate dynamically events in jquery? - javascript

I'm trying to set event attributes on a group of drop-down generated dynamically but for some reason the events aren't working.
Heres's my code.
$(document).ready(function () {
var idRoomTypesList = $("#idRoomTypesList").attr('value').split("_");
for (var i = 0; i < idRoomTypesList.length; i++) {
$("#roomTypeID-" + idRoomTypesList[i] + "_nRentedRooms").attr("onchange", generatePrice);
}
});
var generatePrice = function () {
alert(this.value().toString());
}

I think this must work for you
$(document).ready(function () {
var idRoomTypesList = $("#idRoomTypesList").attr('value').split("_");
for (var i = 0; i < idRoomTypesList.length; i++) {
$("#roomTypeID-" + idRoomTypesList[i] + "_nRentedRooms").on("change", generatePrice);
}
});
var generatePrice = function () {
alert($(this).val());
}
And have a look at this:
How to use the jQuery Selector in this web application?

HTML:
<select class="dynamicSelects">
....
</select>
JS:
var generatePrice = function () {
alert(this.value);
};
$(document).ready(function () {
$('body').on('change', '.dynamicSelects', generatePrice);
});
This is an example of using the on method provided by jQuery and delegating the events. This means that even if those drop downs are not in the DOM yet you can still attach the event to it and whenever they exist in the DOM the event will fire. It basically says attach these events to body but fire on elements with the class dynamicSelects. This covers adding any other dynamically generated drop downs with this class later as well.
Setting attributes to attach events, while it may work, should really be done using the on method or in plain JS the addEventListener, in my opinion.
Also when operating on plain DOM elements the value property is not a function so no value() is needed. Just this.value. And you don't need to convert it to a string because value returns a string. If it were a jquery object then you can do $(this).val() which is a function.
I only suggest this change of course because if you are going to use a library like jQuery at least take advantage of the things it offers.

Did you search into the jQuery documentation?
$(document).ready(function () {
var $idRoomTypesList = $("#idRoomTypesList").attr('value').split("_");
for (var i = 0; i < idRoomTypesList.length; i++) {
$("#roomTypeID-" + idRoomTypesList[i] + "_nRentedRooms").attr("onchange", generatePrice);
}
$( "#idRoomTypesList" ).change(generatePrice());
});
var generatePrice = function () {
alert(this.value().toString());
}

Related

Change Click Function to hover (Vanilla Javascript)

I am using this code:
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("div#logo1").onclick = function(){
hideAllImages();
document.getElementById("01").style.display="block";
removeNavHighlight();
document.getElementById("div#logo1").classList.add("my_active");
};
document.getElementById("div#logo2").onclick = function(){
hideAllImages();
document.getElementById("02").style.display="block";
removeNavHighlight();
document.getElementById("div#logo2").classList.add("my_active");
};
document.getElementById("div#logo3").onclick = function(){
hideAllImages();
document.getElementById("03").style.display="block";
removeNavHighlight();
document.getElementById("div#logo3").classList.add("my_active");
};
function hideAllImages() {
var items = document.getElementsByClassName('changing_text');
var itemsLen = items.length;
for(var i = 0; i < itemsLen; i++) {
items[i].style.display="none";
}
}});
Which working fine with click event but I want to convert it to be functional when I hover to the element.
What this function must to: for example, when I hover on an image other element must appear and previous element must become hidden.
This is Vanilla Javascript code.
Any suggestions? tried to change .onclick to .onmouseover but not working.
It's not .mouseover it's .onmouseover
Is it working for you to replace .onclick by .onmouseover?
These functions are always in format on<event>. It should be .onmouseover as the other answers have already said. Note that you'd be using mouseover if you were adding an event listener using the addEventListener function.

Javascript Equivalent of Jquery

I am having problem in converting jquery to javascript as my application requirement is not to use jquery and only in plain html and javascript. I know how to write the code in Jquery but unable to convert it in javascript. My code is as follows
$(document).ready(function () {
$('input[type="button"').click(function () {
$(this).prop('disabled','disabled');
});
});
How to convert this code snippet to javascript.
Use window.onload to handle load-event on the window
document.querySelectorAll to select list of the elements within the document that match the specified group of selectors.
[].forEach.call to iterate through selected elements.
addEventListener to register the specified listener on the element.
window.onload = function() {
var elems = document.querySelectorAll('input[type="button"]');
[].forEach.call(elems, function(el) {
el.addEventListener('click', function() {
this.disabled = true;
});
});
};
Edit: document.addEventListener('DOMContentLoaded', function () {}); could be used instead of window.onload but consider Browser compatibility as well. Another easier alternate would be to place your <script> as last-child of <body> without wrapping your script in any load handler.
Use the DOMContentLoaded event as follow:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var btns = document.querySelectorAll("input[type=button]");
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
//Do stuff
console.log("button" + i + "clicked");
});
}
});

Convert jquery to javascript, call a function on href click

I am trying to write a pure JavaScript function (means no jquery).When a user clicks a link ( a tag) I wanted to run a javascript function. I Googled for a solution but did't find what I was looking for. Below is the jquery solution, I want a pure JavaScript event listener which listens to a href click. There is no id or class attached to tags. ex: <a href='xxxx'>xxxx</a>
This is what I have (using jquery)
$('a').click(function(e) {
var regExp = new RegExp('//'+location.hostname+'($|/)');
var href = $(this).attr('href');
if (regExp.test(href)) { e.preventDefault();
var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1];
activityFeedClick(event,i); } });
I need to convert the above jquery to javascript, basically I need to convert " $('a').click(function(e) " this to a pure JavaScript event listener.
Thanks.
Short answer:
var myFunction = function(e) {
var regExp = new RegExp('//'+location.hostname+'($|/)');
var href = this.href; // please notice this replacement here
if (regExp.test(href)) {
e.preventDefault();
var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1];
activityFeedClick(event,i);
}
}
var links = document.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', myFunction);
}
You can use "document.getElementsByTagName" to get a nodelist of all "a" elements in the DOM,
then loop through them and use "addEventListener".
This has the advantage of being supported in browsers without support for queryselector.
Add an onclick event on anchor tags like this.
click me

Unable to attach event listeners to dynamically created elements in IE8

OVERVIEW:
When I click a button i want to
insert a new row at the end of a table
copy the cells and contents from the first row of the table
give unique ids to the elements within the cells
assign a focus event listener to all inputs in the page.
PROBLEM:
The event handlers are not firing on the correct elements in IE8. For example if I focus on the last input in the table, the first input gets highlighted.
CLARIFICATION:
This works in IE10, Chrome.
Does not work in IE8 which is my target browser.
I know of ways
to get around this.My aim is NOT to find a workaround but to
understand what my mistake is, in the given code.
The example code is just a quick simplified version of the problem. I am not asking for code optimization thats not relevant to the question.
Change event does not work too.
CODE:
HTML:
<table width="200" border="1" id="myTable">
<tr>
<td>
<input type='text' id='row0col0' name='row0col0'>
</td>
</tr>
</table>
<button id="addRow">Add Row</button>
JS:
function addFocusListener() {
$("input").unbind();
$("input").each(function () {
var $this = $(this);
$this.focus(function () {
var newThis = $(this);
newThis.css('background-color', 'red');
});
});
}
function addRowWithIncrementedIDs() {
var table = document.getElementById("myTable");
var newRow = table.insertRow(-1);
var row = table.rows[0];
var rowNum = newRow.rowIndex;
for (var d = 0; d < row.cells.length; d++) {
var oldCell = row.cells[d];
newCell = oldCell.cloneNode(true);
newRow.appendChild(newCell);
for (var c = 0; c < newCell.childNodes.length; c++) {
var currElement = newCell.childNodes[c];
var id = "row" + rowNum + "col" + d;
$(currElement).attr('name', id);
$(currElement).attr('id', id);
}
}
}
$(document).ready(function () {
$("#addRow").click(function () {
addRowWithIncrementedIDs();
addFocusListener();
});
});
OTHER APPROACHES THAT WORK:
changing from jQuery binding to regular JS binding. I.e from
$this.focus(function () {....});
to
this.onfocus =function () {....};
Attaching the event handler as they are rendered.
FIDDLE:
http://jsfiddle.net/sajjansarkar/GJvvu/
RELATED LINKS IN SO:
jQuery event listener doesn't work in IE 7/8
EDIT
Sorry, I just noticed your comment that you want to understand the error in your code.
I can quickly tell you one error, and that is mixing jQuery and native DOM methods. If you have dedicated yourself to using a very powerful library, then use all of it's features, not just the ones you understand.
The below code uses event delegation (to fix your focusing problem) and jQuery methods to more simply add a row to the table than with native methods.
If you're going to use jQuery, then you might as well use it all the way:
var t = $('#myTable');
$(document)
.on('focus','#myTable input',function() {
$(this).css('background','red')
})
.on('click','#addRow',function() {
//create a new row
var
newIndex,
r = t.find('tr').eq(0).clone();
//append it to the table
r.appendTo(t);
//update newIndex - use it for later
newIndex = r.index();
//update the name/id of each of the inputs in the new row
r.find('input').each(function() {
var
el = $(this),
id = 'row'+newIndex+'col'+el.closest('td').index();
el.attr('id',id).attr('name',name);
});
});
http://jsfiddle.net/GJvvu/1/
You don't need to loop through your inputs and bind a focus handler to each of them, jQuery automatically collects all DOM elements that match the selector and performs it's focus API function on each of them:
Change this:
function addFocusListener() {
$("input").unbind();
$("input").each(function () {
var $this = $(this);
$this.focus(function () {
var newThis = $(this);
newThis.css('background-color', 'red');
});
});
}
To this
function addFocusListener() {
$('input')
.unbind()
.focus(function(){
$(this).css('background-color','red');
});
}
$("#addRow").live("click", function(){
addRowWithIncrementedIDs();
addFocusListener();
});
Try out above code... this should work..

No events for dynamically generated input tags

I have dynamically generated some input tags for a web application.
function FormElement () {
this.formElement = $('<div class="formElement"></div>');
this.formElement.append('<label for=""></label>');
this.formElement.append('<input type="text" />');
FormElement.prototype.addIds = function (id) {
this.formElement.find('label').attr({'for':id});
this.formElement.find('input').attr({'id':id});
return this.formElement;
};
FormElement.prototype.addLabelText = function (value) {
this.formElement.find('label').html(value);
};
FormElement.prototype.addInputValue = function (value) {
this.formElement.find('input').attr({'value':value});
};
FormElement.prototype.addClass = function (className) {
this.formElement.attr({'class':className});
};
FormElement.prototype.append = function (selector) {
$(selector).append(this.formElement);
};
}
The appended elements do not seem to have associated click, select etc.. events. I read you can you .on(). I would like to associate all possible events to all types of elements in a general way. What is the best way to go about this?
Suppose you want to assign a default behavior on click event for all inputs with a specific class, say 'foo':
$(document).on('click','input.foo', function(){
/* your function here */
});
If you don't go this way and try the following:
$('input.foo').click(function(){
/* your function here */
});
then the behavior will be added only to existing elements, not to those added after the script executed.
you have to use On() function on them
Attach an event handler function for one or more events to the selected elements.
$("button").on("click", 'selector',notify);
$("target").on("change",'selector', notify);
For dynamically generated element's you need event delegation -
$(document).on('change','.yourInputClass',function(){
var value = $(this).val();
});
http://api.jquery.com/on/

Categories