how to pass runtime parameters in jquery functions? - javascript

I m new to jquery. My requirement is to pass rowid(unique id of each record of a table) in a jquery function. I can get rowid only at runtime. so how can I bind click event to the tag whose id is this rowid.
Upd
Del
$(what to pass here).bind('click',function(ev) {
_operation(para1,para2); // function which is going to perfom action
ev.preventDefault();
return false;
});

get the id , and acording to id do what ever you want
$('a').on('click',function(){
var id = $(this).attr('id');
if(id == //what you want)
{
//function 1
}
else
{
//function 2
}
return false;
});

If there are any similarities between the IDs, you can use one of the attribute selectors such as:
ID contains
$('[id*="something"]')
ID begins with
$('[id^="something"]')
http://api.jquery.com/category/selectors/
A better approach would be to place all of the dynamically named anchors into a container, and then select on that:
<div id="container">
<a ...></a>
<a ...></a>
</div>
Then you would select all the child anchors:
$('#container > a').click(...);

It's hard to find a good selector from so few HTML code. Use a class on your markup if possible:
<a class="roww" href="javascript:void(0)" id="`string(rowid(Gatepass))`">Upd</a>
<a class="roww" href="javascript:void(0)" id="`string(rowid(Gatepass))`">Del</a>
then you can use $('.roww') to query your nodes.
Here's what you can do to get the id from the event handler:
function( ev ) {
//wrap the element with jQ:
var jel = $(this);
//Then access attributes with .attr() getter:
var id = jel.attr('id');
... //do whatever you want now.
... // there's a quicker alternative to get the id without jQuery, simply:
... // var id = this.id
}

if the id comes dynamically from the server, put inside the function the same id + hash for id selctor
$(what to pass here) => $("'#" + string(rowid(Gatepass)) + "'")

Related

Class not working jQuery

So I more than one dynamicly generated elements with the same class name that I am trying to check input for in jQuery. Instead of it letting me click on both, it is just letting me click the first element generated.
Ex: I click on item_1 and it returns the item_1 id, but when I click on item_2 it doesn't return anyting.
HTML
<div id="item_1" class="resp"></div>
<div id="item_2" class="resp"></div>
JS - Jquery
$(".resp").on("click",() =>{
var id = $(".resp").attr("id");
console.log('attempting toggle' + id);
});
Firstly, you have to use normal function instead of arrow function (to avoid missing the context). Secondly - use this keyword to refer to the actually clicked element.
$(".resp").on("click", function() {
console.log('attempting toggle ' + this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">A</div>
<div id="item_2" class="resp">B</div>
This is because .attr('id') returns the value of the id attribute of the first matched element in the set.
Instead, use an old school function for the handler so the this value is equal to the clicked div, then get its id:
$(".resp").on("click", function() {
var id = $(this).attr('id');
console.log('attempting toggle ' + id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">First</div>
<div id="item_2" class="resp">Second</div>
What you're doing here is referencing the classname to obtain the id. This gathers the id of the first classname, which isn't what you desire. What you need to do is use the this keyword to correctly obtain the id.
After removing the arrow function and changing the internal code a bit, it should look like this:
$(".resp").on("click", function() {
var id = this.id;
console.log('attempting toggle: ' + id);
});
Also make sure you've correctly installed JQuery. Pick up your JQuery embed code from here.
Also remember to include your JQuery code before your JavaScript code.

Making part of an Id name into a variable

I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});

Modify class defined by var on a function

I want to add class "unblock" to all elements contanining desbloquear var value (in this case, taken from clicked a element's id).
I am not able to do this... as there are several ements that should receive the new class, I can not set the same id to them (to be equal as "a" id). How could I say, on the last line of the function, that all items containing "a" class (desbloquear var value) should add class unblock?
I've tried
$(.desbloquear).addClass('unblock');
and
$(".desbloquear").addClass('unblock');
without result...
$('a').on('click', unblock);
function unblock(){
var desbloquear = $(this).attr('id');
$(desbloquear).addClass('unblock');
}
all items containing "a" class (desbloquear var value) should add class unblock
I might not got your question correctly but by above line. It looks that you want to add a class unblock to elements those have some specific class. if yes then you can do like this
function unblock(){
var desbloquear = $(this).attr('class');
$('.'+ desbloquear).addClass('unblock');
}
Yes you are correct, Id's should be unique, you can use class instead
You will need a . to specify a class attribute in selector
$('.'+desbloquear).addClass('unblock');
class selector should begins with a .
Just try,
$('.' + desbloquear).addClass('unblock');
Full code:
$('a').on('click', unblock);
function unblock() {
var desbloquear = $(this).attr('id');
$('.' + desbloquear).addClass('unblock');
}

Get DIV ID where Class is selected?

I currently have the following:
$(window).load(function(){
$(".boxdiv").click(function () {
$(this).toggleClass("selected");
});
});
Which perfectly does the first part of what I need. I have a fair amount of div's with the class "boxdiv" and they each have a unique ID that will identify it. What I need to happen is to have some kind of button that when pressed sends all of these div ID's with the class selected, to the next page.
Anyone got any idea of how I can do this?
Map the ID's in an array, and use $.param to create a querystring
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;});
window.location.href = '/next_page?' + $.param({ids : id_arr});
});
EDIT:
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
window.location.href = '/next_page?ids=' + qs;
});
Perhaps this is what you're looking for:
$(".button").click(function(){
var id_arr = [];
$(".boxdiv").each(function(){ // Loop through each element with that class
id_arr.push($(this).attr('id'));
}); // Loop through each element with that class
});
window.location = 'next.html/ID=' + id_arr.join(',');
The ID's should be stored in id_arr
You can loop over each div that has the class selected. You can then use attr() to access the ID names.
Javascript
var ids = [];
$.each($(".selected"), function() {
ids.push($(this).attr('id'));
});
ids = ids.join(',');
HTML
<div id="boxA"></div>
<div id="boxB" class="selected"></div>
<div id="boxC" class="selected"></div>
<div id="boxD"></div>
This should return ["boxB", "boxC"]
See: http://jsfiddle.net/B4V28/1/
All of the answers submitted are in fact correct - but I think the real issue is your expectation of what jQuery is doing for you.
jQuery will gather all of the ID's in any manner, but you will need to have a way to collect them on the next page and actually do something with them. This will all need to happen server side.
Most likely, the ideal method, based on your comment of "potentially there could be many" you would want to do a mapping (see other answers), and pass the json object to your server, where it can pass it to the next page.
With the same code -
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
alert('/next_page?ids=' + qs);
});
Here is a fiddle for you - http://jsfiddle.net/kellyjandrews/4dYfh/

Get the id of the clicked-upon div

I want to select the id of the current div when I click on it in jQuery.
For example, say I have HTML like this:
<div class="item" id="10">hello world</div>
<div class="item_10">hello people</div>
When I click on the first div on .item class, I want to copy the id of the current div + adding to it the number (10), so it will be ("div id" + 10) equal to the second dev class = item_10.
I tried to use currentid = this.id; but it doesnt work :( !
First, note that id attributes starting with numbers are syntactically illegal in HTML4. If you're using id="10" make sure that you're using the HTML5 doctype (<!DOCTYPE html>).
It's hard to say why what you were doing didn't work without seeing your actual code. Presumably it is because you were registering for the event on a higher element (like the body) and this.id was the id of that higher element and not the element you clicked on.
In this case, you want to use the target property of the event to find what you clicked on. For example:
$(document.body).click(function(evt){
var clicked = evt.target;
var currentID = clicked.id || "No ID!";
$(clicked).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/
If you were registering on the specific elements instead, then this.id does work:
$('div').click(function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/1/
This is sub-ideal, however, because:
It makes many event handler registrations instead of 1, and
If additional divs are added to the document after this code is run, they will not be processed.
Under jQuery 1.7, you use the .on method to create a single event handler on a parent element with selectors for the kinds of elements you want to catch the event on, and have this set to them. In code:
$(document.body).on('click','div',function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/2/
I think you're trying to do something like:
$(".item").click(function(){
var id = $(this).attr("id");
var el = $(".item_" + id);
});
Now el is your second div.
You can simply use this.id
$('div').click(function() {
var divid = this.id;
alert($('.item_'+divid).html());
});
Demo
Something like this?:
$('div').click(function() {
theId = $(this).attr('id');
//Do whatever you want with theId.
});
This can be done as:
$('.item').click(function() {
var divId = $(this).attr("id");
});

Categories