Parent element selection problem? - javascript

My HTML is something like this
<div id="mydiv" class="common">
<input type="text" id="text1" value="" />
<input type="text" id="text2" value="" />
</div>
I am assigning a function on the onclick event of the textbox like this
$(document).ready(function() {
$(".common input").click(function() {
//////// What I am trying to do is access the id of its parent
// in this case it is "mydiv"
alert($(this:parent).attr('id'));
});
But it is not working

Try $(this).parent().attr('id');

You'd be better off using event delegation and only having one event handler on the parent <div>. This will be more efficient by reducing the number of event handlers required, and by replacing the descendant and element selector with the much simpler and faster ID selector. Also, within the event handler function you automatically have references to both elements you're interested in (via evt.target and this) without having to do any traversal.
$(document).ready(function() {
$("#mydiv").click(function(evt) {
if (evt.target.tagName.toLowerCase() == "input") {
alert("Clicked input with ID " + evt.target.id);
alert("Parent ID: " + this.id);
}
});
});

Change it to the following
$(document).ready(function() {
$(".common input").click(function() {
var divId = $(this).parent().attr('id'));
alert(divId);
});

$(document).ready(function() {
$(".common input").click(function() {
alert( $(this).parent().attr('id') ); // <- Use $(this).parent()
}); // <- don't forget to close this function too
});

Related

Jquery get attribute ID for latest click

im trying to get the attribute value through jquery
$(document).click(function() {
var elem = $("input[name='phone']");
alert(elem.length);
if(elem.length > 0){
alert(elem.attr('id'));
}
});
here the case is
i have lots of input fields with same name as "phone" in different form. Whenever i click it i can get only the first value. Not the last one. How can i get it through the Jquery.
In my page only document click will work because the form codes are loading from some other site.
Any help is more appreciate
$( "input[name^='phone']" ).last()
will return the last element with name beginning with 'phone'
You can do this, to get the id of the item that is clicked.
$("input[name='phone']").click(function() {
alert($(this).attr('id'));
}
This is attaching the listener to phone inputs and this is the context, which in this case the item that is clicked.
Try this:
$("input[name='phone']").on('focus', function(){
alert($(this).attr('id'));
}
This will listen to clicks on your phone input fields and alert the id attribute for you to see on screen:
JQuery
$("input[name='phone']").click(function() {
alert($(this).attr("id"));
});
HTML example
<input id="a" name="phone">A</input>
<input id="b" name="phone">B</input>
<input id="c" name="phone">C</input>
<input id="d" name="phone">D</input>
Delegate the event with .on(), then you can use this:
$(document).on('click', 'input[name="phone"]', function() {
console.log('element with id: ' + this.id + ' has value: ' + this.value);
});

Remove buttons added by jQuery

I am adding extra selects and text fields to a form using jQuery. However I want to be able to remove added text fields using the remove button.
Once a field has been added jQuery can not seem to detect it.
jQuery
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'contact-list-div-' + counter).attr("class", 'contact-list-div');
newTextBoxDiv.after().html('<select></select>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >' + '<button type="button" class="removeButton" id="removeButton-' + counter + '">Remove Button</button>');
newTextBoxDiv.appendTo("#contact-list");
counter++;
});
$(".removeButton").click(function() {
alert(this.id); //this never shows, only on the element that was
//added directly added using html, in this case removeButton-1
});
HTML
<div id="contact-list">
<div class="contact-list-div" id="contact-list-div-1">
<select></select>
<input>
<button type='button' class='removeButton' id='removeButton-1'>Remove Button</button>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
$('#contact-list').on('click', '.removeButton', function() {
//Your code
});
You need to use event-delegation:
$(document).on('click', '.removeButton',function() {
$(this).parents('.contact-list-div').remove();
});
You appending content to your DOM after the event-listener for your click on .removeButton is registered. So this element does not exist at the time your binding a click event to it.
Through event-delegation you are able to bind an event-listiner to an existing parent (document in this case, but #contact-list would be working too). And this will listen to all events of its descendants matching the .removeButton - selector.
Demo
This is because you are binding the events to elements that do not yet exist.
Use jQuery delegation to enable handlers on not yet existing elements:
$("body").on("click", ".removeButton", function() {
alert(this.id);
});
You add the click listener only at the first button.
Try using delegate:
$(document).delegate(".removeButton", "click", function() {
alert(this.id);
});
This tells the document that whenever a event click occours on an element with class "removeButton" it should call that callback
(You can see it working here)
Because the element is dynamicly added with jQuery, the normal .click event of jQuery will be not able to detect the new added elements.
Use instead .on. See the example below:
$("body").on("click", ".removeButton", function() {
alert(this.id); //this never shows, only on the element that was
//added directly added using html, in this case removeButton-1
});

Single event function for text, check box, select input using Jquery

I have to do same things when following event occur on a form
1) An input text box value is changed by keyboard or mouse(pasting)
2) A checked box is checked/unchecked
3) A select option is changed
currently I am doing
$(':text').on('input', function() {
//Same code
}
$(':checkbox').on('change', function() {
//Same code
}
$('select').on('change', function() {
//Same code
}
but i want to write single function for all there events like
$(':text', ':checkbox', 'select' ).on('???', function() {
//Same code
}
Please help me on it
Thank you in advance
You may use something like this. But this will trigger both change and input events for the :text.
$(':checkbox, :text, select').on('change input',function(e) {
//code
});
JSFIDDLE
Add a CSS class to these input boxes and use that class as your jQuery selector for binding your event.
HTML
<input type="text" class="changable" />
<input type="checkbox" class="changable" />
and jQuery
$(function(){
$(document).on("change",".changable",function(e){
var _this=$(this);
// do something now.
});
});
I would suggest using #Shyju's answer, as it is much more scalable and friendly, but based off of your question, here is an implementation.
Listen to the document for click events and delegate it to the selectors you pass in:
$(document).on('click', ':text, :checkbox, select', function() {
doFunction();
});
Here's a JSFiddle working example
Bind your single/multiple event/s with multiple elements using class attribute. Assign same class to all elements and find the event type that has been fired. According to the fired event code your implementation.
Try this way :
HTML :
<input class="elements" type="text" />
<input class="elements" type="checkbox" />
<select class="elements">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<input class="elements" type="button" value="Click here" />
jQuery :
$(".elements").on("change click", function(e){
var nodes = e.target;
if(nodes.nodeName == "INPUT"){
if(nodes.type == "text" && e.type == "change"){
// code goes here
alert("Input changed");
}else if(nodes.type == "checkbox" && e.type == "change"){
// code goes here
alert("Checkbox state changed");
}else if(nodes.type == "button" && e.type == "click"){
alert("Button is clicked");
}
}
else if(nodes.nodeName == "SELECT" && e.type == "change"){
// code goes here
alert("Select option changed");
}
});
jsFiddle
Resources :
event.type
event.target.nodeName

get clicked element ID or Name jquery or javascript

I wants to get the ID or the name of the clicked elemt by using the following code. this code is working fine if i have only one element.
$(window).mousedown( function(e) {
mouseTracker.clickState = true;
console.log( "id:" + e.target.id + " name:" + e.target.name );
}).mouseup( function() {
mouseTracker.clickObject = '';
});
but if element is wrapped up in other elements then i am unable to get the ID. for example:
<div id="main">
<div id="subDiv">
<span id="spID" onClick="alert ('hello world')"> Click Me </span>
</div>
</div>
in the above case, it is return the ID of the main div. how can i get the clicked element.
The most secure way to do this is to add an event listener to each element. There are different ways to do that:
First as you have coded in your HTML:
var testfunction = function(event){
// Do something
};
<span id="spID" onclick="testfunction(event)"></span>
Or nicer:
<span id="spID"></span>
var element = document.getElementById('spID');
element.addEventListener('click', function(event){
// do something
})
Best regards
Dustin
I wouldn't use inline scripting if it was me. The bigger a project gets, the messier this becomes. I tend to have all my event listeners tucked away together in an init function that you can just add to as you need more event listeners:
In the head of your HTML:
<script src="global.js"></script>
<script>
$(document).ready(function() {
global.init();
});
</script>
In a separate js file, linked to your HTML (e.g. global.js):
(function (global, $, undefined) {
global.init = function() {
//bind your event listeners in here
};
})(window.global = window.global || {}, jQuery));
In terms of using this for the purposes of what you are trying to do, if you have a series of these clickable spans, I would use a class selector, so you only have to bind the click event once, otherwise if you are binding to only one span as above then you already know the ID anyway as you had to use it in the bind.
Using class:
global.init = function() {
//assuming you have applied the class "clickable-span" to all the spans you want to be clickable
$('.clickable-span').on('click', function(evt) {
var id = $(this).attr('id'),
name = $(this).attr('name');
console.log( "id:" + id + " name:" + name );
});
//add more event listeners here
};

JQuery script for one checkbox selection from group not working while adding a checkbox dynamically

i'm using the below jquery script to disable user from selecting more than 1 check box of same name at a time
$("input:checkbox").click(function () {
if ($(this).is(":checked")) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).prop("checked", false);
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
And here is the check boxes
<div class="ChekMarkWrap">
<input id="chkFilm_4" type="checkbox" name="four" style="margin-left:2px;" /><br />film
</div>
<div class="ChekMarkWrap">
<input id="chkTv_4" type="checkbox" name="four" /><br />tv
</div>
<div class="ChekMarkWrap">
<input id="chkWeb_4" type="checkbox" name="four" /><br />web
</div>
<div class="ChekMarkWrap">
<input id="chkStage_4" type="checkbox" name="four" /><br />stage
</div>
It works well and good until i add a new check box dynamically.i'm binding the above jquery script on document.ready()
Fiddle: http://jsfiddle.net/3hcFp/2/
That method binds the click event only once, so elements added after that code has been run will not have the event bound. What you need to do is set up a listener instead, like so:
$('body').on('click', 'input:checkbox', function () {
// Do some stuff
}
In the fiddle, i have wrapped the checkboxes in a form#exampleForm, and replaced body in the above example with that.
EDIT: Updated fiddle with live example of adding more checkboxes.
Try like this:
$("body").on('click',input:checkbox,function () {
if ($(this).is(":checked")) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).prop("checked", false);
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
When you add new content you need to append it to the DOM.
But you can target a parent element that was not added after the DOM was loaded to be able to reference/attach-event to it using .on() and passing the selector as I wrote above on the first line of your code..
You should use delegated events. Your code is running on document ready. Nothing is bound to new elements.
$("your-form-selector").on('click', ':checkbox', function(){
//your code here.
});
You can try using delegates. Something like this:
$(".ChekMarkWrap").delegate('click','input:checkbox',function () {
//your functionality
});
For Reference: jQuery Documentation

Categories