why this javascript code is not working? - javascript

Do you know why this is failing, I mean alert is working (it shows me that if found the button) but text or background is not changed:
$('input[type=button]').click( function() {
var button=document.getElementsByName("contactme");
alert(button.length + " elements!");
button.value="New Button Text";
button.style.backgroundImage="url(some_real_gif);"
});
HTML:
<input type="button" name="contactme" value="test"/>
Thanks...
I have to use plain java script not jQuery..

You're setting value and style of a NodeList. getElementsByName can retrieve multiple elements, as the name attribute does not have to be unique in the document (the clue's in the name!) Setting these has no effect -- it doesn't affect the properties of the element(s) within the NodeList.
Either loop through the element(s) manually (using a for loop) or fully use jQuery:
$('input[type=button]').click(function () {
var buttons = $('input[name="contactme"]');
alert(buttons.length + " elements!");
buttons.val("New Button Text");
buttons.css({backgroundImage: "url(some_real_gif)"});
});
See the jQuery API:
val
css
attribute-equals selector ([name="value"])

It looks like var button=document.getElementsByName("contactme"); would return an array of elements. Try:
var button=document.getElementsByName("contactme")[0];

getElementsByName will return a nodeList but value and style are properties of HTMLElementNodes. You have to loop over the list to get them.

$('input[type=button]').click(function() {
$("#contactme").val('New Button Text').css('background-image', 'url(some_real_gif)');
});
You would need to make sure the button id matches the name...

Because button is a list of elements (even if it is a list of one)
What you can do is use button[0].value and button[0].style.background
Or use a jQuery solution:
To change only clicked button:
$('input[type=button]').click( function()
{
$(this).val("New Button Text");
$(this).css('background-image','url("some_real_gif")');
});
To change all buttons:
$('input[type=button]').click( function()
{
$('input[type=button]').each(function(){
$(this).val("New Button Text");
$(this).css('background-image','url("some_real_gif")');
});
});

Related

Jquery remove element

I am basically trying to print the value of a button in the div with list class if the button is selected. Also remove the same value wwhen it is deselected. I am able to print the value successfully but not able to remove it. Could somebody please help me out with it.
var buttonSelect = $(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append(this.value + " ")
}
else {
$(".list").remove(this.value)
}
});
You should rather append the content along with html element like span:
$(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append('<span class="newval_'+this.value+'">'+this.value + "</span>");
}else{
$(".list").find('.newval_'+this.value).remove();
}});
The parameters from .remove() is a selector, just having a value in there that contains the content of the element you want to remove will not work. For example if I had this:
<li class="list">test</li>
Doing $(".list").remove("test") will not remove it. You will probably want to use the :contains selector (since you may have the value with spaces at the end). So in the example above doing $(".list").remove(":contains('test')") will remove the element. You can do the same thing in your case:
$(".list").remove(":contains('"+this.value+"')");
If you want to remove the element itself along with everything in it, just use jQuery’s remove() method.
$(document).ready(function() {
$("button").click(function() {
$("div").remove(); //remove Div element
});
});
You can see an example here: How to Remove Elements from DOM in jQuery

Changing the contents of an input/div/span etc

I add a .listen class to various elements on my page, could be a button, could be an input, div, span etc.
$('.listen').on('click', this._init.bind(this));
In the method I wish to replace text in the element that was clicked.
p._init = function(e){
$(e.currentTarget).val('new data');
};
The above works for input elements, but not for things like divs. Is there a way to change the data on any type of elements or will I have to use a switch to test for the variations?
You could get a little fancy and check if the element has a value property, and change methods based one that, something like
p._init = function(e){
$(e.currentTarget)['value' in e.currentTarget ? 'val' : 'text']('new data');
};
FIDDLE
Unless you're adding value properties to elements that don't natively have value properties, that should work.
For input it's val() for divs and stuff it's text().
If you wanna do everything with a single event, you can do something like:
$('.listen').on(...
{
if($(this).is('input'))
{
use val()
}
else
{
use text()
}
}
Try this DEMO
$(document).ready(function(){
_init = function(e){
if(e.target.nodeName=='SPAN'||e.target.nodeName=='DIV')
$(this).text('new data');
else if(e.target.nodeName=='INPUT')
$(this).val('new data');
};
$('.listen').on('click', _init);
});

Adding onclick events to appended div tags in JavaScript

I am trying to add a click event to a bunch of div elements that I created by appending them and I am having some trouble.
I have a bunch of div elements the with the ids a0 ---> an. I am trying to create a for loop after the divs are created to assign them click events. The issue is the way I am doing it when the click event happens I do not have any way to track which div fired the event. The code bellow might make that more clear. So the issue I am having is that #a + i always returns the last div, and I want it to return the div number that was clicked.
$(document).ready(function () {
traverse(oo);
for (i = 0; i <= groupNum; i += 1) {
$("#a" + i).click(function () {
console.log("#a" + i + "clicked");
});
}
});
I thought about returning a closeur, but that seems I would make it even more complicated. Does anybody have any advice on how to do this the best?
Thanks in advance.
I'm not sure what you are trying to do but if you just want to assign a click event to a bunch of elements then use the correct selector (note the use of $(this) to get the clicked element):
$("div").click(function(){
var clickedDiv = $(this);
var id = clickedDiv.attr("id");
});
If you don't want ALL div elements, then you could add a class to them and use a different selector:
$(".MyDivClass").click(function(){...
or without the class, a 'starts with' on the id (the following with get all div elements where the id attribute starts with "a"):
$("div[id^='a']").click(function(){...
If you are dynamically adding divs with other javascript and you want them to automatically have the click events, use the on function...
$(document).on("click", ".MyDivClass", function(){...
The variable i will, as you noticed, will contains the value set on the last iteration. Change
console.log("#a" + i + "clicked");
by
console.log(this.id + " clicked");
Within the event handler, this is the target DOM element for the event.
You can do it in this way:
$('[id^="a"]').click(function () {
console.log(this.id+" clicked");
});
You may assign a click event to a class instead of to specific ID's and use conditional statements within the click function to do different things base on ID.
$(documnet).ready(function(){
$('.clickclass').click(function(){
/* conditional code here */
});
});

getting individual atrributes while selecting a class with JQuery

I'm new to javascript and JQuery, and I'm working in a small project with JSP.
I create a grid dynamically with JSP and I added some buttons wich class is "select" and in the alt attribute I set the current row index. That works perfectly, I'm trying to set the onclick dynamically. This is my code
$('.select').click(function (){
alert($('.select').attr('alt'));
}
I want to each button to show its own index, but that code shows just the first index in each button. I've searched how to do it, but nothing comes out.
Is there a chance to do what I want?
change this line as:
alert($(this).attr('alt'));
When jQuery calls your event handler it sets this to be the DOM element in question, so try this:
$('.select').click(function (){
alert($(this).attr('alt'));
});
If you need to access DOM element properties you can then get them directly, e.g.:
alert( this.id );
this.value = "test";
If you need to use jQuery methods on the element you need to pass it to the jQuery function first, e.g.:
$(this).hide();
$(this).css("color","red").slideDown();
$('.select').click(function (){
alert($(this).attr('alt'));
});
Change
alert($('.select').attr('alt'));
by
alert($(this).attr('alt'));
Now you select the attr alt of the button lauch the event.
Not sure if that's what you're looking for but...
$('.select').click(function() {
$('.select').each(function() {
$(this).attr('value', $(this).attr('alt'));
});
});
This'll have every button "show" the value stored within their alt attribute when you click one button.
By the way, if you're using 1 button per row, you'd probably better go with index().

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

Categories

Resources