Jquery - getting ID of DIV element clicked - javascript

The following works fine and the ID of the button is displayed:
<input class="edit" type="button" value="Edit" id="button1">
SCRIPT
$(".edit").click (function(){
var buttonID = $(this).attr('id');
alert(buttonID);
}
But this does not with the ID buttonID as undefined:
<div id="button1" onclick="pickedID()">Edit</div>
SCRIPT
function pickedID() {
var buttonID = $(this).attr('id');
alert(buttonID);
}
Why is this is and is there a way of getting the Div ID as I am trying to do?

You have to add this to the function when you call it, as in <div id="button1" onclick="pickedID(this)">Edit</div>
Then we can use it as below:
function pickedID(obj) {
var buttonID = $(obj).attr('id');
alert(buttonID);
}
So in this case, obj in function pickedID(obj) refers to this from onclick="pickedID(this)"
demo
function pickedID(obj) {
var buttonID = $(obj).attr('id');
alert(buttonID);
}
$(".edit").click(function(){
var buttonID = $(this).attr('id');
alert(buttonID);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="edit" type="button" value="Edit" id="button1">
<div id="button2" onclick="pickedID(this)">Edit</div>

I would suggest you to not use inline onclick handler. Much better to assign event handlers using jQuery.
$('#button1').on('click', function(){
console.log($(this).attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="button1">Edit</div>

With onclick, it doesn't give you direct access to the attributes using this.
You can use event which will give you the mouse event handled and then you can retrieve the id.
In your case:
function pickedID() {
var buttonID = event.srcElement.id;
console.log(buttonID);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="button1" onclick="pickedID()">Edit</div>
Or you can pass the id directly into the function:
function pickedID(id) {
console.log(id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="button1" onclick="pickedID(this.id)" data-id="2">Edit</div>

Related

get value from multiple buttons

How can I get the value of the button that the user clicked. I tried this but it doesn't work
for (var i = 0; i < 4; i++) {
var x = document.getElementsByClassName("button")[i].onclick() = function(){
console.log(x);
}
}
$("button").click(function() {
alert($(this).html()); // for the text in button tag. for value in button tag use $(this).val()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="up" value="up">button up</button>
<button id="down" value="down">button down</button>
if you don't want to use jquery and use only pure javascript you can do following:
<button id="up" value="up" onclick="alert(this.value)">button up</button><!-- for value -->
<button id="down" onclick="alert(this.innerHTML)">button down</button><!-- for text in tag -->

How do you put an onclick on a js button

I have some js created buttons from GeeksforGeeks, but I don't know how to put on click on the buttons. I can create a button using the code I found online, but there was no explanation on how to make that button have on click function
let btn = document.createElement("button");
btn.innerHTML = 'hello';
btn.addEventListener('click',function(){
console.log('click clock!');
});
document.body.appendChild(btn);
This is how you should implement.
btn.addEventListener('click',funcName);
ex.
function onClick(){
//Your Code..
}
btn.addEventListener('click',onClick);
It is as simple as below:
<button id="submit" value="Submit" onclick="getData();">Submit</button>
function getData(){
// your logic
}
<!DOCTYPE html>
<html>
<body>
<button id="btnDemo">On-click Demo</button>
</body>
</html>
java script Code :
var btn = document.getElementById('btnDemo');
btn.onClick = function(){
alert('button is clicked..');
}
Jquery Code :
var btn = $('#btnDemo');
btn.click(function(){
alert('button is clicked..');
});
<button id="submit" value="Submit" onclick="getData();">Submit</button>
function getData(){
--write here
}
You can do it with JS and jQuery both, check both the solutions.
For JS use onlick on button , with jQuery use .click function
function runMe(){
alert('I am executed with Pure JS');
}
$('document').ready(function(){
$('#jQueryBubmit').click(function(){
alert('I am executed with jQuery');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="submit" value="Submit" onclick="runMe();">Submit</button>
<button id="jQueryBubmit" value="Submit">Submit with jQuery</button>
<body>
<script>
var button = document.createElement('BUTTON');
button.setAttribute('id','btn');
document.body.appendChild(button);
var buttonById = document.getElementById('btn');
buttonById.textContent = 'button is not clicked';
buttonById.addEventListener('click',buttonClickFuntion);
function buttonClickFuntion() {
buttonById.textContent = 'button clicked';
}
</script>
</body>
The onclick="java_script_function()" attribute can be used for handling click event on a button.
Here is a working example:
<!DOCTYPE html>
<html>
<body>
<button onclick="clickDemo()">On-click Demo</button>
<hr>
<span id="result"></span>
<script>
function clickDemo() {
document.getElementById("result").innerHTML = "Button was clicked";
}
</script>
</body>
</html>
Output:
More information:
https://www.w3schools.com/jsref/event_onclick.asp

track div class and data-id="" in javascript (jquery) as an example

there is an example
<button id="tri" style='display: block;'>add</button>
<div id="box" style='display: none;' >
tracked by id
$('#tri').on('click', function(){
var e = document.getElementById('box');
var b = document.getElementById('tri');
if(e.style.display == 'none')
$("#box").slideDown();
b.style.display = 'none';
})
need to do the same so that this button tracks but only class and data-id
<div class="block_view" data-id="52" style='display: none; ></div>
what i tried did not work
<button class="editblock" data-id="51">edit</button>
<div class="block_edit" style="display: none;" data-id="51"></div>
<script>
$('body').on('click', '.editblock', function() {
var $this = $(this),
id = $this.attr('data-id');
var b = $('.block_view[data-id=id]');
if(b.style.display == 'none')
b.style.display = 'block';
})
</script>
what am I doing wrong?
The variable id contains dynamic data but you are using that as a string, you should form the selector in a proper way.
b refers to a jQuery element, you should use .css() instead of style property.
Try the following way:
$('body').on('click', '.editblock', function() {
var $this = $(this),
id = $this.attr('data-id');
var b = $('.block_view[data-id='+id+']');
if(b.css('display') == 'none')
b.css('display', 'block');
else b.css('display', 'none');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="editblock" data-id="51">edit</button>
<div class="block_view" data-id="51" style='display: none;' >block_view</div>
You have to insert the id variable in to selector, you are just putting the literal sting id in it. Also jQuery returns a jQuery object not an element, so you can use document.querySelector instead.
var b = document.querySelector('.block_view[data-id="'+id+'"]');
You can take data-id using $(this).data('id'); and the style by $(this).css("display"). you can find all div with the data-id and show/hide based on that
$(".editblock").click(function() {
var id=$(this).data('id');
console.log(id)
var styles = $(this).css("display");
console.log(styles)
$("div").each(function(){
if($(this).attr('id') == id && $(this).css("display")=="none") {
$(this).css('display','block');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="editblock" data-id="51">edit</button>
<div class="block_edit" >
<div id="51" style="display:none">div1</div>
<div id="52" style="display:none">div2</div>
<div id="53" style="display:none">div3</div>
</div>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button class="editblock" data-id="51">edit</button>
<div class="block_edit" style="display: none;" data-id="51"></div>
<div class="block_view" data-id="51" style='display: none;'>Demo</div>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$('.editblock').click(function(){
var id = $(this).attr('data-id');
var b = $('.block_view[data-id='+id+']');
if($(b).css('display')=='none'){
$(b).css('display','block')
}
});
</script>
</html>

take div's id by referencing this

Hello everyone im trying to get the id of a div through a function in javascript like this:
<div id="txtHint" onload="getId(this);"></div>
The function is located just before </body> tag of my html page
function getId(theId) {
var name = document.getElementById(theId);
}
In the body of my html page i have a button:
<button type="button" onclick="alert(getId())">get</button>
I receive an undefined alert on clicking
How do i get the div's id?
Anyone can help?
Though I don't know the use case of this, you can pass the id to the function and return that from the function:
function getId(theId) {
var name = document.getElementById(theId);
return name.id;
}
<div id="txtHint"></div>
<button type="button" onclick="alert(getId('txtHint'))">get</button>
Update: If you want to get all id's by tag, simple pass the tag to the function and get all the id's of those element:
function getId(el) {
var element = document.querySelectorAll(el);
var id = [...element].map(i=>i.id).filter(i=>i);
return id;
}
<div id="txtHint1">First</div>
<div id="txtHint2">Second</div>
<div id="txtHint3">Third</div>
<div id="txtHint4">Fourth</div>
<button type="button" onclick="alert(getId('div'))">get</button>
The way your functions is written the only way is to have global variable
var divId = null;
function getId(div) {
divId = div.id;
}
function getId() {
alert(divId);
}
And here is my suggetions on doing it
First way is to "mark" the div at onload event and get the id of it using this "mark"
function markDiv(thisDiv) {
thisDiv.classList.add('mark')
}
function getMarkedDiv() {
var div = document.querySelector('.mark');
alert(div.id);
}
<div id="Mark" onload="markDiv(this)" class="mark"></div>
<button onclick="getMarkedDiv()">button</button>
Another way is to wrap the button and the div inside one parent
function getMySiblingId(button) {
alert(button.parentElement.firstElementChild.id);
}
<div id="Parent">
<div id="Mark"></div>
<button onclick="getMySiblingId(this)">Button</button>
</div>
Or the easiest way is to wrap button inside the desired div
function getId(btn) {
alert(btn.parentElement.id);
}
<div id="Mark">
<button onclick="getId(this)">Click me</button>
</div>
<div id="Alice">
<button onclick="getId(this)">Click me</button>
</div>
<div id="Charlie">
<button onclick="getId(this)">Click me</button>
</div>
Of course in all this scenarios i didn't assume that you want to get ids of multiple divs
so i remade the code
function divField(theDivFieldId) {
var name = document.getElementById(theDivFieldId);
return name.id;
}
html
<div id="txtHint" onload="alert(divField(this));"></div>
and nothing happens

Add/remove a class in html using a js function

I want to add a class to body in HTML using Javascript using a button that executes a function, then remove it using another button. But I want to save that class, until the other button is pressed, using LocalStorage.
I can do that without LocalStorage
$$('body').addClass('Class here');
But how with LocalStorage?
By using Storage.setItem to save, then Storage.getItem to retrieve, like this:
var className = "theclass";
// Put the class name into storage
localStorage.setItem('className', className);
// Retrieve the class name from storage
var retrievedClassName = localStorage.getItem('className');
$('body').addClass(retrievedClassName);
Here a working code with jquery:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body class="">
<div class="form-group">
<button class="button">your button</button>
</div>
<script>
var className = "theclass";
jQuery('.button').on( 'click', function(){
localStorage.setItem('className', className);
jQuery('body').addClass(className);
});
// Retrieve the class name from storage
var retrievedClassName = localStorage.getItem('className');
jQuery('body').addClass(retrievedClassName);
</script>
</body>
</html>
And here without:
<html>
<head></head>
<body id="mybigbody" class="">
<div class="form-group">
<button id="button">your button</button>
</div>
<script>
var className = "theclass";
var body = document.getElementById("mybigbody");
document.getElementById('button').onclick = function(e) {
localStorage.setItem('className', className);
body.setAttribute("class", className);
e.stopPropagation();
}
// Retrieve the class name from storage
var retrievedClassName = localStorage.getItem('className');
if(retrievedClassName)
body.setAttribute("class", retrievedClassName);
</script>
</body>
</html>

Categories

Resources