I want to call myfunc() using the id button, how I do that?
I dont want to use nothing but the id to call this function..what code I need to add in my script?
<html>
<head>
<script>
function myfunc() {
var count = 0;
var line = 0;
var i = 0;
var phrase = document.getElementById('phrase').value;
var filter = document.getElementById('filter').value;
var arr = phrase.split(" ").reverse();
for (i = 0; i < arr.length; i++) {
if (arr[i].search(filter) == -1) {
if (line % 2 == 0) {
document.getElementById('words').innerHTML += " <u><span class='word' style='background:#D8D8D8; border:1px solid black; ' >
" + arr[i] + "</span></u>";
line++;
} else {
document.getElementById('words').innerHTML += " <span class='word' style='background:#D8D8D8; border:1px solid black; '>
" + arr[i] + "</span>";
line++;
}
}
if ((arr[i].search(filter) != -1) && (filter)) {
count++;
}
}
document.getElementById('count').innerHTML = count + " word(s) filtered out";
}
</script>
</head>
<body>
<h1>Sentence Reverser!</h1>
<div>Phrase:
<input id="phrase" type="text" size="40" />
</div>
<div>Filter:
<input id="filter" type="text" size="10" />
</div>
<div>
<button id="go">Go!</button>
</div>
<div id="words"></div>
<div id="count"></div>
</body>
</html>
You can add the following
document.getElementById('go').onclick = myfunc
After the element has loaded. In practice this means below the element, or in the head within a window loaded event.
You can use addEventListener() to attach the function on particular event inside the window.onload, something like this.
window.onload = function (){
document.getElementById('go').addEventListener('click', myfunc);
function myfunc(){
//your all code be here
}
}
DEMO
To be as short as possible, you can add this script after the HTML, or in the document load event:
go.onclick = myfunc
But this is far from best practice. A better practice would be to add an onclick attribute to your button:
<button id="go" type="button" onclick="myfunc()"> Go! </button>
Related
JS
var score = 0
var yes = "yes"
var pokemonName = [];
var bg = [];
var index = 0;
document.getElementById('repete').style.visibility = 'hidden';
(function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
})();
function loop() {
var myAnswer = document.getElementById("myAnswer");
var answer = myAnswer.value;
if (answer.toLowerCase().trim() == pokemonName[num].toLowerCase().trim()) {
document.getElementById("text").innerHTML = "Correct, do you want to try again?";
score++
document.getElementById('repete').style.visibility = 'visible';
} else {
document.getElementById("text").innerHTML = "Incorrect, do you want to try again?" + "\n" + " The pokemon was " + pokemonName[num];
document.getElementById('repete').style.visibility = 'visible';
}
}
function loopRepete() {
var repete1 = document.getElementById("repete");
var replay = repete1.value;
if (replay.toLowerCase().trim() == yes.toLowerCase().trim()) {
asyncLoop();
} else {
document.getElementById("text").innerHTML = "Goodbye, your score is " + score;
location.href = 'index.html'
}
}
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pokemon Quiz</title>
</head>
<body>
<lable> Answer </lable>
<input id="myAnswer" type="text">
<button onclick="loop()">click</button>
<p id="text"></p>
<div id="repete">
<lable> Answer </lable>
<input id="loop" type="text">
<button onclick="loopRepete()">click</button>
<p id="loopText"></p>
</div>
<script src="Gen3.js">
</script>
</body>
</html>
When I try take the input from the second second button (div id = repete) and put a toLowerCase() on it it does not work, and we I remove the toLowerCase() it still doesn't work but doesn't show a console error on the page. So I am confused On what I need to try do. I have tried to google it, but I could not find anything that helped.
You have to check if num exists in pokemonName array.
Otherwise, you'll be doing something like this:
[1,2,3][5].toLowerCase() which results in undefined.toLowerCase(), and you can't call .toLowerCase() on undefined as it only exists for String.
If you want asyncLoop to be defined you can't wrap it in a IIFE like that. I suspect you did that so it would run when the page loads, however there's another way to do that and still have the function defined for later use:
// define it like a normal function
function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
}
// and call it right away
asyncLoop();
I have two input fields and a button. When the user clicks the button, I want it to display the text the user wrote in the first input the amount of times the user wrote in the second input.
I understand you have to use a while loop for this. What am I doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
while (inputOne < inputTwo) {
text += inputOne;
inputOne++;
}
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Since inputOne is a text, you cannot increment it (you can't do inputOne++), instead, use another variable, let's call it i, to control the while loop:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
var i=1; // to control the loop
while (i <= inputTwo) { // i goes from 1 to inputTwo
text += inputOne;
i++;
}
document.getElementById("showCode").innerHTML = text;
}
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
This is my solution
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
var count = 0;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
console.log("Text: "+text);
var inputOne = document.getElementById("txtBox").value;
console.log("Input One: "+inputOne);
var inputTwo = document.getElementById("numBox").value;
console.log("Input 2: "+inputTwo);
count=count+1;
console.log("Times: "+count);
document.getElementById("numBox").value = count;
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Instead of the while loop you can use a for loop like this:
for( let i = inputTwo; i>0; i--) {
text += inputOne;
}
I have a span tag and a button tag
<span class="myspan">1</span>
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}
I want to append more span tag with new class from this array with increment value by clicking button.
Like this output:
<span class="myspan1">1</span>
<span class="myspan2">2</span>
<span class="myspan3">3</span>
<span class="myspan4">4</span>
i try `
this JsFiddle
But i can not add class name to new append tag from array.
Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here
value increaseesenter code here this snippet
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
another attempt...anyone can help.. to get desire output
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;
$("#add").click( function() {
(i < elements.length){
$(".new-field").append('<span class="myspan">1</span><script');
var value = parseInt($(".myspan").text(), 10) + 1;
elements[i].className += ' ' + backgrounds[i%len];
i++;
$(".background").text(i);
}
});
*/
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
Try this check the span length via parseInt($(".myspan").length) .And use with Array#forEach for iterate the array instead of increment i.parseInt used convert ths string to number
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var len = backgrounds.length;
$("#add").click( function() {
var len = parseInt($(".myspan").length)
backgrounds.forEach(function(a){
$(".new-field").append('<span class="'+a+'">'+(len++)+'</span>');
})
console.log($(".new-field").html())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
Check the fiddle. Hope this helps!
HTML :
<div id="mainContainer">
<span class="myspan">1</span>
</div>
<button id="add">Add +1</button>
JS :
var arr = ["myspan1", "myspan2", "myspan3", "myspan4"];
$("#add").on("click", function() {
var spans = $("span");
var classList = [];
$.each(spans, function() {
var elemCls = $(this).attr('class').length > 1 ? $(this).attr('class').split(' ') : $(this).attr('class');
if (elemCls) {
$.each(elemCls, function() {
classList.push(this.toString());
});
}
});
$.each(arr, function(i, e) {
if ($.inArray(e, classList) == -1) {
$("#mainContainer").append("<span class='" + e + "'>" + parseInt(spans.length + 1) + "</span>");
return false;
}
});
});
How can I make my event listener work on inserted HTML?
I insert
<li id="test">Titre : test<input type="button" id="del" value="X"><br>Texte : </li>
on my list, but my event listener only works on the button named "work", which is created in the HTML page.
I want to call the function clickHandlerRem by clicking on the new button in the list.
Image:
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="libs/css1.css" rel="stylesheet">
<script src="/script1.js"></script>
</head>
<body>
<form>
Ajouter une note
<input type="text" id="oTitleInput" placeholder="Entrez un titre" />
<input type="button" id="bdel" value="Supprimer"/>
<input type="text" id="oTextInput" placeholder="Entrez une note ici" />
<input type="button" id="binput" value="Ajouter"/>
<div class="divlist">
<ul class="notelist" id="notelist">
</ul>
</div>
</form>
<input type="button" id="del" value="work"/>
</body>
</html>
And my JavaScript code:
function clickHandler(e) {
addnote();
}
function clickHandlerDel(e) {
var oTitle = document.getElementById("oTitleInput").value;
delnote(oTitle);
document.getElementById("oTitleInput").value = '';
document.getElementById("oTextInput").value = '';
}
function clickHandlerRem(e) {
var oTitle = "test";
delnote(oTitle);
}
function addnote() {
var oTitle = document.getElementById("oTitleInput").value;
document.getElementById("oTitleInput").value = '';
var oText = document.getElementById("oTextInput").value;
document.getElementById("oTextInput").value = '';
localStorage.setItem(oTitle, oText);
affnote();
}
function affnote() {
var node = document.getElementById("notelist");
while (node.firstChild) {
node.removeChild(node.firstChild);
}
for (var i = 0, len = localStorage.length; i < len; i++) {
var key = localStorage.key(i);
var value = localStorage[key];
var html = "<li id=\"" + key + "\">Titre : " + key + "\<input type=\"button\" id=\"del\" value=\"X\"\/\><br />Texte : " + value + "</li>";
document.querySelector('#notelist').innerHTML += html;
}
}
function delnote(keyname) {
localStorage.removeItem(keyname);
affnote();
}
function main() {
affnote();
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#binput').addEventListener('click', clickHandler);
document.querySelector('#bdel').addEventListener('click', clickHandlerDel);
document.querySelector('#del').addEventListener('click', clickHandlerRem);
main();
});
Javascript will not reattach event handlers after you create a new DOM element. You will have to add the event handler to your new element manually:
Run
document.querySelector('#del').addEventListener('click', clickHandlerRem);
at the end of affnote().
I need to display a message on mouse click. But I also need another message to be displayed on the next mouse click. The problem is that in my code both messages appear on the first mouse click.
<!DOCTYPE>
<html>
<head>
<script>
function myfunction()
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
if(obj.innerHTML=="message1")
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>
<script>
var flag=0;
function myfunction()
{
if (flag==0)
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
flag=1;}
else
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
obj1.innerHTML = "message2";
}else{
obj.innerHTML = "message1";
}
Your if would always execute because you were trying to check if obj.innerHTML == "message1" immediately after setting it to that.
Do you see that you set the innerhtml of obj to "message1" and then immediately after you check if the innerHTML is "message1" that will always be true.
You need to change the if. So it says:
if(obj.innterHTML=="message1"){
obj.innerHTML="message2";
} else {
obj.innerHTML="message1";
}
Similar to others, but what the heck:
var obj1 = document.getElementById('msg1');
var obj2 = document.getElementById('msg2');
if (obj1.innerHTML == '') {
obj1.innerHTML = 'message1';
} else {
obj2.innerHTML = 'message2';
}
function myfunction() {
var i, ele;
for(i = 1; i <= 2; i++) {
ele = document.getElementById("msg"+i);
if (ele && ele.innerHTML.length == 0) {
ele.innerHTML = 'message' + i;
return;
}
}
}
Just add a click counter to check it was first click or more then first.
<!DOCTYPE>
<html>
<head>
<script>
var $clickCount = 0;
function myfunction() {
$clickCount++;
var obj = document.getElementById("msg1");
obj.innerHTML = "message1";
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
if ($clickCount == 2) {
obj1.innerHTML = "message2";
}
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>