Determining Element Type from Id - javascript

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

Related

javascript this.value doesn't work?

sorry for asking that stupid:D However what did i do wrong here?
html:
<div onclick="prompt()" value="test">test</div>
javascript:
function prompt() {
var error = this.value;
alert("sdsd");
}
Thanks!
First off, <div>s don't have a value attribute, so .value won't work. Second, you should not use inline JavaScript.
What you should do is:
<div id="test" value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
// You need to get the attribute from the element
var error = $(this).attr('value');
});
});
If you must use inline events, then you need to pass the element to the prompt() function. The problem is that it doesn't know what this is. This is why you should bind the event as shown above. Anyway, you can also do:
<div onclick="prompt(this)" value="test">test</div>
Then:
function prompt(ele){
// You can't use `.value` because `<div>`s
// don't have a value property
var error = ele.getAttribute('value');
}
P.S. May I also suggest using data-* attributes for this instead of invalid attributes?
<div id="test" data-value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
var error = $(this).data('value');
});
});
The value of this depends on how the function that it appears in was called.
When the browser calls the onclick function from the event trigger, this is the input.
When you call prompt(), because you provided no context and you are no in strict mode, this is the window.
You need to explicitly pass the value.
onclick="prompt.call(this)"
Better yet, don't use intrinsic event attributes in the first place. They mix your HTML and logic and have a whole collection of gotchas to go with them.
Then you have a second problem.
Div elements don't have values. Only inputs and other form controls do. You would need to use .getAttribute("value") instead of .value … but that still leaves your HTML invalid (as well as inappropriate - div elements aren't designed to be interacted with, they give no visual indication that they should be clicked on, and they won't receive the focus should the user not be using a mouse or other pointing device anyway).
You should use a control designed to be interacted with.
Finally, prompt is a built in function, so you should avoid overwriting it and pick a different name instead.
function show_value(event) {
var value = this.value;
document.body.appendChild(document.createTextNode(value));
}
document.querySelector("button").addEventListener("click", show_value);
<button type="button" value="test">test</div>
Div does not have value attribute.
If you need to get the value inside div element you can do it by innerHTML property.
function prompt() {
var error = this.innerHTML; // OR this.getAttribute("value");
}

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");
}
}

Deconstructing javascript script

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.

multiple button determine which is clicked

I have multiple buttons in a form (all are type 'submit'). I would like to determine which one of them is clicked. I am currently using:
$(".MyForm").click(function() {
...
}
to get values from my form. Any help is greatly appreciated.
Inside your handler, 'this' is the DOM element that was clicked, and $(this) is the jQuery object for that DOM element. So...
$(".MyForm").click(function() {
var buttonId = $(this).attr('id');
//...
}
You define an id for each button then you can use $("#buttonid").click to define different action for each button you like or test the id with .attr('id')

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