So, I have 3 variables as seen below, assume they are assigned values.
What I want to do is to insert those variables into img class "myimg2", p class "myname2" and p class "myprof2" when the user clicks the div class="info2".
It has to be in that div because I want the user to click anywhere on that div to change all 3 values.
Is this possible in Javascript?
Javscript:
var storeOnClick,
name,
prof;
HTML
<table class="table2" rules="rows">
<tr>
<td>
<div class="info2" onclick="changeStats(this)" >
<div style="float:left">
<img class="myimg2"style="max-height:80px;" src="Pictures/QuestionMark.png">
</div>
<div style="float:left;">
<p class="myname2">Name: Jane Doe</p>
<p class="myprof2">Profession: Something</p>
</div>
</div>
</td>
<td>
<div class="info2" onclick="changeStats(this)" >
<div style="float:left">
<img class="myimg2"style="max-height:80px;" src="Pictures/QuestionMark.png">
</div>
<div style="float:left;">
<p class="myname2">Name: Jane Doe</p>
<p class="myprof2">Profession: Something</p>
</div>
</div>
</td>
</tr>
</table>
Ok, I think I've got the code. The way I'm doing it is attaching an event handler to the body of the page. Then in that function, I detect if you clicked on a .info element (or one of it's children). If you did, then I change out the values of that particular .info div
Super important parts:
// add an event listener to the entire body. I could have iterated through each div with the '.info2' class instead
if (document.body.addEventListener) {
document.body.addEventListener('click', updateCard, false);
} else {
document.body.attachEvent('onclick',updateCard); // stupid IE
}
// this is the callback function for the click event handler
function updateCard(e) {
e = e || window.event;
var target = e.target || e.srcElement; // more IE stuff
// does target have an ancestor of .info2 ?
var el = findAncestor(target, 'info2');
if (el) {
// which elements do we want to update? Only the currently clicked on .info2
var iImg = el.querySelector('.myimg2');
var iName = el.querySelector('.myname2');
var iProf = el.querySelector('.myprof2');
// assign the values a random element from the arrays
storeOnClick = imgArray[Math.floor(Math.random()*imgArray.length)];
name = nameArray[Math.floor(Math.random()*nameArray.length)];
prof = profArray[Math.floor(Math.random()*profArray.length)];
iImg.src = storeOnClick;
iName.innerHTML = lblName + name;
iProf.innerHTML = lblProf + prof;
}
}
// this is similar to jQuery's $.parents('.class')
function findAncestor (el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
demo
For fun, here's what it might look like in jQuery:
$(function() {
$('.info2').on("click",function() {
var t = $(this);
t.find('.myimg2').attr('src',storeOnClick);
t.find('.myname2').html(name);
t.find('.prof2').html(prof);
});
});
Try this:
Insert the new onClick in info2:
<div class="info2" onclick="change_text()">
Also change class to ID for your fields. For example: class="myname2" to id="myname2"
Javascript:
function change_text() {
var text1 = document.getElementById('myname2');
var text2 = document.getElementById('myprof2');
var img1 = document.getElementById("myimg2");
if (text1.innerHTML === "Name: Jane Doe") {
text1.innerHTML = "test";
}
if (text2.innerHTML === "Profession: Something") {
text2.innerHTML = "test";
}
if (img1.src == "link here") {
img1.src = "link here";
}
}
Kinda messy method but it will be easier for you to understand from this method :)
DEMO
Related
I need some help.. the idea behind this is like a simple toggle button that can hide the object and replacing the empty area with ****.
I was thinking it was more like in a Password form input where you can hide password by clicking the Eye icon. However, I needed something that are not required input form, something that is just simple DIV
function toggler(divId) {
$("#" + divId).toggle();
.css('content', 'sadas');
}
.hidden {
display:none;
}
this is a test
<div id="myContent" class='hidden'>
<div>this is a test #1 </div>
</div>
I can hide the DIV but leaving the empty area, how can I replace this empty area with ***** ??
example:
My balance is $200 [hide]
My balance is **** [show]
https://jsfiddle.net/qobgfLh6/
I have written a fiddle.
There are some points that can be better managed.
But I think you are looking for something like that.
The idea is to add another div with the **** placeholder and use toggleClass() function of jQuery.
$("#" + divId).toggleClass('hidden');
$("#myPlaceholder").toggleClass('hidden');
https://jsfiddle.net/qze8fydv/
Try to use something like this.
$(document).ready(function () {
function handle(input, toggler) {
var inputValue = ""
var shouldShowAsterisks = false
input.change(function () {
inputValue = $(this).val()
})
toggler.click(function () {
shouldShowAsterisks = !shouldShowAsterisks
shouldShowAsterisks
? input.val("*".repeat(inputValue.length))
: input.val(inputValue)
input.prop("disabled", shouldShowAsterisks)
})
}
handle($(".enter"), $(".toggler"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="enter" />
<button class="toggler">Hide</button>
function toggleElementMask(element){
//Regex to find *
let reg = /^\*+$/g;
//If all * we are masked
let isMasked = element.innerText.match(reg);
if(!isMasked) {
//Store the original text
element.dataset.original = element.innerText;
//Replace the contente with the same amount of *
element.innerText = "*".repeat(element.innerText.length);
}else{
//Restore the text
element.innerText = element.dataset.original;
}
}
//Mask on page load
$(".masked").each(function(){
toggleElementMask(this);
});
//Click event handler
$(".toggleMask").on("click", function(e){
e.preventDefault();
toggleElementMask($($(this).attr("href"))[0]);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
this is a test
<div id="myContent" class='masked'>
<div>this is a test #1 </div>
</div>
this is a test
<div id="myContent2" class='masked'>
<div>Another one</div>
</div>
this is a test
<div id="myContent3" class='masked'>
<div>one with <span>a</span> span</div>
</div>
I want to get a specific element when the button clicked. I select the clicked data with DOM Traversal method, Is there any method I can use to get an element faster?
<div class="item" id="dessert">
<div class="item-image-div">
<img src="mcd/<?= $row["image"]; ?>" alt="" class="item-image" onclick="getSrc(this.src)">
</div>
<div class="item-detail">
<div class="item-name" onclick="getSrc(this.name)"><?= $row["item"]; ?></div>
<div class="item-order">
<div class="item-price"><?= $row["price"]; ?></div>
<button class="order">
<img src="icon/order.png" alt="" width="40px">
</button>
</div>
</div>
</div>
let orderBtn = document.querySelectorAll('.order');
orderBtn.forEach(function(btn){
btn.addEventListener('click', (e)=>{
if (e.target.parentElement.classList.contains('order')) {
let fullPath = e.target.parentElement.parentElement.parentElement.previousElementSibling.children[0].src;
let pos = fullPath.indexOf('mcd') + 3;
let partPath = fullPath.slice(pos);
let itemId = e.target.parentElement.parentElement.parentElement.parentElement.id;
const item = {};
item.img = `${partPath}`;
console.log(item);
let itemName = e.target.parentElement.parentElement.previousElementSibling.textContent;
let itemPrice = e.target.parentElement.previousElementSibling.textContent;
console.log(itemName);
console.log(itemPrice);
}
});
});
Instead of adding a listener to the button and checking inside the handler that the clicked parent is the .order, add a listener to the <img> instead. (Or, is that even needed? Could you permit clicks on both the <img> and the outer <button>, maybe? That'd make more sense to me, if possible)
Utilize .closest to avoid having to use lots of difficult-to-read .parentElement accesses.
Use querySelector to readably navigate down to descendants of the whole .item.
document.querySelectorAll('.order > img').forEach((img) => {
img.addEventListener('click', () => {
const item = img.closest('.item');
const fullPath = item.querySelector('img').src;
const pos = fullPath.indexOf('mcd') + 3;
const partPath = fullPath.slice(pos);
const itemId = item.id;
const itemName = item.querySelector('.item-name').textContent;
const itemPrice = item.querySelector('.item-price').textContent;
});
});
I have problem with my code.
I have products on my website, each product has his own <a><h1>CODE</h1></a> and I need to take this CODE and paste it before an image. I need to copy element with has class="loop1" and paste it into another element with class="lop1" and then take another element with class="loop2" and paste into element with class="lop2" and so on..
I made class with same numbers for easier copying, but it doesnt work. Can sombody help me?
This is my code:
$('#loop').addClass(function(i) {
return 'lop'+(i+1);
});
$('.p-name').addClass(function(i) {
return 'loop'+(i+1);
});
function doForm() {
var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];
for (var i=0;i<numb.length;i++) {
number = numb[i];
selector = '.loop' + number;
if ($(selector).length != 0) {
val = $(selector).html();
$('lop' + number).html(val);
}
}
}
doForm();
Related html:
<div class="columns">
<div id="loop" class="lop1"></div>
<div class="p-image">
<img src="https://" width="290" height="218">
</div>
<div class="p-info">
<span itemprop="name">PRODUCT</span>
</div>
<div>
So I need to take from "p-info > a" and paste it into div "lop1". Depends on number in class copy and paste HTML into div with same number.
Change $('lop' + radek).html(val); to $('.lop' + number).html(val);
Notice the . at the beginning of lop, it will create a selector to fetch element based on the class.
$('#loop').addClass(function(i) {
return 'lop'+(i+1);
});
$('.p-name').addClass(function(i) {
return 'loop'+(i+1);
});
function doForm() {
var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];
for (var i=0;i<numb.length;i++) {
var number = numb[i];
var selector = '.loop' + number;
if ($(selector).length != 0) {
var val = $(selector).html();
$('.lop' + number).html(val);
}
}
}
doForm();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="columns">
<div id="loop" class="lop1"></div>
<div class="p-image">
<img src="https://" width="290" height="218">
</div>
<div class="p-info">
<span itemprop="name">PRODUCT</span>
</div>
<div>
I am trying to make a page where the user selects an item in a drop-down list, which then will create a duplicate drop-down list. The last drop-down list always needs to create a new one once an item is selected.
Using the following javascript code
<script type="text/javascript">
$(document).ready(function () {
$(function listselect() {
if (x == null) {
var x = 1;
}
//need to increment x after the completion of the following funciton so the function will trigger on different drop-down lists
$('#FooId' + x).change(function q() {
$('#FooId' + x).clone().attr('id', 'FooId' + (++x)).attr('name', 'Selected').insertAfter('#FooId' + (x - 1))
//return x;
});
//return x;
});
});
</script>
and the razor html
<div class ="container">
<div class="label">
#Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
#Html.DropDownList("FooId", Nothing, "--Select--", New With {.Name = "Selected", .Id = "FooId" & "1"})
//#*#Html.ValidationMessageFor(Function(model) model.Foo)*#
</div>
</div>
I am able to make the first list clone itself, but how do you return x from function q so that it can be used by its own function (Function q needs to trigger when an item is selected in Foo1, then Foo2, etc.).
(Sorry if this doesn't make sense, I am not sure how to word it. I am very new to coding). Thanks.
If I got you right, you don't need most of your code. And it's easier to use classes here. Just do it like this:
$(document).ready(function () {
$('.foo').on('change', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
});
And your markup part should be like this:
<div class ="container">
<div class="label">
#Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
#Html.DropDownList("FooId", Nothing, "--Select--", new {name = "Selected", #class = "foo" })
</div>
</div>
I don't remember Html.DropDownList signature so I created simple jsfiddle without it. I hope this is what you needed.
UPDATE:
I've corrected my fiddle as follows:
$(document).on('change', '.foo:last', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
Now it doesn't add extra selects if it's not the last select that was changed.
I have an HTML structure like so:
<tr class = "#rowOrdinal" id = "...">
<td>
<a href = "#">
<img src = "/Content/updateIcon.gif" class = "updateResourceImageButton" id = "..." />
</a>
<a href = "#">
<img src = "/Content/cancelIcon.gif" class = "cancelImageButton" />
</a>
</td>
<td class = "hiddenColumn" id = ...>...</td>
<td class = "resourceKeyColumn" id = ...>...</td>
... and so on...
When the update link is clicked, I'd like to get the reference to the row, i.e. tr element in which the update hyperlink was.
So, in the below event listener, I'd like to go up the DOM hierarchy a few levels. I could use simple JavaScript and use a while loop to get the parentNode, but how would I do that with jQuery?
function WireHandlers() {
$('.updateResourceImageButton').click(UpdateResourceLinkClickedHandler);
}
function UpdateResourceLinkClickedHandler() {
// how do I get a reference to the tr that contains
// the hyperlink which is the source of this event?
}
$(document).ready(function () { WireHandlers(); });
You are looking for .closest() method:
function UpdateResourceLinkClickedHandler() {
var $tr = $(this).closest('tr');
}
function WireHandlers() {
$('.updateResourceImageButton').click( function(){
var trParent = $( this ).parent().parent();
UpdateResourceLinkClickedHandler();
});
}
Not sure why you need parent tr reference, so haven't used it in my example