There is something in this javascript or html which is is allowing the checkboxes to be ticked but for not even half a second. (I need the checks to stay there!) I also need the additems function to work
var computer = new Array();
computer[0] = "10001, Nvidia Geforce GTX 690, 1200";
computer[1] = "10002, Raedon HD 7950, 450";
computer[2] = "20001, Ivy Bridge i7 3770, 400";
computer[3] = "20002, Ivy Bridge i7 3770k, 420";
computer[4] = "20003, Sandy Bridge i7 2700k, 340";
computer[5] = "20004, Bulldozer FX-8150, 270";
computer[6] = "30001, Antec eleven-hundred, 120";
computer[7] = "30002, Coolermaster HAF-X, 170";
computer[8] = "30003, Antec three-hundred, 50";
computer[9] = "30004, Corsair 550D, 160";
computer[10] = "40001, INTEL-ASrock fatal1ty Z77 Professional Motherboard, 250";
computer[11] = "40002, INTEL-ASrock Z77 extreme9 Motherboard, 350";
computer[12] = "40003, AMD-ASrock fatal1ty 990FX Professional Motherboard, 240";
computer[13] = "40004, AMD-ASUS Sabertooth 990FX Motherboard, 260";
Check all checkboxes function
function check() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 1;
} else {
inputs[x].checked = true;
}
}
}
Uncheck all checkboxes function
function uncheck() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 0;
} else {
inputs[x].checked = false;
}
}
}
add checked items to cart
function addItems() {
var leftSide = document.getElementById('table_container_left');
var rightSide = document.getElementById('table_container_right');
var inputs = leftSide.getElementByTagName('input');
var totalPrice = 0;
var basketTable = "<h3>My Basket:</h3><table><thead><tr><th>Item</th><th>Quantity</th><th>price</th><th>Sub-total</th></tr></thead><tbody>";
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].checked == true) {
var quantity = ParseFloat(inputs[x+1).value);
var itemName = computer[x/2].split(",")[1];
var itemPrice = parseFloat(computer[x/2].split(",")[2])
var itemTotal = parseFloat(quantity*itemPrice);
totalPrice += itemTotal;
basketTable += "<tr><td>"+itemName+"</td><td>"+quantity+"</td><td>$"+itemPrice+"</td><td>$"+itemTotal+"</td></tr>";
}
}
basketTable +=" <tr><td> colspan='3'><b>Total:</b></td><td><b>$"+totalPrice+"</b></td></tr></tbody><table>";
rightsSide.innerHTML = basketTable;
}
update quantity to 1 when item is checked
function updateQty(id) {
var targetRow = document.getElementById(id);
var qtyBox = targetRow.getElementsByTagName('input')[1];
if (qtyBox.value == 0) {
qtyBox.value = 1;
} else {
qtyBox.value = 0;
}
}
Here's the HTML as requested
<form name="myForm" action="index.html" method="post">
<div id="table_container_left">
<button onclick="check();">Select All</button>
<button onclick="uncheck();">Unselect All</button>
<button onclick="addItems();">Add Items</button>
<table>
<thead>
<th><u>Item Code</u></th>
<th><u>Item</u></th>
<th><u>Qty</u></th>
<th><u>Price</u></th>
</thead>
<tbody>
<script type="text/javascript">
for(x=0; x<=computer.length-1; x++) {
document.write("<tr id='"+x+"'><td><label><input type='checkbox' name='item' value='"+x+"' onclick='updateQty('"+x+"');'/> "+computer[x].split(",")[0]+"</label></td><td>"+computer[x].split (",")[1]+"</td><td> <input name='qty' id='qty' type='textbox' value='0' onchange='qtychange ('"+x+"');'/></td><td>$"+computer[x].split(",")[2]+"</td></tr>");
}
</script>
</tbody>
</table>
</div>
<div id="table_container_right">
<table id="shoppingBasket">
<input name='selectAll' type='button' value='Select All' onclick="itemSelected();"/>
<input name='clearAll' type='button' value='Clear All' onclick=""/>
<input name='removeItem(s)' type='button' value='Remove Item(s)' />
<input name='sortItemCode' type='button' value='Sort by Item Code' disabled='disabled' />
<input name='sortPrice' type='button' value='Sort by Price' disabled='disabled' />
</tbody>
</table>
</div>
</div>
</form>
Your JS syntax is way off, this is what it should look like
function addItems(field) {
for (i = 0; i <= field.length-1; i++)
{
if (field[i].checked == true)
{
if (computer[i]!=null) {
selected[i] = computer[i];
}
}
}
}
Half of your if statements are missing parentheses, that's some basic wrongfulness.
I don't know what and where should any of the variables be, but here is my best shot:
function addItems(field) {
var i;
for (i = 0; i < field.length; i++) {
if (field[i].checked === true) {
if (computer[i] !== null) {
selected[i] = computer[i];
}
}
}
}
You are using i = 0 rather than var i = 0, which will introduce a global variable. This could be a problem if you're writing similar code elsewhere.
Your if-statements are not statements at all. They look like pseudo-code. You're also comparing with = rather than ==, which will cause an assignment rather than a condition, even if you fix up your syntax.
You are not properly indenting your code, which will make you much more prone to introduce new errors.
These are the general issues I notice immediately. Of course, heaps of things could be wrong with this code. fields might not be an array, computer and selected might not match the size of fields, etc.
If you have any specific problem, please describe that, and we may be able to address it.
Related
How do I get the scoring system to work right?
It adds +1 if it's correct, but + an even bigger number if it's wrong...I just want it to add +1 to both.
It should post only +1 for wrong...
HTML
<div>
<h5>What do you say to begin a game in No Game No Life?</h5>
<input class='question1' id='question1'>
</div>
<div>
<h5>What color is Mumen Rider's helmet in One Punch Man?</h5>
<input class='question2' id='question2'>
</div>
<div>
<h5>Are Goku's new Super Saiyan Forms too ridiculous?</h5>
<input class='question3' id='question3' placeholder='Yes or No?'>
</div>
<div>
<h5>What is the Answer to Life's Problems?</h5>
<input class='question4' id='question4' placeholder='Love or Fear?'>
</div>
<div>
<h5>In Season 2 of SAO, is the main character a girl, boy, or both?</h5>
<input class='question5' id='question5'>
</div>
<div>
<h5>Who is the best character in One Piece?</h5>
<input class='question6' id='question6'>
</h5>
</div>
<div>
<h5>Finish this quote from Gurren Lagann, "TO THE ( )!!!!!"</h5>
<input class='question7' id='question7'>
</div>
<button id='button' type='button' onclick='answer()'>Do you even anime?</button>
</form>
<span class='correct'>
<label for='score'>CORRECT</label>
<input type='text' id='score'>
</span>
<span class='wrong'>
<label for='wrong'>WRONG</label>
<input type='text' id='wrong'>
</span>
JavaScript:
var quizArray = [
{ answer: 'ashente' },
{ answer: 'green' },
{ answer: 'yes' },
{ answer: 'love' },
{ answer: 'both' },
{ answer: 'chopper' },
{ answer: 'heavens' }
]
function answer() {
var correct = 0;
var wrong = 0;
for (i = 0; i < quizArray.length; i++) {
var question1 = document.getElementById('question1').value;
if (question1 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question2 = document.getElementById('question2').value;
for (i = 0; i < quizArray.length; i++) {
if (question2 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question3 = document.getElementById('question3').value;
for (i = 0; i < quizArray.length; i++) {
if (question3 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question4 = document.getElementById('question4').value;
for (i = 0; i < quizArray.length; i++) {
if (question4 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question5 = document.getElementById('question5').value;
for (i = 0; i < quizArray.length; i++) {
if (question5 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question6 = document.getElementById('question6').value;
for (i = 0; i < quizArray.length; i++) {
if (question6 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
var question7 = document.getElementById('question7').value;
for (i = 0; i < quizArray.length; i++) {
if (question7 == quizArray[i].answer) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
}
Here it is. You have several problems. Check teh code and feel free to ask anything:
var quizArray = [{
answer: 'ashente'
}, {
answer: 'green'
}, {
answer: 'yes'
}, {
answer: 'love'
}, {
answer: 'both'
}, {
answer: 'chopper'
}, {
answer: 'heavens'
}]
function answer() {
var correct = 0;
var wrong = 0;
var questions = document.querySelectorAll(".question");
for (i = 0; i < quizArray.length; i++) {
if (questions[i].value.toLowerCase() == quizArray[i].answer.toLowerCase()) {
correct += 1;
document.getElementById('score').value = correct
} else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
}
}
(function(){
document.getElementById("button").addEventListener("click", answer);
})();
<div>
<h5>What do you say to begin a game in No Game No Life?</h5>
<input class='question' id='question1'>
</div>
<div>
<h5>What color is Mumen Rider's helmet in One Punch Man?</h5>
<input class='question' id='question2'>
</div>
<div>
<h5>Are Goku's new Super Saiyan Forms too ridiculous?</h5>
<input class='question' id='question3' placeholder='Yes or No?'>
</div>
<div>
<h5>What is the Answer to Life's Problems?</h5>
<input class='question' id='question4' placeholder='Love or Fear?'>
</div>
<div>
<h5>In Season 2 of SAO, is the main character a girl, boy, or both?</h5>
<input class='question' id='question5'>
</div>
<div>
<h5>Who is the best character in One Piece?</h5>
<input class='question' id='question6'>
</div>
<div>
<h5>Finish this quote from Gurren Lagann, "TO THE ( )!!!!!"</h5>
<input class='question' id='question7'>
</div>
<input id='button' type='submit' value="Do you even anime?">
<span class='correct'><label for='score'>CORRECT</label><input type='text' id='score'></span>
<span class='wrong'><label for='wrong'>WRONG</label><input type='text' id='wrong'></span>
I will calrify some points anyway. As you could see, the main difference is the size of the js. You had teh same piece of code for each question, when you are in a situation like this, you should use a function or a loop. This is part of the DRY concept. So taking all the questions in an array and iterate over them is easier than create a piece of code for each one.
I added the function toLowerCase because is annoying failing answers only if you missed that detail. Using this function is not necessary, it's up to you.
In the HTML part I must remark that if you have a button that sends a form you should create an input which type is submit. HTML button is not properly for submitting a form. It can do the job, but it is not the correct way.
You use inputs to show the score, but, instead it will be better to use plain text. Again, it's not bad but it's handier.
The issue is related to how the incrementing is implemented in the for-loops. Let's take the first loop as an example:
You are trying to assess whether or not question 1 has been answered correctly by comparing the users answer with every possible answer in the quizArray element. With 7 questions we should have 7 iterations of the loop. In each iteration, you check if the answer for question 1 is correct and increment the correct variable accordingly. Otherwise you increment the wrong variable. So for 7 iterations of the for-loop you are incrementing the wrong variable at least 6 times.
Instead of trying to increment the correct and wrong variables in each iteration, you can use a flag to determine if the question was answered correctly, and then increment the variables after the loop. For example:
var correct = 0;
var wrong = 0;
var question1 = document.getElementById('question1').value;
var answerCorrect = false;
for (i = 0; i < quizArray.length; i++) {
if (question1 == quizArray[i].answer) {
answerCorrect = true;
}
}
if (answerCorrect){
correct += 1;
document.getElementById('score').value = correct
}
else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
answerCorrect = false;
var question2 = document.getElementById('question2').value;
for (i = 0; i < quizArray.length; i++) {
if (question2 == quizArray[i].answer) {
answerCorrect = true;
}
}
if (answerCorrect){
correct += 1;
document.getElementById('score').value = correct
}
else {
wrong += 1;
document.getElementById('wrong').value = wrong
}
I have a little product search code that I've been working on for a while. It works great, although a bit backwards.
The more keywords I type in, ideally, the less products will show up (because it narrows down the results). But as is stands, the more keywords I type in my search system, the MORE products are displayed, because it looks for any product with any of the keywords.
I want to change the script so that it only shows results if they include ALL the searched for keywords, not ANY of them...
Sorry for the long-winded explanation.
Here's the meat and potatoes (jsfiddle):
http://jsfiddle.net/yk0Lhneg/
HTML:
<input type="text" id="edit_search" onkeyup="find_my_div();">
<input type="button" onClick="find_my_div();" value="Find">
<div id="product_0" class="name" style="display:none">Mac
<br/>Apple
<br/>
<br/>
</div>
<div id="product_1" class="name" style="display:none">PC
<br/>Windows
<br/>
<br/>
</div>
<div id="product_2" class="name" style="display:none">Hybrid
<br/>Mac PC Apple Windows
<br/>
<br/>
</div>
JAVASCRIPT:
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
for (i = 0; i < 999; i++) {
var o = gid("product_" + i);
if (o) {
o.style.display = "none";
}
}
}
function find_my_div() {
close_all();
var o_edit = gid("edit_search");
var str_needle = edit_search.value;
str_needle = str_needle.toUpperCase();
var searchStrings = str_needle.split(/\W/);
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toUpperCase();
if (currentSearch !== "") {
nameDivs = document.getElementsByClassName("name");
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
nameDivs[j].style.display = "block";
}
}
}
}
}
So, when you search "mac pc" the only result that should be displayed is the hybrid, because it has both of those keywords. Not all 3 products.
Thank you in advance!
I changed a little bit your code to adjust it better to my solution. I hope you don't mind. You loop first over the terms, and then through the list of products, I do it the other way around.
How this solution works:
Traverse the list of products, for each product:
Create a counter and set it to 0.
Traverse the list of search terms, for each.
If the word is found in the product's name, add 1 to the counter.
If the counter has the same value as the list length, display the product (matched all words)
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
for (i = 0; i < 999; i++) {
var o = gid("product_" + i);
if (o) {
o.style.display = "none";
}
}
}
function find_my_div() {
close_all();
var o_edit = gid("edit_search");
var str_needle = edit_search.value;
str_needle = str_needle.toUpperCase();
var searchStrings = str_needle.split(/\W/);
// I moved this loop outside
var nameDivs = document.getElementsByClassName("name");
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
// set a counter to zero
var num = 0;
// I moved this loop inside
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toUpperCase();
// only run the search if the text input is not empty (to avoid a blank)
if (str_needle !== "") {
// if the term is found, add 1 to the counter
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
num++;
}
// display only if all the terms where found
if (num == searchStrings.length) {
nameDivs[j].style.display = "block";
}
}
}
}
}
<input type="text" id="edit_search" onkeyup="find_my_div();">
<input type="button" onClick="find_my_div();" value="Find">
<div id="product_0" class="name" style="display:none">Mac
<br/>Apple
<br/>
<br/>
</div>
<div id="product_1" class="name" style="display:none">PC
<br/>Windows
<br/>
<br/>
</div>
<div id="product_2" class="name" style="display:none">Hybrid
<br/>Mac PC Apple Windows
<br/>
<br/>
</div>
You can also see it on this version of your JSFiddle: http://jsfiddle.net/yk0Lhneg/1/
Here is the link to the jsbin.
I was almost finished with my project (I thought I was) and then I tested it out. It is supposed to add buttons with the chosen title of the task and the number of points it awards. Every time the button is clicked the points would be added on to the "Points" section and every 500 points my "Level" would increase.
Upon finishing it, it worked. Then I went to clear the localStorage since that's what I used to save the information, but I wanted to start over. When I did that, the 'Points' section, or 'results' value, keeps returning as "NaN". The code is exactly the same as it was when it worked. Can someone please tell me how to fix this problem, thank you in advance.
Here is the code. (Used bootstrap for CSS)
HTML
<center>
<br>
<h2> Add task </h2>
<div class='well' style='width:500px' id="addc">
<div id="addc">
<input class='form-control' style='width:450px' id="btnName" type="text" placeholder="New Task" /><br>
<input class='form-control' style='width:450px' id="btnPoints" type="text" placeholder="Points" /><br>
<button id="addBtn">Add</button>
</div> </div>
<div class='well' style='width:230px' id="container">
</div>
<hr style="width:400px;">
<h3>Points </h3>
<div id="result">0</div>
</div>
<hr style="width:400px;">
<div style="width:400px;">
<h3>Level
<p id='lvl'>0</p>
</div>
<hr style="width:400px;">
</center>
JavaScript
var res = document.getElementById('result');
res.innerText = localStorage.getItem('myResult');
var level = document.getElementById('lvl');
level.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for(var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if(!btnName)
btnName = "Button ?";
if(!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-danger';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
var result = document.getElementById('result');
result.innerText = parseInt(result.innerText) + parseInt(pts);
var lvl = 0;
var a = 100;
while (result.innerText > 5*a) {
lvl+=1;
a+=100;
}
document.getElementById('lvl').innerText = lvl;
var res = document.getElementById('result');
localStorage.setItem("myResult", res.innerText);
var level = document.getElementById('lvl');
localStorage.setItem("myLevel", level.textContent);
}
You were parsing result.innerText as a number, but its value, initially, was actually either NaN or nothing, both which end up being NaN. One fix is to just check if it parsed to a number, and if it didn't, fall back to 0.
I just basically changed that and removed some getElementByIds that, in my opinion, were redundant, check the addToResult function:
http://jsfiddle.net/owc26a0p/1/
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fallback to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
while (result > 5 * a) {
lvl += 1;
a += 100;
}
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
I ended up using jsFiddle since I couldn't always get jsBin to save my changes. Good luck.
please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.
I've looked through many posts to no avail. I have the following in a simple form where one of the products changes based on the number of checkboxes checked. It works in every browser except IE. What am I doing wrong?
<body>
<script type="text/javascript">
function check(){
"use strict";
var count = 0, x=0, checkboxes=document.signup.getElementsByClassName("styled");
for(;x<checkboxes.length; x++){
if(checkboxes[x].checked){
count++;
}
}
if(count<3) {
document.getElementById("variable").value = "1";
}
else if (count == 3){
document.getElementById("variable").value = "74";
}
else if (count == 4){
document.getElementById("variable").value = "75";
}
else if (count == 5){
document.getElementById("variable").value = "76";
}
}
</script>
<form name="signup" id="signup" method="post" action="/subscribers/signup.php">
<input type="checkbox" id="variable" name="product_id[]" value="" class="styled"></input>product 1 - variable</div>
<input type="checkbox" id="same" name="product_id[]" value="3" class="styled"></input>product 2
<input type="checkbox" id="same2" name="product_id[]" value="2" class="styled"></input>product 3
<input type="checkbox" id="same3" name="product_id[]" value="4" class="styled"></input><div class="check-title">product 4
<input type="checkbox" id="same4" name="product_id[]" value="44" class="styled"></input><div class="check-title">product 5
Continue</td></tr>
</form>
</body>
All versions of IE prior to IE9 do not support getElementsByClassName(). You will need to use some sort of substitute.
Instead of this piece of your code:
checkboxes = document.signup.getElementsByClassName("styled");
I would suggest using this:
checkboxes = document.getElementById("signup").getElementsByTagName("input")
getElementsByTagName() is widely support in all versions of IE. This will obviously get all input tags, but only the checkboxes will have checked set so you should be OK.
If you need to filter by class, then you could do the whole thing this way:
function check() {
"use strict";
// initialize checkbox count to 0
var count = 0, item;
// get all input tags in the form
var inputs = document.getElementById("signup").getElementsByTagName("input");
// loop through all input tags in the form
for (var i = 0; i < inputs.length; i++) {
// get this one into the local variable item
item = inputs[i];
// if this input tag has the right classname and is checked, increment the count
if ((item.className.indexOf("styled") != -1) && item.checked) {
count++;
}
}
// get object for result
var obj = document.getElementById("variable");
// check count and set result based on the count
if(count < 3) {
obj.value = "1";
} else if (count == 3) {
obj.value = "74";
} else if (count == 4) {
obj.value = "75";
} else if (count == 5) {
obj.value = "76";
}
}
IE doesnt have method getElementsByClassName... you can try to define it:
if(document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) {
retnode.push(elem[i]);
}
}
return retnode;
}
};