Appending a string variable in jQuery - javascript

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']").

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

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.

jQuery .click() event for multiple div's

I have some search results that I'm outputting that are of this form:
<div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>
There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?
Here's how I'm getting the HTML from above:
$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;
var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));
I tried
$('div').click(function(){
alert(this.id);
});
and the alert says "searchresults" (no quotes).
Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.
$("#searchresults").delegate("div", "click", function() {
console.log(this.id);
});
See .delegate
You can't have the same ID on multiple tags. You will have to fix that. You can use the same class, but there can only be one object in the page with a given ID value.
this.id will fetch the id value of the item clicked on and this should work fine once you get rid of conflicting IDs:
$('div').click(function(){
alert(this.id);
});
This code should be something this:
var search_results="<div id='result'" + video_id + " title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append(search_results);
to coin a unique id value for each incarnation and append will just take the string - you don't need to turn it into a jQuery object.
you could get the title using $(this).attr("title").val()

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')

Categories

Resources