change the background of an id that is clicked - javascript

When one of the element(id) of a form is clicked, i would like to listen to that event, and change the background of that element.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$(x).css('background-color',color);
return false;
});
}
<form>
<div id="a">Item1</div>
<div id="b">Item2</div>
<div id="c">Item3</div>
</form>

Your code will end up looking for tag names because the selector is
$("b")
If you want to do it the way you have it, you would need to add the missing #.
$("#" + x).css('background-color',color);
But there is no need to look up the element when you already have a reference to is. Use event delegation and this
$('form').on('click', 'div', function(e){
$(this).css('background-color',color);
});

Why bother using e.target? Just update your code to use $(this):
$(function() {
$('form > div').on('click', function(e) {
e.preventDefault();
$(this).css('backgroundColor', color);
});
});

This will work out. Take care of your tags.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$("#"+x).css('background-color',"red");
return false;
});
});

The thing happening to you is that event.target.id returns a string representing the id of the element, not a selector. So where you use $(x).... you have to use $('#'+x), your actual code does not work because the selector for the background change is not looking for an element with the X value on the Id but for an element called like the value of X (eg. x="a", then it's looking for elements)

Here's my "lowly" try:
<!DOCTYPE html>
<html lang = 'es'>
<head>
<title> My Test </title>
</head>
<body>
<form>
<div id="a"> Item1 </div>
<div id="b"> Item2 </div>
<div id="c"> Item3 </div>
</form>
<script>
function addBackgroundColor(e){
var index = parseInt(Math.random() * 4); // the number of the multiplier has to be equal to the length of the array colorsList.
e.target.style.backgroundColor = colorsList[index];
}
var colorsList = ['blue','red','green','yellow','orange']; //add others colors here if you want.
var divsList = document.getElementsByTagName('div');
for (var i in divsList){
divsList[i].addEventListener('click', addBackgroundColor);
}
</script>
</body>
</html>

No need to go fancy. Just do
$(document).ready(function(){
$('form div').on('click', function(e){
$(this).css('background-color',color);
return false;
});
}

Related

Same AJAX call for multiple button on clicks on the same page [duplicate]

I have multiple buttons containing different values.
My buttons :-
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Now, if I click on Button1, I should get it's value. That is 1, and if I click Button2, I should get value 2.
I have written this code :-
<script type="text/javascript">
$("button").click(function() {
var fired_button = $("button").val();
alert(fired_button);
});
</script>
But it always alerts 1. What must I do to fix my code?
UPDATED
Use this instead of button in :
var fired_button = $("button").val();
You have to use this to target the current button clicked instead of button that will select all buttons in the DOM, .val() makes it to get the value of the first button.
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
You need to use this variable in order to access the clicked button's value.
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>
This would return the value of the button.
You could try something as simple as:
$(this).val();
$(function(){
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Note: you should add your event listeners after the document is ready. This is why, I have enclosed the event handler in the
$(function{})
This is a shorthand of
$(document).ready(function(){})
For more information about this, please have a look here.
Use this inside the click handler
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>
this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
Try with $(this).val();. It will return clicked button value.
If you're using jQuery, you're looking for the .attr() function.
$(this).attr("value")
That code will give you the value attribute of the html element designed by $(this) (or you precise the ID of the element).
Try $(this).val().
'this' always refers to the current object.
this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
Plain JavaScript solution with ES6 syntax:
document.querySelectorAll('button').forEach(button => {
button.addEventListener('click', () => {
const fired_button = button.value;
alert(fired_button);
});
});

How can I get data from multiple attributes?

I want to get data from multiple attributes on click event. Suppose I have a div with class test_class and ID testID as given below.
<div class="test_class" id="testId"><!-- ... --></div>
I want to get the value of the class and id attributes and store them in separate variables.
var classattr = 'test_class';
var idattr = 'testId';
How can I make this? I would like to avoid calling attr() multiple times.
You can get those with javascript too, like below.
var attrs = document.getElementById("testId").attributes;
var classattr = attrs["class"].nodeValue;
var idattr = attrs["id"].nodeValue;
console.log(classattr);
console.log(idattr);
<div class="test_class" id="testId">
</div>
Even simpler with object destruction:
var t = document.getElementById("testId");
var {className, id} = t;
console.log(className, id)
<div class="test_class" id="testId">
You can add any other attributes between surly braces if you need.
console.log("Div id is "+$('div').attr('id'))
console.log("Div class is "+$('div').attr('class'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test_class" id="testId"></div>
Use .attr()
Description: Get the value of an attribute for the first element in the set of matched elements.
USE:
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});
You will not have to use .attr multiple times.
For eg: a single span tag with multiple attributes can be obtained using the above code.
what you can do is when a certain button has been pressed. lets say the class btn has been clicked.
<html>
Click me
<div class="test_class" id="testId> Some stuff in here </div>
</html>
<script>
$("").click(function(){
var dvclass = $(".test_class").attr("class");
var dvid = $(".test_class").attr("id");
});
</script>
You don't need jQuery at all. By the magic of vanilla JavaScript, you can already access the class and id of any element you have. There is even a neater interfaces for adding/removing classes: classList. You can use them as follows, in a jQuery click handler:
$('.test_class').click(function() {
console.log(this.className, this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test_class" id="testId">Click me!</div>
Or without any jQuery:
document.querySelector('.test_class').addEventListener('click', function() {
console.log(this.className, this.id);
});
<div class="test_class" id="testId">Click me!</div>
To access other attributes, you can use other methods.
data-* attributes? Use dataset.
name attribute? Well... name.
Attribute that cannot be accessed directly? getAttribute() has you covered.
function getDomNodeProps(domNode) {
let attrs = {}
Array.from(domNode.attributes).forEach(a => attrs[a.name] = a.value);
return attrs;
}
console.log(getDomNodeProps(document.getElementById("testId")))
Try with attr().And do with click function .Then find the attr value using this.attr
$('.test_class').click(function() {
var cls = $(this).attr('class');
var id = $(this).attr('id');
console.log(cls, id)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test_class" id="testId">click</div>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").click(function(){
var clnm=$(this).attr("class");
var idSel=$(this).attr("id");
});
});
</script>
</head>
<body>
<div class="test_class" id="testId">
Example
</div>
</body>
</html>
$("div").click(function(){
var classattr=$(this).attr("class");
var idattr=$(this).attr("id");
console.log(classattr,idattr);
});
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes returns array
if(this.specified) {
console.log(this.name, this.value);
}
});
});

Get value of the clicked button

I have multiple buttons containing different values.
My buttons :-
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Now, if I click on Button1, I should get it's value. That is 1, and if I click Button2, I should get value 2.
I have written this code :-
<script type="text/javascript">
$("button").click(function() {
var fired_button = $("button").val();
alert(fired_button);
});
</script>
But it always alerts 1. What must I do to fix my code?
UPDATED
Use this instead of button in :
var fired_button = $("button").val();
You have to use this to target the current button clicked instead of button that will select all buttons in the DOM, .val() makes it to get the value of the first button.
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
You need to use this variable in order to access the clicked button's value.
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>
This would return the value of the button.
You could try something as simple as:
$(this).val();
$(function(){
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Note: you should add your event listeners after the document is ready. This is why, I have enclosed the event handler in the
$(function{})
This is a shorthand of
$(document).ready(function(){})
For more information about this, please have a look here.
Use this inside the click handler
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>
this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
Try with $(this).val();. It will return clicked button value.
If you're using jQuery, you're looking for the .attr() function.
$(this).attr("value")
That code will give you the value attribute of the html element designed by $(this) (or you precise the ID of the element).
Try $(this).val().
'this' always refers to the current object.
this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
Plain JavaScript solution with ES6 syntax:
document.querySelectorAll('button').forEach(button => {
button.addEventListener('click', () => {
const fired_button = button.value;
alert(fired_button);
});
});

jquery create and delete input fields

I wrote this code here:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
</head>
<body>
<button id="add_field">Noch ein Inputfeld</button>
<hr>
<div class="input_fields">
</div>
<script>
$(function(){
var number = 1;
$("#add_field").click(function(){
if(number < 11){
var name = "input";
name = name + number;
$(".input_fields").append('<a>'+ number +':</a><input type="text" name="' + name + '" />entfernen<br>');
number++;
}
else{
alert("10 ist Max");
}
});
$(".remove_field").click(function(){
$(this).parent('input').remove();
x--;
});
});
</script>
</body>
I can create input fields, but if i press on the loeschen Button, nothing happens. So i think here is a mistake in this function:
$(".remove_field").click(function(){
$(this).parent('input').remove();
x--;
});
Try something like this:
$('.input_fields').on('click', '.remove_field', function(){
$(this).parent('input').remove();
x--;
});
You need to use the delegate pattern for the event handler.
You might also be interested in:
Your fiddle fixed (note that you need to re-do the logic for displaying numbers if you want them to handle inputs getting removed from the middle)
https://developer.chrome.com/devtools/docs/javascript-debugging
JQuery event handlers not firing
https://api.jquery.com/on/
You need to use event delegation for attaching events to dynamically added elements:
$("body").on("click",".remove_field",function(){
$(this).parent('input').remove();
number--;
});
Working Demo

dynamically create element using jquery

I am trying to create element using jquery. When i click on a link, i want to create an element "p", give it some text, and then put it in one of my divs. Also, i want to check which link is clicked on, so i can put the created "p" in the right div. Any solutions on where i am doing it wrong?
Javascript/Jquery
$(document).ready(function () {
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
}
$("#menu").find('a').each(function () {
$(this).click(function () {
createElement();
});
});
createElement();
});
HTML
<html>
<head>
<title>Inl1-1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style-1.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="Uppg1.js"></script>
</head>
<body>
<ul class="meny" id="menu">
<li>Utvärdering/Feedback</li>
<li>Kontakt</li>
<li>Öppettider</li>
<li>Om Asperöd</li>
</ul>
<div id="contentl1">
</div>
<div id="contentl2">
</div>
<div id="contentl3">
</div>
<div id="contentl4">
</div>
</body>
</html>
Here is the best way to add new <p> element with text "Hej" to #contentl1 using jQuery:
$("<p />", { text: "Hej" }).appendTo("#contentl1");
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var p = $("<p>");
p.text("Hej");
$("#contentl1").append(p);
}
});
}
For a start the click function can be done like this instead of having to use .find():
$('#menu a').click(function() { }
The .each() loop can be done like:
$('#menu a').each(function () {
var aId = $(this).attr('id');
var contentId = content + aId;
$(contentId).append('<p>Hej</p>');
})
I know it doesn't realate to answering your question but it is hard to leave this as a comment:
var a = $("#menu").find('a').each(function(){ <-- this "a" will only be created after the each completes
if(a == "l1"){ <-- this "a" that you are verifying is a global variable
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
You can try this to solve your issue:
function createElement() {
if($(this).attr("id") == "l1"){
$("#contentl1").append('<p>hej</p>');
}
}
$("#menu a").each(function () {
$(this).click(function () {
createElement.apply(this);
});
});
Something like this fiddle?
$('#menu').on('click', 'a', function(e) {
e.preventDefault();
$('<p>').text($(this).text()).appendTo('#content'+this.id);
});
try this script, it'll do place the text in correct div.
$(document).ready(function () {
$("#menu").find('a').each(function () {
$(this).on('click',function () {
$("#content"+$(this).attr("id")).append("<p>link "+$(this).attr("id")+" is clicked</p>");
});
});
});
I personally like to use classic JS DOM for tasks so this is how you can first create the DOM object using JQuery. The DOM object returned is the outer element of HTML (p tag) but the inner HTML can be as complex as you want.
var elP = $("<p>Hej</p>")[0]
// Do some other DOM manipulations of p
// eg: elP.someCustomTag='foobar'
$("#content1").append(elP)

Categories

Resources