when i click label, prompts make result - javascript

I make HTML file and js file but i had some problems.
In HTML there are 5 labels tag(and there's no specific id or class name) and when i click each label, pop-up(prompt) appear, and it make result(change style).
Changing style is not difficult so i am okay but i have a problem in prompt.
I wrote this code:
function changeCol(evnt) {
var theEvent = evnt ? evnt : window.event;
var label = document.getElementsByTagName("label");
label[0].addEventListener ("click", function (){
var one = prompt("Enter the color");
label[0].style.color = one;
});
label[1].addEventListener ("click", function (){
var two = prompt("Enter the color");
label[1].style.color = two;
});
label[2].addEventListener ("click", function (){
var three = prompt("Enter the color");
label[2].style.color = three;
});
}
But when i click a label first, it is okay buy when i click 2nd prompt appear twice... and 3rd click show prompt three times...
And when i want to see prompt i have to click twice and maybe it is because of function. In js there.
function loadevent(){ ...
if (label){
for (i=0;i < label.length; i++){
label[i].onclick = changeCol;
}
}
}
What should i do?

Hi try using the below code snippet:-
var label = document.getElementsByTagName("label");
function changeCol(element) {
element.addEventListener ("click", function (){
var promcolor= prompt("Enter the color");
element.style.color = promcolor;
});
}
function loadevent(){
if (label){
for (i=0;i < label.length; i++){
changeCol(label[i]);
}
}
}
loadevent();
And I assumed below HTML
<p><label for="1">label-1</label></p>
<p><label for="2">label-2</label></p>
<p><label for="3">label-3</label></p>
I dont see much use of loadevent function . But seeing the dots I assume there is some other code there. But if its not you can simply have one function like below:
function loadevent(){
for (itr=0;itr < label.length; itr++){
label[itr].addEventListener ("click", function (){
var promcolor= prompt("Enter the color");
this.style.color = promcolor;
});
}
}
Also the issue with your code was even while you iterate the element in loadevent function you add event listeners for all labels. This wont happen with this code.

Problem:
The problem with your actual code is that for each label you use this label's index and loop according to this index an alert a prompt, that's why you get only one prompt with the first label, two prompts with the second and three with the third label.
Solution:
The best approach is to use addEventListener like in your first function and loop through all labels using document.getElementsByTagName("label")and use this keyword to change color of the clicked label inside the loop, here's what you need :
var labels = document.getElementsByTagName("label");
for (i = 0; i < labels.length; i++) {
labels[i].addEventListener("click", function() {
var prmt = prompt("Enter the color");
this.style.color = prmt;
});
}
<label> A</label><br>
<label> B</label><br>
<label> C</label><br>
<label> D</label><br>
<label> E</label><br>
Note:
Using this code you don't need to specify any id or class or other attribute to your labels.
And then you just need to put this code inside your load function and call it in windows load:
function loadevent(){
var labels = document.getElementsByTagName("label");
for (i = 0; i < labels.length; i++) {
labels[i].addEventListener("click", function() {
var prmt = prompt("Enter the color");
this.style.color = prmt;
});
}
]

here you have written script of opening prompt in for loop hence it generate multiple popup depending on label number. i.e if you clicked on 4th label then it will open prompt 4 times.
To avoid this you have to pass index of current label.
function loadevent(){
if (label){
for (i=0;i < label.length; i++){
label[i].onclick = changeCol(i);
}
}
}
function changeCol(index,evnt) {
var theEvent = evnt ? evnt : window.event;
var label = document.getElementsByTagName("label");
label[index].addEventListener ("click", function (){
var current_color = prompt("Enter the color");
label[index].style.color = current_color;
});
}
This may helps you.

Related

Drag and drop event sometimes doesnt execute the DOM

I have a textarea that has the id = display
javascript:
<script>
function drag(event) {
event.dataTransfer.setData("text", this.event.target.src);
}
function drop(event) {
event.preventDefault();
let data = event.dataTransfer.files;
for (file of data) {
var l = document.getElementById('display').selectionStart;
var text = document.getElementById("display").value;
sub1 = text.substring(l,0);
var len = text.length;
var l2 = sub1.length;
sub2 = text.substring(len,l2);
var test = sub1 + file.name + sub2;
var end = document.getElementById("display").textContent = test;
alert(end);
}
}
function allow(event) {
event.preventDefault();
}
</script>
I type in some text and want to put the dragged file in between the text. When i run this code, the alert shows the correct content, but the DOM never updates.
This only occurs when i input text in the area myself. For example if text is already in the field and i drag and drop the DOM wont update even though the alert shows the correct content.
I have spent countless hours trying to debug this but cant seem to find a solution.
The demo below you will see if you type in the textarea it doesnt work with the drag and drop. But if you dont press any keys and just keep on dragging images it will work
Demo here
Thanks.
This line:
var end = document.getElementById("display").textContent = test;
Should be:
var end = document.getElementById("display").value = test;
.textContent is replaced with .value

javascript dynamically remove text

I have successfully created a button which adds text to the webpage however I do not know a viable way to remove text once this has been created. The js code I have is:
var addButtons = document.querySelectorAll('.add button');
function addText () {
var self = this;
var weekParent = self.parentNode.parentNode;
var textarea = self.parentNode.querySelector('textarea');
var value = textarea.value;
var item = document.createElement("p");
var text = document.createTextNode(value);
item.appendChild(text)
weekParent.appendChild(item);
}
function removeText() {
//document.getElementbyId(-).removeChild(-);
}
for (i = 0; i < addButtons.length; i++) {
var self = addButtons[i];
self.addEventListener("click", addText);
}
I have viewed various sources of help online including from this site however I simply cannot get any to work correctly. Thank you in advance.
Sure, it should be easy to locate the added <p> tag relative to the remove button that gets clicked.
function removeText() {
var weekParent = this.parentNode.parentNode;
var item = weekParent.querySelector("p");
weekParent.removeChild(item);
}
If there is more than 1 <p> tag inside the weekParent you will need a more specific querySelector.

Dynamic drop down menu will not create based on selection

So i'm working on a project that creates three drop down menus that appear based on the option selected on the first. When I select from the first menu, "Male" or "Female" the correct menus appear( example, when Male is selected, the drop down with the options ""Human", "Dwarf", "Orc" appear). However, after that I can not get a third drop down menu to appear based on the next selection using the same methods before. At this point I am very lost.
var step1 = ["Choose Gender?", "Male", "Female"];
var step2 = [["Choose your race!", "Human", "Dwarf", "Orc"],["Choose your race!", "Fairy", "Elf", "Centaur"]];
var step3 = [["Human Class!", "Warrior", "Sorcerer", "Theif"], ["Elf Class!", "Cleric", "Necromancer", "Priest"], ["Dwarf Class!", "Cannonner", "Rifelman", "Engineer"], ["Orc Class!", "Beserker","Warlock", "Shaman"], ["Fairy Class!", "Druid", "Arcanist", "Mystic"]];
function testData(){
menuCreate(step3[0]);
}
function init() {
menuCreate(step1);
var dropdown = document.getElementById("form");
dropdown.onchange = function(event){
if (dropdown.value == "Male"){
//menuCreate(step2[0]);
var myDiv = document.getElementById("mainDiv");
var next = document.createElement('input');
next.setAttribute('type','button');
next.setAttribute('value','Next');
next.setAttribute('onclick','maleRace()');
myDiv.appendChild(next);
} else if (dropdown.value == "Female"){
//menuCreate(step2[1]);
myDiv = document.getElementById("mainDiv");
femaleNext = document.createElement('input');
femaleNext.setAttribute('type','button');
femaleNext.setAttribute('value','Next');
femaleNext.setAttribute('onclick','femaleRace()');
myDiv.appendChild(femaleNext);
}
}
} // end init()
function menuCreate(step1){
//console.log(step1);
var myDiv = document.getElementById("mainDiv");
var titleElement = document.createElement("h1");
titleElement.setAttribute('style','color:white');
titleElement.setAttribute('id','guide');
var selectForm = document.createElement('select');
selectForm.id = "form";
myDiv.appendChild(selectForm);
for (var i=0; i< step1.length; i++){
var option = document.createElement('option');
option.value = step1[i];
option.text = step1[i];
selectForm.appendChild(option);
}
} // end menuCreate()
function maleRace(){
menuCreate(step2[0]);
var down = document.getElementById("form");
down.onchange = function(event){
if (down.value == "Human"){
menuCreate(step3[0]);
var div = document.createElement("div");
var next = document.createElement('input');
next.setAttribute('type','button');
next.setAttribute('value','Next');
next.setAttribute('onclick','maleRace()');
div.appendChild(next);
}
}
} // end maleRace()
Please note I cant use JQUERY or innerHTML/innerText. I have to do this using normal JavaScript the problem is that when I select "Human" on the second menu, I am supposed to get another menu that uses step3[0].
In the menuCreate function, you're setting an id attribute to the select element: selectForm.id = "form";. After you call it for the second time (for the second step), you have two elements with the same id in your document. Then, when you try to add the onchange event handler on the maleRace function - document.getElementById("form"); down.onchange = function(event){ you actually attach this handler to the first select element (the gender one) instead of the second one.
A nice way to solve this problem, will be to add a second argument to the menuCreate function like so: function menuCreate(step1, id){. Then, change this line a bit from selectForm.id = "form"; to selectForm.id = id;.
Then, change every call to the createMenu function to have its own id:
function init() {
menuCreate(step1, 'step1form');
var dropdown = document.getElementById("step1form");
function maleRace(){
menuCreate(step2[0], 'step2form');
var down = document.getElementById("step2form");
You can check out this codepen: https://codepen.io/anon/pen/xXJwBv?editors=1011

javascript: set onclick function with a parameter for a button

I have created a button using javascript and now I want to give it a onclick. however I want the function to have a parameter i. the problem is that when I inspect the console the onclick function is just onclick=playAudio(i). I want it to be different for each value of i in the for loop, but because it is in brackets it just stays as i instead of the current number in the for loop. I hope I have explained this properly. some of the code is below to help you understand.
var i;
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];
for(i = 0; i < audioMp3.length; i++{
var audioBtn = document.createElement("BUTTON");
audioBtn.setAttribute("onclick", "playAudio(i);";
}
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];
for(var i = 0; i < audioMp3.length; i++){
var node = document.createElement("BUTTON");
var textnode = document.createTextNode(audioMp3[i]);
node.appendChild(textnode);
node.setAttribute("onclick", "playAudio("+i+");");
document.getElementById("element").appendChild(node);
}
function playAudio(i){
alert(i);
}
<div id="element"></div>
I'm pretty sure that this should work :
audioBtn.setAttribute("onclick", "playAudio("+i+");");
audioBtn.onclick = function(){
playAudio(i)
}
Create an array with all the possible values, loop through the values to create the buttons, each button should have their click event listener to play their own button's song.
I don't know your precise code but that is the pseudo-code to do it.

Get JavaScript Object

I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")

Categories