Deconstructing javascript script - javascript

I'm new to javascript and I am trying to destruct the following so I can understand it. I can't seem to find the answer on the web. Is anyone able to help?
$("#modal-add-person").on('show.bs.modal', function (e) {
var personId = $(e.relatedTarget).attr('data-id');
$('#modal-add-person-hidden').val(personId);
$('#modal-add-person-id-text').html(personId);
});
Thanks

In you code you have eventHandler on $("#modal-add-person") .
It means that somewhere in you global code you are triggering 'show.bs.modal' event on
$("#modal-add-person") like this
$("#modal-add-person").trigger('show.bs.modal')
The function that is 2nd parameter of on function is eventHandler function that receive eventObject.
function (e) {
var personId = $(e.relatedTarget).attr('data-id');
$('#modal-add-person-hidden').val(personId);
$('#modal-add-person-id-text').html(personId);
}
It use relatedTarget property of event object and extract data-id attribute from it.
var personId = $(e.relatedTarget).attr('data-id');
After it set that value in $('#modal-add-person-hidden') - I guess it is hidden input.
$('#modal-add-person-id-text').html(personId);
And last thing it's do draw the value in $('#modal-add-person-id-text') element.
$('#modal-add-person-id-text').html(personId);
And also you should look at jQuery reference for elements, selectors and etc.

$("#modal-add-person").on('show.bs.modal', function (e) {
'show.bs.modal' would be a event in html as a click is. So the above statement means on 'show.bs.modal' of an element with id modal-add-person ("anythig appended with a # means it is an id of a html element.") execute the steps in the function (e) where e seems to be another html element.
var personId = $(e.relatedTarget).attr('data-id');
Get the attribute 'data-id' from the element passed in e.(For example if it was attr('id') it would return the id of the element passed to personid )
$('#modal-add-person-hidden').val(personId);
Set the html element with id "modal-add-person-hidden" by the value in personId
$('#modal-add-person-id-text').html(personId);
Set the element's (where id = modal-add-person-id-text) inner html with personId
});
note: '#' stand for id of the html element '.' stands for class of the
element or you can give the tag as it is, for example "input" means
all elements with input tag
Hope this helps. Please let me know if this was helpful.

Related

Determining Element Type from Id

I have a javascript method -testElement() which is called on onclick event -
<script type = "text/javascript">
function testElementType(element){
var elemId = $(element).attr("id");
//Can I determine the 'element' from the 'elemId' ?
// if element is div - do something
// if element is button - do another thing
}
</sccript>
Now consider the following code -
<div onclick="testElementType(this);" id="testDiv" > Test Div </div>
...
<button onclick="testElementType(this);" id="testBtn" > Test Button </button>
So when either of 'testDiv' or 'testBtn' is clicked then the 'testElementType() method is called. In this method I can get the element Id by jquery - $(element).attr("id"); and store it in 'elemId'
Is there any way to find the the type (ie - whether it is a div or button ) of element from 'elemId'?
I know in practice most of the situation we don't have to bother about the element type. Because we can call to different function for two type of element click if we want to do two different type of task.
You dont need to use the id value here. You pass the object into the function iself so all you need to do is this:
function testElementType(element){
var tag = element.tagName;
if(tag=='DIV') // its a div
if(tag=='BUTTON') // its a button
}
using jquery $("#elementId").is("button") will return if elementId is button.
for more answer here
Taken from docs, the tagName selector will return the elements type, you can use it like this.
function testElem(e) {
var t = e.tagName;
// Print the tag name
console.log(t);
}
Something like...
function testElementType(element){
var id = $(element).attr('id'),
tag = $(element).prop("tagName");
});
See this demo fiddle
Try this way to get element type by id
$("#elementId").get(0).tagName

get id and value dynamically created element jquery

I need the id(and other attributes such as value) of a span i previously created on an ajax event.
Is there a way to do this?
This is how the span is created on php post:
echo "<span class='non-skin-symptom-choice disease_option' ".
"onclick='showinfo(".$var[0].");' id=".$var[0].">"
.$var[1]." -- ".number_format($var[3]*100, 2, '.', '')."%</span>";
and I want to get its id whenever a checkbox is clicked.
$(".chb").click(function(){
var id= $(this).attr('id');
var list=[];
$('.disease_option').each(function (){
alert("this.val=="+ $(this).attr("val")); //i need the value here
var str= $(this).attr("value").split(" -- ")[1];
alert(str);
str=str.slice(0,str.length - 1);
if(parseFloat(str) >=support)
list.push(id) //i need the id here
});
the checkbox is not dynamically created, so $(".chb").click(function(){} works.
somehow, $(this).attr("id") works but $(this).attr("val") returns undefined... i also tried $(this).attr("value") but same results. $(this).val returns empty.
use
$(document).on('click','.chb',function(){
var id = $(".non-skin-symptom-choice").attr("id");
})
as this have a high level event attachment and it can get the elements who have been created on a runtime
Try this
alert($(".non-skin-symptom-choice").attr("id"));
The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have create a "delegated" binding by using on()
$(document).on('click','.chb',function(){
var id = $(".non-skin-symptom-choice").attr("id");
})
possible duplicate: Click event doesn't work on dynamically generated elements
If your DOM node did not exist when the page loaded (ie. it was added to the page via AJAX after the page loaded), jQuery cannot see it if you try to update it or read it with jQuery methods. One way to overcome this is to set up your jQuery function to reference the class or ID of the parent of the node you want to target (assuming the parent class is loaded into the page on page load), along with the class of the node you want to target. For example:
$(".chb").click(function(){
var id = $(".your-parent-class .non-skin-symptom-choice").attr("id");
}
}

Getting access to a jquery element that was just appended to the DOM

I am simply appending an element that is on the DOM like:
$("#div_element").append('test');
Right after I append it I need access to the element I just made in order to bind an click function to it, I tried:
$("#div_element").append('test').click(function(){alert("test")});
But the above didn't work. I could uniquely id the element but that seems like a bit to much work when perhaps there is a way I can get the element right after I append it.
You can do this:
var el = $('test');
$("#div_element").append(el);
el.click(function(){alert("test")});
// or preferrably:
el.on('click', function(){alert("test")});
The append function accepts two types of arguments: a string or a jQuery element.
In case a string is passed in, it will create a jQuery element internally and append it to the parent element.
In this case, you want access to the jQuery element yourself, so you can attach the event handler. So instead of passing in the string and let jQuery create an element, you have to create the element first and then pass it to the append-function.
After you've done that, you still have access to the jQuery element to be able to attach the handler.
var $a = $('<a />', {href:"#"})
.text("test")
.on('click', function(e) {
alert('Hello')
})
.appendTo('#div_element');
http://jsfiddle.net/33jX4/
Why not save a reference to the new element before you append it:
var newElement = $('test');
$("#div_element").append(newElement);
newElement.click(function(){alert("test")});
The last element would be the new element
$('a:last','#div_element').on('click',function(){
// do something
});
Add identity to that element then use it as follows
$("#div_element").append('<a id="tester" href="#">test</a>');
$('#tester').on('click', function(event) {
console.log('tester clicked');
});
You can attach event to element when you create it --
var ele =$("<a href='#'>Link</a>");
ele.on("click",function(){
alert("clicked");
});
$("#div_element").append(ele);
Just attach the click handler to the anchor BEFORE you append it.
$("#div_element").append($('test').click(function(){alert("test")}));

How to get attributes values separately for each container present on the webpage in jquery?

This question is in continuation to How to get attributes of container in jQuery, I have different containers on my webpage and all of them have <div id = "some values">. Now how can I get attributes values separately for each component?
Is there any way I can know which attribute id belong to which container div?
Currently I am using:
var id = $( '.promotion' ).attr( 'id' );
But if I have multiple promotional components on page and all have same div attribute as id than how can I relate that this particular attribute id belonged to this specific container?
Update: I am having a function which is called for each container present on the page and so if I am using above mentioned code than will it not always return me the first match for id in the div and would never go to other divs and so I will always get same value for id which is for the first container ? If so than what is the work around for this ?
var id = $( '.promotion' ).this.attr( 'id' );
var id = $( '.promotion' ).$this.attr( 'id' );
var id = this.$( '.promotion' ).attr( 'id' );
How would I know if the attribute value is for current container, so how should I use this properly to get this information ?
Hope this question is clear.
You can loop through and process each div individually
$(".promotion").each(function() {
var id = this.id; // 'this' is the html element, not the jquery object
});
Update
function myfunc() {
alert(this);
}
// inside myfunc, this will be the window
myfunc();
// call (also: apply()) changes "this" to be the first argument
myfunc.call(document.getElementById("someid"));
Jquery uses this to refer to the current element being processed. In events that would be the target element. In .each it is the current element in the collection.
Consider:
$(".promotion").click(function() {
alert(this); // will alert with the div that was clicked
});
In Jquery you can wrap any html element with a JQuery Object by using $(element). So when this is an html element like in the example above you can use $(this):
$(".promotion").click(function() {
alert($(this).attr("id")); // will alert with the div that was clicked
});
Play around with it here: http://jsbin.com/okuri3/edit.
More about this:
http://www.quirksmode.org/js/this.html
http://remysharp.com/2007/04/12/jquerys-this-demystified/

Appending a string variable in jQuery

I'm not sure if I have the syntax correct in the code below, I'm trying to append a var to a string parameter within the find function. I'm trying to search for a unique id within each input element of a particular form.
//Get value attribute from submit button
var name = $('#myForm').find('input#submitThis').val();
//Other code that manipulates the name variable
//Submit button in hidden form
$('.submitLink').click(function(){
$('#myForm').find('input#'+name).click();
return false;
});
The element with a submitLink class is supposed to be tied to the submit button in the form. I don't think I have the syntax correct though, when I go back and click the element that has the submitLink class, nothing happens.
The syntax appears fine to me. To be sure the selector is what you are expecting it to be, you could do something like this:
$('.submitLink').click(function() {
var selector = 'input#' + name;
alert(selector);
/* rest of the code */
});
Try adding an alert to test the var inside the event handler (and to see that the handler is fired). Also, if you are looking for an element with a specific id you don't need to include the element type. Like this:
$('.submitLink').click(function (event) {
event.preventDefault();
alert(name);
$('#' + name, $('#myForm')).click();
});
NOTE: If you are trying to find an element by its name rather than ID you must use $("input[name='foo']").

Categories

Resources