I'm a fresher in JS, so I have the following task: Some text is given on a page and when a user wants to find a set of characters or string by adding this string in a window and then clicking "search", this string should be marked as bold in our text each time it is met.
Looking through my code I'm almost sure that the function is working, but after the function has finished, the bold strings just blink for a moment and the text returns to its initial status.
Please help me to find out my mistake.
Here's the code.
function look(a) {
var str = document.getElementById("original").innerHTML;
var len = a.text.value.length;
var begin = str.indexOf(a.text.value);
var final = str;
if (begin == -1) {
alert("No matches");
return false;
}
if (begin > -1) {
var count = 0;
final = str.substring(count, begin) + "<b>" + a.text.value + "</b>" + str.substring(begin + len + 1, str.length);
while (begin != -1) {
begin = str.indexOf(a.text.value, begin + len);
if (begin == -1) break;
final = final.substring(count, begin) + "<b>" + a.text.value + "</b>" + str.substring(begin + len + 1, str.length);
}
document.getElementById("original").innerHTML = final;
return true;
}
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<span id="original" type="text">Some given text</span>
<br/>
<form name="search" onsubmit="return look(this)">
<p>Enter text to search<input type="text" name="text"></p>
<p><input type="submit" value="search"></p>
</form>
</body>
Returning true on successfully finding the text span makes the form to be submitted. You need to return false to make the form invalidate the submission. This is the updated code, I have changed the return statement out of the if-else block and returned false either way. Another way is to make submit button as input[type='button'] and register an onclick event listener to it.
function look(a)
{
var str=document.getElementById("original").innerHTML;
var len=a.text.value.length;
var begin=str.indexOf(a.text.value);
var final=str;
if (begin==-1){
alert("No matches");
}
if (begin>-1){
var count=0;
final=str.substring(count,begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
while(begin!=-1){
begin=str.indexOf(a.text.value,begin+len);
if(begin==-1) break;
final=final.substring(count, begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
}
document.getElementById("original").innerHTML=final;
}
return false;
}
The page is refreshing! By default, forms refresh the page. You can use the return value of the on submit function to stop this default behavior: just return false.
function look(a)
{
var str=document.getElementById("original").innerHTML;
var len=a.text.value.length;
var begin=str.indexOf(a.text.value);
var final=str;
if (begin==-1){
alert("No matches");
return false;
}
if (begin>-1){
var count=0;
final=str.substring(count,begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
while(begin!=-1){
begin=str.indexOf(a.text.value,begin+len);
if(begin==-1) break;
final=final.substring(count, begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
}
document.getElementById("original").innerHTML=final;
return false;
}
}
<body>
<span id="original" type="text">
Some given text
</span>
<br/>
<form name="search" onsubmit="look(this); return false;">
<p>
Enter text to search<input type="text" name="text">
</p>
<p>
<input type="submit" value="search">
</p>
</form>
</body>
</html>
I have looked through a lot of the already asked questions and cannot find it. I need the previous appended message to be deleted once you hit the submit button again. So this will let you choose your character that you type into the input field and then it will append a message bellow telling you that you choose x character. After that you can resubmit another character which I want, but I do not want the previous append to be there.
I tried to do a search function in javascript and if it was not equal to -1 then delete the first p in the div, but that did not work=/
Thanks for your help in advance.
html:
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
<link rel='stylesheet' type='text/css' href='styles/main.css'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type='text/javascript' src='jquery/script.js'></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) : <br><br><input id='text' type="text" name="mess" value="">
<button id='button1' type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br>
<div id="box_holder"></div>
<br><br>
<button id='button2' type='button' name='button2' onclick="redirect()">Start Your Adventure</button>
</body>
</html>
JS:
$(document).ready(function() {
$('#button1').click(function(){
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
chooseChar = function () {
var text = document.getElementById('text').value;
var text = text.toLowerCase();
if(text == 'human') {
$(document).ready(function() {
$('#button1').click(function(){
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function(){
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text+".html";
window.location.href = url;
}
So your variable send gets sent and then it clears out the input field with either of those functions
$(document).ready(function() {
$('#button1').click(function(){
$('#box_holder').children('p').remove(); <===========
or Either of these should work
$('#box_holder').empty(); <===========================
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
Instead of using append, try using html as follows
$('#box_holder').html('<p>'+ 'You have chosen your character to be: '+send+'</p>');
Here is a Plunkr to explain it a little better
$(document).ready(function() {
$('#button1').click(function() {
var send = $("input[name=mess]").val();
$('#box_holder').html('<p>' + 'You have chosen your character to be: ' + send + '</p>');
});
$('input').css("color", "blue");
});
chooseChar = function() {
var text = document.getElementById('text').value;
text = text.toLowerCase();
if (text == 'human') {
$(document).ready(function() {
$('#button1').click(function() {
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function() {
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text + ".html";
window.location.href = url;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) :
<br />
<br />
<input id="text" type="text" name="mess" value="" />
<button id="button1" type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br />
<div id="box_holder"></div>
<br />
<br />
<button id="button2" type="button" name="button2" onclick="redirect()">Start Your Adventure</button>
</body>
</html>
You have to remember, the append() function appends the content on the selected component. The html() function replaces all content inside of it.
Hope it helps
I want to know how to detect if a textbox does not contain certain words. For example if the textbox did not contain 'who', 'what', 'why', 'when' or 'where' some sort of function would run.
JavaScript:
function command() {
var srchVar = document.getElementById("srch");
var srch = srchVar.value;
var t = srch;
if (srch == '') {
alert('Please do not leave the field empty!');
}
else if (srch.indexOf('time') != -1) {
alert('The current time according to your computer is' + ShowTime(new Date()));
}
else if (srch.indexOf('old are you') != -1) {
alert("I am as old as you want me to be.");
}
else {
if (confirm('I am sorry but I do not understand that command. Would you like to search Google for that command?') == true) {
window.open('https://google.co.uk/#q=' + srch, '_blank');
}
else { /* Nothing */ }
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="script.js" type="text/javascript"></script>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div class="ui-widget">
<input class="search-field" id="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false">
</div>
</body>
</html>
You will want to call that function when you press a button.
Try something in your HTML like:
<input class="info" onclick="contains();" type="button">
And in your JS
function contains() {
var srchVar = document.getElementById("srch");
var srch = srchVar.value;
if (
(srch.indexOf('who')==-1) &&
(srch.indexOf('what')==-1) &&
(srch.indexOf('why')==-1) &&
(srch.indexOf('when')==-1) &&
(srch.indexOf('where')==-1)
) {
alert("That is not a question");
}
}
You will want to merge this with your command() function in the future.
Also, what does info(); do ?
I have the following setup - http://codepen.io/anon/pen/WvjmLv?editors=100 and am trying to output text depending on which button is clicked
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="right-answer" type="button">6</button>
<button class="wrong-answer" type="button">10</button>
<script>
var text;
var wrongAnswer = document.getElementsByClassName("wrongAnswer").addEventListener("click");
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click");
if (wrongAnswer) {
text = "Incorrect!";
text = "Wrong!";
text = "Try Again!";
}
if (rightAnswer) {
text = "Correct!";
}
document.getElementById("answer").innerHTML = text;
</script>
</div>
<div>
<p id="answer"></p>
</div>
If the user selects the wrong answer, it should either read Wrong!, Incorrect! or Try Again! (without repeating the same text output if their next guess is also wrong)
If they get the answer right, it should just simply read Correct!
As I'm fairly new to JavaScript, I feel as though I'm a little bit off with my solution and was wanting to know how can I make this function work?
Thanks.
Easiest and fastest way to get the result you want is by adding onclick-eventhandlers to your buttons.
<button onclick="somefunction()"></button>
After that you can easily handle what should happen after that click.
In your case I would check what's in the class attribute of the button you clicked.
By doing this you can print the results to your #answer-container.
With a simple array and a global variable of which index is next you can output different "false"-messages.
var _i = 0;
var _wrongs = ['Incorrect!', 'Wrong!', 'Try Again!'];
function showResult(b) {
var res = document.getElementById('answer');
if (b.classList.contains('right-answer')) {
res.innerHTML = 'Correct'
} else {
res.innerHTML = _wrongs[_i];
_i = _i > 1 ? 0 : _i + 1;
}
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" onclick="showResult(this)">2</button>
<button class="wrongAnswer" onclick="showResult(this)">5</button>
<button class="right-answer" onclick="showResult(this)">6</button>
<button class="wrong-answer" onclick="showResult(this)">10</button>
</div>
<div>
<p id="answer"></p>
</div>
Demo on Codepen
Well, there are a couple things that you need to do:
You do not have a separate click handler function defined.
You need to properly add the event function to the addEventListener call.
You cannot attach an event to multiple elements at once. You need to loop over them.
Why do you have two different classes? i.e. 'wrongAnswer' and 'wrong-answer'? Please make sure that you stick with one convention.
I added an onReady() to wait for the DOM to load before accessing and adding listeners to the elements.
Addition Information
Below, I have wrapped the document.getElementsByClassName(className) call with [].slice.call(scope, [begin[, end]]) because the result of getElementsByClassName is a NodeList. You cannot treat a list like an array in JavaScript. Since I used Array.prototype.forEach to loop over the elements, they needed to transformed into an array. This is simply syntactic sugar in order to make the code look more aesthetically pleasing and readable.
This could have easily been accomplished with a for-loop:
var nodes = document.getElementsByClassName("rightAnswer");
for (var i = 0; i < nodes.length; i++) {
var el = nodes[i];
el.addEventListener('click', clickHandler);
}
Code
var wrongTextArr = ['Try Again!', 'Wrong!', 'Incorrect!'];
var guesses = 0;
onReady(function() {
// Set the number of guesses equal to the number of questions - 1.
guesses = document.querySelectorAll('.question button').length - 1;
[].slice.call(document.getElementsByClassName('wrongAnswer')).forEach(function(el) {
el.addEventListener('click', clickHandler);
});
[].slice.call(document.getElementsByClassName('rightAnswer')).forEach(function(el) {
el.addEventListener('click', clickHandler);
});
});
function clickHandler(e) {
var text = '';
var target = e.target;
var targetClass = target.className;
if (guesses < 1) {
text = 'You have reached the max number of attempts!';
} else if (targetClass === 'wrongAnswer') {
text = wrongTextArr[--guesses]; // Decrement guesses.
} else if (targetClass === 'rightAnswer') {
text = 'Correct!';
} else {
text = 'Unexpected Error!';
}
document.getElementById('answer').innerHTML = text;
}
function onReady(callback) {
var intervalID = window.setInterval(function() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, 1000);
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
In the code above, I tried not to stray too far away from your original code, I just simply pointed out things that made your code not work and fix them with the minimalist amount of effort. Here is my solution that I would go with.
var wrongTextArr = ['Try Again!', 'Wrong!', 'Incorrect!'];
var guesses = 0;
onReady(function() {
// Set the number of guesses equal to the number of questions - 1.
guesses = document.querySelectorAll('.question button').length - 1;
addEventListeners('button[class$="Answer"]', 'click', function(e) {
document.getElementById('answer').innerHTML = getText(e.target.className.split());
});
});
function getText(classList) {
if (guesses < 1) {
return 'You have reached the max number of attempts!';
} else if (classList.indexOf('wrongAnswer') > -1) {
return wrongTextArr[--guesses]; // Decrement guesses.
} else if (classList.indexOf('rightAnswer') > -1) {
return 'Correct!';
} else {
return 'Unexpected Error!';
}
}
// Generic functions.
function addEventListeners(selector, event, listenerFn) {
[].slice.call(document.querySelectorAll(selector)).forEach(function(el) {
el.addEventListener(event, listenerFn);
});
}
function onReady(callback) {
var intervalID = window.setInterval(function() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, 1000);
}
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
Lots of good answers.. Here is another approach,
HTML:
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">2</button>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">5</button>
<button class="rightAnswer" type="button" onclick="checkAnswer(this)">6</button>
<button class="wrongAnswer" type="button" onclick="checkAnswer(this)">10</button>
</div>
<div>
<p id="answer"></p>
</div>
JS:
<script>
var count = 0;
var wrongtext = ["Incorrect!", "Wrong!", "Try Again!"];
function checkAnswer(el) {
if (el.classList.contains('wrongAnswer')) {
count++;
if(count === 3)
count = 0;
alert(wrongtext[count])
}
if (el.classList.contains('rightAnswer')) {
alert('correct');
}
}
</script>
Demo:
https://jsfiddle.net/cubq361t/22/
I am not totally sure how to make it so it will say different things like "wrong" and "incorrect" but I hope this will point you in the right direction:
<!DOCTYPE html>
<html lang="en">
<body>
<div class="section">
<p>How many sides does a hexagon have?</p>
<input type="button" onClick="wrongAnswer()" value="2">
<input type="button" onClick="wrongAnswer()" value="5">
<input type="button" onClick="rightAnswer()" value="6">
<input type="button" onClick="wrongAnswer()" value="10">
<p id="text"></p>
</div>
<script>
function wrongAnswer() {
document.getElementById('text').innerHTML = "Wrong";
}
function rightAnswer() {
document.getElementById('text').innerHTML = "Correct!";
}
</script>
</body>
</html>
Here is an updated version of your code. The main issue you had was mixing up your variable and function names.
Here is a
Fiddle
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="wrongAnswer" type="button">10</button>
</div>
<div>
<p id="answer"></p>
</div>
<script>
var text;
var wrongAnswers = document.getElementsByClassName("wrongAnswer");
var rightAnswers = document.getElementsByClassName("rightAnswer");
for (var i = 0; i < wrongAnswers.length; i++) {
// alert( wrongAnswers[i]);
wrongAnswers[i].addEventListener('click', printWrongAnswer);
}
for (var i = 0; i < rightAnswers.length; i++) {
rightAnswers[i].addEventListener('click', printRightAnswer);
}
function printRightAnswer() {
text = "Correct!";
printAnswer();
};
function printWrongAnswer() {
text = "Incorrect!";
text += "Wrong!";
text += "Try Again!";
printAnswer();
}
function printAnswer() {
document.getElementById("answer").innerHTML = text;
}
</script>
In addition to the answers of Mr. Polywhirl and Bellash:
If you are new to JavaScript you should try to understand how the EventBindings are working. Every binding in JavaScript is an event, so if you click somewhere the Browser will check if he will find a binding which is listening to the event "click". So its irrelevant when you bind the event but it has to be before the click. However you have to tell JavaScript which function he has to call if someone clicks your button! Thats because events are kinda "floating" in you browser scope, they are present but know one knows when they are actually be triggered but if they are getting triggered the script have to know what gets triggered or in other words: which functionality should be triggered now?
Your lines
var wrongAnswer = document.getElementsByClassName("wrongAnswer").addEventListener("click");
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click");
are wrong because you never told the event "click" what functionality should be executed if the button is clicked.
The call or one type of a correct call would be:
var someFunction = function() { // DO YOUR AWESOME WORK PLS! }
var rightAnswer = document.getElementsByClassName("rightAnswer").addEventListener("click", someFunction);
and in addition to that:
I don't know how experienced you are in programming but this lines
text = "Incorrect!";
text = "Wrong!";
text = "Try Again!";
will override each other, because you are using the same variable in all 3 rows ;)
Mr. Polywhirl and Bellash posted you some good example to begin with. Try them out and try to understand them!
Hope this makes it a bit clearer!
cheers,
Sebastian
Here's a rewrite of your code, providing comments as a sort of tutorial:
Update: added random response generation.
HTML:
<div class="question">
<p>How many sides does a hexagon have?</p>
<!--
Use a common class ('answer-button' used here) for all buttons
so that clicks can be easily handled with a single listener.
Since you know any answers that aren't right are wrong, you can
simply add a 'right-answer' class for that one and leave the
others as is.
-->
<button class="answer-button" type="button">2</button>
<button class="answer-button" type="button">5</button>
<button class="answer-button right-answer" type="button">6</button>
<button class="answer-button" type="button">10</button>
</div>
<div>
<!--
Using an id is often unnecessary, so I'd switch this to a class.
Since the above buttons represent answers, using an "answer" class
on this paragraph can bring confusion, so I'd recommend using something
more accurate, such as "response".
-->
<p class="response"></p>
</div>
<!--
Generally you'll want your js in a separate file. If you include the script, whether
inline or separate, at the bottom of the body element, as you did initially, it will
automatically execute after the dom has initialized, which is good.
-->
JavaScript:
// Wrap in an immediately invoking function expression
// to keep your variables off the global scope.
(function() {
// Capture all of your response phrases in an object.
var responses = {
correct: [
"Correct!"
],
incorrect: [
"Wrong!",
"Try Again!",
"Incorrect!"
]
};
// Get the element that will display your answer.
// getElementsByClassName returns an array, so get the
// first element in the array.
var response = document.getElementsByClassName('response')[0];
// Get all of the answer buttons.
var answerButtons = document.getElementsByClassName('answer-button');
// Set a listener on each answerButton element.
for (var i = 0; i < answerButtons.length; i++) {
// Add the event listener to the element. When the event occurs,
// the checkAnswer function will run, and will be passed an event object.
answerButtons[i].addEventListener('click', checkAnswer);
}
// event is an object that is automatically passed in
// when the listener calls this function, and event.target
// is the element where the event occurred.
function checkAnswer(event) {
// initialize a variable for the message
var message;
// get the element where the event occurred
var element = event.target;
// get all classes from target element
var classes = event.target.className;
// classes will be in a space-separated string, so
// we convert that to an array
classes = classes.split(' ');
// check if a specific class is in the array
if (classes.indexOf('right-answer') >= 0) {
// if the 'right-answer' class is there, they
// clicked the right answer.
message = getRandomArrayElement(responses.correct);
} else {
// otherwise, they clicked the wrong answer
message = getRandomArrayElement(responses.incorrect);
}
// set the target element's content to the message
response.textContent = message;
}
function getRandomArrayElement(array) {
// This function picks a random element from an array and
// returns it.
// You're going to want to pick one of these array items by their
// index, so we'll set up variables to capture the lowest and
// highest possible numbers that can be used.
var min = 0;
var max = array.length - 1;
// Javascript provides random numbers using the Math.random function,
// wich gives a random float between 0 and 1. The expression below
// uses that to generate a random number within a given range - in this
// case, between min and max.
var index = Math.floor(Math.random() * (max - min + 1)) + min;
return array[index];
}
})();
I have edited your code to help you understand how you could deal with .getElementsByClassName
<div class="question">
<p>How many sides does a hexagon have?</p>
<button class="wrongAnswer" type="button">2</button>
<button class="wrongAnswer" type="button">5</button>
<button class="rightAnswer" type="button">6</button>
<button class="rightAnswer" type="button">10</button>
</div>
<div>
<p id="answer">ok</p>
</div>
<script>
var text="...",
wrongs=document.getElementsByClassName("wrongAnswer"),
rights=document.getElementsByClassName("rightAnswer"),
wrongTexts=["Incorrect","Try Again","Wrong!"],
i=0;
for(var i=0; i< wrongs.length; i++){
wrongs[i].addEventListener("click",function(e){
text = "Incorrect!";
DisplayText();
});
}
for(var i=0; i< rights.length; i++){
rights[i].addEventListener("click",function(e){
text = "Correct!";
DisplayText();
});
}
function DisplayText(){
i=i%wrongTexts.length;
text=text=="Correct"?text:wrongTexts[i++];
document.getElementById("answer").innerHTML = text;
}
</script>
Make a function first and the assign it to the buttons like
<button onclick="myFunction()">Click me</button>
<p class="demo"></p>
Then in the JS
function myFunction() {
document.getElementByClassName("demo").innerHTML = "Hello World";
}
in your pen make a function add all the logic in it and call it on button click
I am trying to remove the style or the background of a textbox to reveal the content after 10 clicks. How can I do that on Javascript?
here is my html:
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000">
and here is my JS:
function check() {
var tries++;
if (tries == 10){
document.getElementById('firstN').disabled= true;
}
}
The problem is that tries is a local variable (local to the check function). Every time check is called, a new variable named tries is created and initialized to 0.
Try this instead:
var tries = 0;
function check() {
tries++;
if (tries == 10) {
document.getElementById('firstN').style.background = '#ffffff';
}
}
(I'm assuming that you already have some code to call check when the element is clicked. If not, you need to add a click handler to your element.)
You are instantiating a var "tries" everytime you go into this function. Move the variable up a level to where it will increment:
var btn = document.getElementById("btnclick");
btn.onclick = check;
var tries = 0;
function check() {
tries++;
if (tries == 10){
var ele = document.getElementById("firstN");
ele.value= "DISABLED";
ele.disabled = true;
}
}
EDIT:
Working JSFiddle
store it in a cookie:
<script type="text/javascript">var clicks = 0;</script>
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" value="Click" onclick="clicks++">
onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
Here you go. Remove the alert lines when you see that it works.
<html>
<head>
<title>Test</title>
<script>
function check(){
var getClicks = parseInt(document.getElementById('firstN').getAttribute('clicks')); //Get Old value
document.getElementById('firstN').setAttribute("clicks", 1 + getClicks); //Add 1
if (getClicks === 10){ //Check
alert('Locked');
document.getElementById('firstN').disabled= true;
} else {
alert(getClicks); //Remove else statement when you see it works.
}
}
</script>
</head>
<body>
<form action="#">
Input Box: <input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" onclick="check();" clicks="0">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>