Supposed to get the child but somehow gets the parent ID - javascript

Good day. I have a code. To my understanding, the clicked2 should get the id "Third" since it's looking for the children. But somehow, it always get the id "First". How do i get the "Third"?
<!DOCTYPE html>
<html>
<body>
<div class="menu" id="First">
<button id="Second">eee</button>
<button id="Third">yyy</button>
</div>
<div class="holder"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).on('click', '.menu', function(e) {
var clicked = e.target.id || this.id;
var clicked2 = e.target.children.id || this.id;
var y = clicked2.replace(/\D/g, '');
var x = clicked.replace(/\D/g, '');
var w = 0;
$('.holder') .append('<BR>'+clicked+'<BR>'+clicked2);
});
</script>
</body>
</html>

Add this var clicked2 = $(this).children("button").next().attr("id")
It will return id of the second button.
Try this
$(document).on('click', '.menu', function(e) {
var clicked = e.target.id || this.id;
var clicked2 = $(this).children("button").next().attr("id") || this.id;
var y = clicked2.replace(/\D/g, '');
var x = clicked.replace(/\D/g, '');
var w = 0;
$('.holder') .append('<BR>'+clicked+'<BR>'+clicked2);
});
Demo Here

children() returns all the childrens, so you need to adress the right one:
var clicked2 = $(this).children().next().attr("id");

Related

Why does content of h1 tag doesnot change after clicking reset button?

var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1").innerHTML = "<h1>0 to 0</h1>";
});
// it doent work when i add textcontent in place of inner html
> why does content of h1 doesnot change when i click reset button.
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
<script type="text/javascript" src="score.js"></script>
</html>
why does content of h1 doesnot change when i click reset button.
Problem :
document.getElementsByTagName returns an array so you will need index you could use
document.getElementsByTagName("h1")[0].innerHTML = "<h1>0 to 0</h1>";
But a better version is this :
var one = document.getElementById("one"),
two = document.getElementById("two"),
reset = document.getElementById("reset"),
i = 0,
j = 0;
one.addEventListener("click", function() {
i ++;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j ++;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
i = 0 , j = 0
document.getElementById("resetId").innerHTML = "<span id="d1">0</span> to <span id="d2">0</span>"; // Thanks to #Micheale
});
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1 id='resetId'><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score.js"></script>
</body>
</html>
You are using getElementsByTagName which doesn't return a single element like getElementById. It returns an HTMLCollection/NodeList (depending on which browser), but you can just treat it like a standard array.
You should select the first element by using getElementsByTagName[0] instead.
You can either use innerHTML or textContent, but they do different things.
innerHTML would replace the contents of the h1 tag with whatever you assign. So, document.getElementsByTagName("h1").innerHTML = "<h1>0 to 0</h1>"; would output two h1 elements, which you don't want.
So in either case, set innerHTML or textContent to simply 0 to 0
var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1")[0].innerHTML = "0 to 0";
});
// it doent work when i add textcontent in place of inner html
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
</html>
document.getElementsByTagName("h1") returns an array so you have to select the h1 you want.
Your code modified to take first h1 (assuming it is always the good one).
var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1")[0].innerHTML = "<h1>0 to 0</h1>";
});
// it doent work when i add textcontent in place of inner html
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
<script type="text/javascript" src="score.js"></script>
</html>
Three problems here:
1- getElementsByTagName returns an array, not an element. You can retrieve the first element of the array with "[0]" as I've done in the snippet.
(I'd recommend giving that header an id.)
2- Problems with the innerHTML for h1. When replacing the h1 innerHTML, there's no need to repeat the h1 tags (you end up with nested h1s). But another problem is that you shouldn't forget the d1 and d2 spans, otherwise the code breaks.
3- Also, don't forget to reset i and j
var one = document.getElementById("one");
var two = document.getElementById("two");
var reset = document.getElementById("reset");
var i = 0;
var j = 0;
one.addEventListener("click", function() {
i = i + 1;
document.querySelector("#d1").textContent = i;
});
two.addEventListener("click", function() {
j = j + 1;
document.querySelector("#d2").textContent = j;
});
reset.addEventListener("click", function() {
document.getElementsByTagName("h1")[0].innerHTML = '<span id="d1">0</span> to <span id="d2">0</span>';
i = j = 0;
});
// it doent work when i add textcontent in place of inner html
<!DOCTYPE html>
<html>
<head>
<title>Score Keeper</title>
</head>
<body>
<h1><span id="d1">0</span> to <span id="d2">0</span></h1><br>
<p>Playing To : 5</p><br>
<input type="number">
<button id="one">Player One</button>
<button id="two">Player Two</button>
<button id="reset">Reset</button>
</body>
<script type="text/javascript" src="score.js"></script>
</html>
EDIT: I see some other people have got here first, but I'll leave my answer up for now because the other answers don't maintain the spans with id d1 and d2, which makes the code fail after hitting reset

Changing data-value when Clicked not working

value when clicked tried these codes but when i inspect the elements the value is not changing
<div id="foo" data-value="3">Click Here</div>
This is the JavaScript
$("#foo").on('click', function(){
var foo1 = $(this);
var c = foo1.attr('data-value');
var sum = parseInt(c) + parseInt(3);
$("#foo").data("data-value", sum);
});
To set the attribute value you can use attr, like you get the attribute value with attr. Try the following:
$("#foo").on('click', function(){
var foo1 = $(this);
var c = foo1.attr('data-value');
var sum = parseInt(c) + parseInt(3);
a = foo1.attr("data-value", sum);
console.log(foo1.attr("data-value"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" data-value="3">Click Here</div>

how do i get same DIV name or id when it change into input field

I want to make editable list like MySQL but i can't get same DIV id when it's change to input field...can anyone tel me how to do that....
this is my code...
//<![CDATA[
$(window).load(function() {
$.fn.editable = function() {
var textBlocks = $(this);
for (var i = 0; i < textBlocks.length; i += 1) {
var textBox = $('<input class="my-text-box" onchange="myFunction(this.value)" />');
var textBlock = textBlocks.eq(i);
textBox.hide().insertAfter(textBlock).val(textBlock.html());
}
textBlocks.dblclick(function() {
toggleVisiblity($(this), true);
});
$('.my-text-box').blur(function() {
toggleVisiblity($(this), false);
});
toggleVisiblity = function(element, editMode) {
var textBlock,
textBox;
if (editMode === true) {
textBlock = element;
textBox = element.next();
textBlock.hide();
textBox.show().focus();
textBox[0].value = textBox[0].value;
} else {
textBlock = element.prev();
textBox = element;
textBlock.show();
textBox.hide();
textBlock.html(textBox.val());
}
};
};
var $edit = $('.makeEditable').editable();
});
function myFunction(val) {
document.writeln(val);
}
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<div class="makeEditable" id="fname">First Name</div>
<div class="makeEditable" id="lname">Last Name</div>
<div class="makeEditable" id="contacts">00 000 0000</div>
<div class="makeEditable" id="email">test#yourdomain.com</div>
please HELP me on this.....
You can get div id when it's change to input field like following.
In if (editMode === true) {} block add var divId = element.attr('id')); like below.
if (editMode === true) {
var divId = element.attr('id'));
console.log(divId);
}
Hope it will help you.

Change Div background color using HEX value stored in json file

(I updated my code to remove the br from info2)
I want to use jQuery to read a JSON file (it contains a color name and its hex value) and load the color names into a drop-down select (I got this part working). Then I want the div next to the drop-down select to change to the selected color when the user changes the value of the drop-down select. How do I change the div background color to that of the hex value for the color the user selects?
My page:
<script language="javascript" type="text/javascript">
var JSON_Response;
$(document).ready(function () {
$.getJSON('Colors.json', function (data) {
JSON_Response = data;
var mySelect = document.getElementById("selColor");
for (i = 0; i < JSON_Response.Colors.length; i++) {
var myOption = document.createElement("option");
myOption.text = JSON_Response.Colors[i].colorName;
myOption.value = i;
try {
mySelect.add(myOption, mySelect.options[null]);
}
catch (e) {
mySelect.add(myOption, null);
}
}
});
$("#selColor").change(function () {
var myIndex = $("#selColor").val();
$("#showColor").attr("src", JSON_Response.Colors[myIndex].hex);
var info = JSON_Response.Colors[myIndex].colorName + "<br />";
info += JSON_Response.Colors[myIndex].hex+ "<br />";
var info2 = JSON_Response.Colors[myIndex].hex;
$("#divDisplay").html(info).css({'background-color' : '#' + info2});
});
});
</script>
Don't append <br /> to info2, since it's supposed to just contain a color code.
var info2 = JSON_Response.Colors[myIndex].hex;
You basically have it. The error is in the background-color value you're setting for the div.
$("#divDisplay").html(info).css({'background-color' : '#' + info2});
should read
$("#divDisplay").html(info).css({'background-color' : '#' + JSON_Response.Colors[myIndex].hex});
Basic working fiddle example
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<button>Click me</button><br/>
<div id="myDiv" style="height:400px;width:400px;">
</div>
<script>
var hexChars = "ABCDEF0123456789";
function getColor() {
var colorStr = "";
for(var idx=0; idx < 6; idx++ ) {
colorStr += hexChars.charAt(Math.floor(Math.random() * hexChars.length));
}
return colorStr;
}
$('document').ready(function() {
$('button').click(function() {
var rand = getColor();
$('#myDiv').html('#' + rand).css({ 'background-color' : '#' + rand });
});
});
</script>
</body>
</html>

Increase ID number as a button is clicked in js

I have a button each time it is clicked, a new select input will be added. But I want the id and name of the select changed as well.My codes was:
<section>
<div class="container">
<select id="myId_1" name="myName_1">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</section>
<button type="button" id="myBtn">add</button>
$(document).ready(function () {
$('#myBtn').click(function(){
var addEvent = $('.container').html();
var addEventCell = $('<div class="container">'+addEvent+'</div>');
$('section').append(addEventCell);
});
});
But my code just duplicates the id and name of select. I want it to change to myId_2, myName_2,myId_3,myName_3 and so on.
I am new to javascript. It could be easy to you guys. Thanks for help !
this is the link for JSFiddle working here. It may be useful for you
$(document).ready(function () {
$('#myBtn').click(function(){
var addEvent = $('.container').html();
var selectid = $('section :last-child select').attr('id');
var selectname = $('section :last-child select').attr('name');
var tempId = parseInt(selectid.split('_')[1])+1;
var tempName = parseInt(selectname.split('_')[1])+1;
var addEventCell = $('<div class="container">'+addEvent+'</div>');
var newId = selectid.split('_')[0]+"_"+tempId;
var newName = selectname.split('_')[0]+"_"+tempName ;
var select = $('select', addEventCell);
select.attr('id', newId).attr('name', newName);
$('section').append(addEventCell);
});
});​
$(document).ready(function () {
$('#myBtn').click(function(){
var addEvent = $('.container:last').html();
var addEventCell = $('<div class="container">'+addEvent+'</div>');
var select = $('select', addEventCell);
var oldId = select.attr('id');
var newId = oldId.split('_')[0] + '_' + (parseInt(oldId.split('_')[1]) + 1);
select.attr('id', newId).attr('name', newId);
$('section').append(addEventCell);
});
});​
http://jsfiddle.net/QVYhu/

Categories