Html field incrementer breaks if field is edited by user - javascript

Below I have code that is problematic to me. The purpose of it is to increment "input class=qty". This works great unless the user puts in their own number then decides they want to return to using the incremental buttons. My impression is that I can no longer reference the value once the field is edited, but I'm unsure as to what the cause is or a proper solution. Help would be appreciated.
<html>
<head>
<script>
function qtyPlus(fieldId){
var curVal = parseInt(document.getElementById(fieldId).value);
if(isNaN(curVal)) {
document.getElementById(fieldId).setAttribute('value', 0);
}
else {
document.getElementById(fieldId).setAttribute('value', curVal+1);
}
}
function qtyMinus(fieldId) {
var curVal = parseInt(document.getElementById(fieldId).value);
if(isNaN(curVal)) {
document.getElementById(fieldId).setAttribute('value', 0);
}
else {
if(curVal != 0) {
document.getElementById(fieldId).setAttribute('value', curVal-1);
}
}
}
</script>
</head>
<body>
<input type='button' value='-' onclick='qtyMinus("numOfAttendees")' class='qtyminus' >
<input type='text' value='0' class='qty' id='numOfAttendees' >
<input type='button' value='+' onclick='qtyPlus("numOfAttendees")' class='qtyplus' >
</body>
</html>

Change your js for:
function qtyPlus(fieldId){
var curVal = parseInt(document.getElementById(fieldId).value);
if(isNaN(curVal)) {
document.getElementById(fieldId).value = 0;
}
else {
document.getElementById(fieldId).value = curVal+1;
}
}
function qtyMinus(fieldId) {
var curVal = parseInt(document.getElementById(fieldId).value);
if(isNaN(curVal)) {
document.getElementById(fieldId).value = 0;
}
else {
if(curVal != 0) {
document.getElementById(fieldId).value = curVal-1;
}
}
}
Test: http://jsfiddle.net/7dhjT/

Related

How to show and hide field immediately base on the text length? - JQuery

I have two input text like this:
input1
<input type='text' id='input1' name='input1'>
<br>
input2
<input type='text' id='input2' name='input2'>
<br>
Now I want to hide and show input2 base on the event in input1 if there is no text in input1 then input2 will be hidden and vice versa. I write JQuery code like this:
$(document).ready(function () {
var inputText = document.getElementById("input1");
var textLength = inputText.value.length;
if (textLength <= 0){
$('#input2').hide("fast");
}
else{
$('#input2').show("fast");
}
});
It works only after each time refresh. So how to catch the input event in input1 and affect the change immediately to input2?
You can try this code:
$(document).ready(function () {
var input1 = $('#input1');
function toggleInput() {
if(input1.val().length) {
$('#input2').show("fast");
} else {
$('#input2').hide("fast");
}
}
toggleInput();
$('#input1').on('keyup', toggleInput);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
input1
<input type='text' id='input1' name='input1'>
<br>
input2
<input type='text' id='input2' name='input2'>
<br>
you can wrap it on jquery keydown or keyup function.
<script>
$(document).ready(function() {
$("#input1").keydown(function() {
var inputText = this.value;
var textLength = inputText.length;
if (textLength <= 0) {
$('#input2').hide("fast");
} else {
$('#input2').show("fast");
}
});
});
JS fiddle
You need to add event listeners for these elements. Example using mostly your original code.
$(document).ready(function() {
$('#input1').on("keyup", function() {
var inputText = document.getElementById("input1");
var textLength = inputText.value.length;
if (textLength <= 0) {
$("#input2").hide("fast");
} else {
$("#input2").show("fast");
}
})
});
$('#input1').on('input', function() {
$('#input2').toggle($(this).val().length === 0);
});
This solution assumes that you have two input textbox only.
First assign a common class like
input1
<input type='text' id='input1' class='input' name='input1'>
<br>
input2
<input type='text' id='input2' class='input' name='input2'>
<br>
$(".input").change(function(){
alert(this.id);
if(this.id == 'input1')
{
if ($(this).val().length > 0){
$("#input2").show();
} else {
$("#input2").hide();
}
}
else
{
if ($(this).val().length > 0){
$("#input1").show();
} else {
$("#input1").hide();
}
}
});
Replace your javascript with this code! This code improves the performance of your application as it uses selectors only once!
$(document).ready(function () {
var input1 = $('#input1');
var input2 = $('#input2');
input2.hide("fast");
input1.on('keyup', function() {
if(input1.val().length) {
input2.show("fast");
} else {
input2.hide("fast");
}
});
});

How to store user inputs in a variable?

I keep trying this and it still says it is wrong. It keeps saying that numberOfRounds is undefined. Is there another way I can do it? I want it to run the statement "Choose the ___ color" the amount of times the user wants.
<html>
<!--This is the start screen that you see to begin the game. You also select how many rounds of the game you would like.-->
<font size="6"><center><strong><p id="startScreen">Welcome to the Random Color Game.</p></strong></center></font>
<font size="4"><center><p id="startScreen2">How many many rounds of the game would you like?</p>
<form id="numberOfRounds"><p id="startScreen3">I would like <input id="numberOfRounds" type="number" min="1" max="20" name="numberOfRounds"> rounds.</p>
<p id="startScreen5">To start playing the game, push begin.</p></center></font>
<center><h4 id="sayColor"></h4></center>
<center><p id="startButton"><button type="button" onclick="startGame();buttonColors();">Begin</button></p></center>
<!--this is the paragraph that will have all the buttons placed inside.-->
<center><p id="game"></p><center>
<script>
var randomNumber = 0;
var redPressed = false;
var bluePressed = false;
var greenPressed = false;
var purplePressed = false;
var orangePressed = false;
var x = 1;
function startGame()
{
buttonColors();
//gets rid of the start screen text
document.getElementById("startScreen").innerHTML = "";
document.getElementById("startScreen2").innerHTML = "";
document.getElementById("startScreen3").innerHTML = "";
document.getElementById("startScreen5").innerHTML = "";
//makes the text for the game
document.getElementById("startButton").innerHTML = "<button type='button' onclick='location.reload()'>Restart</button>";
document.getElementById("game").innerHTML = "<button type='button' onclick='redPressed = true;redCheck();' style='background-color:red'>Red</button><button type='button' onclick='bluePressed = true;blueCheck();' style='background-color:blue'>Blue</button><button type='button' onclick='greenPressed = true;greenCheck();' style='background-color:green'>Green</button><button type='button' onclick='purplePressed = true;purpleCheck();' style='background-color:purple'>Purple</button><button type='button' onclick='orangePressed = true;orangeCheck();' style='background-color:orange'>Orange</button>";
//checks to see if the function ran
console.log("startGame() ran.");
makeRounds();
}
function makeRounds()
{
//takes the number of rounds and puts it into a variable so it shows the amount of questions you want
var numberOfRounds = document.getElementById("numberOfRounds").value;
console.log(numberOfRounds);
x = numberOfRounds*2;
console.log(x);
while (x<=numberOfRounds)
{
randomNumber = ( Math.floor(Math.random() * 5));
console.log(randomNumber);
}
}
function buttonColors()
{
if (randomNumber==1)
{
document.getElementById("sayColor").innerHTML = "Push the red button."
}
if (randomNumber==2)
{
document.getElementById("sayColor").innerHTML = "Push the blue button."
}
if (randomNumber==3)
{
document.getElementById("sayColor").innerHTML = "Push the green button."
}
if (randomNumber==4)
{
document.getElementById("sayColor").innerHTML = "Push the purple button."
}
if (randomNumber==5)
{
document.getElementById("sayColor").innerHTML = "Push the orange button."
}
}
function redCheck()
{
if (randomNumber==1)
{
correct();
}
else
{
incorrect();
}
x--;
}
function blueCheck()
{
if (randomNumber==2)
{
correct();
}
else
{
incorrect();
}
x--;
}
function greenCheck()
{
if (randomNumber==3)
{
correct();
}
else
{
incorrect();
}
x--;
}
function purpleCheck()
{
if (randomNumber==4)
{
correct();
}
else
{
incorrect();
}
x--;
}
function orangeCheck()
{
if (randomNumber==5)
{
correct();
}
else
{
incorrect();
}
x--;
}
function correct()
{
console.log("DATS RIGHT!!");
window.alert("Correct!")
}
function incorrect()
{
console.log("Incorrect.");
window.alert("Incorrect.");
}
</script>
</html>
<form id="numberOfRounds"><p id="startScreen3">I would like <input id="numberOfRounds" type="number" min="1" max="20" name="numberOfRounds"> rounds.</p>
Both have same id, numberOfRounds.

Getting values from elements added dynamically

http://jsfiddle.net/R89fn/9/
If any of the text input/Box added are empty then the page must not submit.when I try to retrieve values from the text inputs using their id`s nothing gets retrieved is it possible to retrieve values from elements added dynamically?
$("#submit").click(function (event) {
var string = "tb";
var i;
for (i = 1; i <= count; i++) {
if (document.getElementById(string+1).value=="") {
event.preventDefault();
break;
}
}
});
The above code is what I am using to get the value from the text fields using there id
I took a look on the code in the JSFiddle. It appears that the input textboxes are not given the intended IDs; the IDs are given to the container div.
The code for the add button should use this,
var inputBox = $('<input type="text" id="td1">') //add also the needed attributes
$(containerDiv).append(inputBox);
Check out this solution on fiddle: http://jsfiddle.net/R89fn/15/
var count = 0;
$(document).ready(function () {
$("#b1").click(function () {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$('#form').append("<div class=\"newTextBox\" id=" + tb + ">" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function () {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function (event) {
var inputBoxes = $('#form').find('input[type="text"]');;
if (inputBoxes.length < 1) {
alert('No text inputs to submit');
return false;
} else {
inputBoxes.each(function(i, v) {
if ($(this).val() == "") {
alert('Input number ' + (i + 1) + ' is empty');
$(this).css('border-color', 'red');
}
});
alert('continue here');
return false;
}
});
});
<form name="form" id="form" action="htmlpage.html" method="POST">
<input type="button" id="b1" name="b1" value="Add TextBox" />
<input type="button" id="b2" name="b2" value="Remove TextBox" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
var count = 0;
$(document).ready(function() {
$("#b1").click(function() {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$(this).before("<div class=\"newTextBox\" id= "+ tb +" >" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function() {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function(event) {
var string = "#texttb";
var i;
for (i = 1; i <= count; i++) {
if ($('input[type = text]').val() == "") {
event.preventDefault();
break;
}
}
});
});
</script>
<style>
.newTextBox
{
margin: 5px;z
}
</style>
Reason:
you had given id to the div element. so its not get retrive. i had updated the answer with the usage of jquery functions and changed your code for this requirement.
If I understand correctly, your only issue atm is to make sure that the form is not sent if one of the inputs are empty? Seems the solution to your problem is simpler. Simply add required at the end of any input and HTML5 will ensure that the form is not sent if empty. For example:
<input type="text" required />

Function with if else statement - javascript

Could anyone please tell me what I'm doing wron here?
I'm sort of new to Javascript and I can't get this function to work the way i want it..
Basically if i type in ABCJ in the number1 field , i want to display 123X in the ansarea
<!DOCTYPE html>
<html>
<body>
<script>
function convert(number1)
{
for(var i=0;i<number1.length();i++)
{
if(number1[i]=='A')
{
document.getElementById("ansarea").innerHTML="1";
}
else if(number1[i]=='B')
{
document.getElementById("ansarea").innerHTML="2";
}
else if(number1[i]=='C')
{
document.getElementById("ansarea").innerHTML="3";
}
else if(number1[i]=='D')
{
document.getElementById("ansarea").innerHTML="4";
}
else if(number1[i]=='E')
{
document.getElementById("ansarea").innerHTML="5";
}
else
{
document.getElementById("ansarea").innerHTML="x";
}
}
}
</script>
<form>Enter here : <input type="text" name="number1"><br></form>
<button type="button" onclick="convert("number1")">Convert</button>
<div id="ansarea"><input type="text" name = "ans"></div>
</body>
</html>
this will make you code work...
<!DOCTYPE html>
<html>
<body>
<script>
function convert() {
var valu = document.getElementById("some").value;
document.getElementById("ansarea").innerHTML = "";
for (var i = 0; i < valu.length; i++) {
if (valu[i] == 'A') {
document.getElementById("ansarea").innerHTML += "1";
} else if (valu[i] == 'B') {
document.getElementById("ansarea").innerHTML += "2";
} else if (valu[i] == 'C') {
document.getElementById("ansarea").innerHTML += "3";
} else if (valu[i] == 'D') {
document.getElementById("ansarea").innerHTML += "4";
} else if (valu[i] == 'E') {
document.getElementById("ansarea").innerHTML += "5";
} else {
document.getElementById("ansarea").innerHTML += "x";
}
}
}
</script>
<form>Enter here : <input type="text" name="number1" id="some"><br>
<button type="button" onclick="convert()">Convert</button>
<div id="ansarea"></div>
</form>
</body>
</html>
you dont need to pass a value to convert() since you are getting the value from the input field, you dont need the other input field, since you putting the text in a div..
This is another working example:
<!DOCTYPE html>
<head>
<script>
function convert()
{
var number1 = document.getElementById('textbox_id').value;
for(var i=0;i<number1.length;i++)
{
if(number1.charAt(i)=='A')
{
document.getElementById("ansarea").innerHTML +="1";
}
else if(number1.charAt(i)=='B')
{
document.getElementById("ansarea").innerHTML +="2";
}
else if(number1.charAt(i)=='C')
{
document.getElementById("ansarea").innerHTML +="3";
}
else if(number1.charAt(i)=='D')
{
document.getElementById("ansarea").innerHTML +="4";
}
else if(number1.charAt(i)=='E')
{
document.getElementById("ansarea").innerHTML +="5";
}
else
{
document.getElementById("ansarea").innerHTML +="x";
}
}
}
</script>
</head>
<body>
Enter here : <input type="text" name="number1" id='textbox_id'>
</br>
<button type="button" onclick="convert()">Convert</button>
<div id="ansarea"></div>
</body>
</html>
Few things to notice here:
You can take the value from inside the function convert()
You don't need the second onpening <html> tag after <!DOCTYPE html>
It's better not to skip the <head> tag
For this task specifically you don't need <form> so I've removed it, but you can add it if you plan to submit to some other method or something...
First, welcome to javascript ! Because you are starting, a good rule of thumb to start is to find your way around repetitions.
Here's another example on how you can execute exactly the same thing as in the other answers using a map:
// let's map all the characters you need against some digits
// this will make it super easy to add, remove or swap things around.
var map = { A: '1', B: '2', C: '3', D: '4', E: 5 };
// for example, map['A'] will now have the value of '1'
// we can store the output element once for good,
// so you don't have to look it up over and over again.
var outputElement = document.getElementById('ansarea');
function convert( inputString ) {
// the result variable will temporary store the result, so let's start empty
var result = "";
for ( var i = 0; i < inputString.length; i ++ ) {
// grab the current character so we don't have to look it up twice
var char = inputString[i];
if ( typeof map[char] !== 'undefined' ) {
// cool, the character existed within the map.
// We can append its value to the result:
result += map[char];
} else {
// ... if not add 'x'
result += 'x';
}
}
// and finally, populate the HTML with the result
outputElement.innerHTML = result;
}
innerHTML - it is property containing html in element. And every time you completely rewriting it.
Try this:
document.getElementById("ansarea").innerHTML+="1";
document.getElementById("ansarea").innerHTML+="2"; // etc
By += (instead =) you will concatenate old value with new.
And you must change you function call.
Try this (i don't test it):
function convert(selector) {
var dataFromInput = document.querySelector(selector);
var dataLength = dataFromInput.length();
var ansarea = document.getElementById("ansarea");
for(var i = 0; i < dataLength; i++) {
switch (dataFromInput[i]) {
case 'A':
ansarea.innerHTML += '1';
break;
case 'B':
ansarea.innerHTML += '2';
break;
case 'C':
ansarea.innerHTML += '3';
break;
case 'D':
ansarea.innerHTML += '4';
break;
case 'E':
ansarea.innerHTML += '5';
break;
default:
ansarea.innerHTML += 'x';
}
}
}
and add id for input:
<form>Enter here : <input type="text" name="number1" id="number1"><br></form>
<button type="button" onclick="convert('#number1')">Convert</button>

Validating a single radio button is not working in available javascript validation script Part-2

I am available with the solution given by #Tomalak for MY QUESTION could you pls help me out with it as its giving me an error in firebug as : frm.creatorusers is undefined
[Break On This Error] var rdo = (frm.creatorusers.length >...rm.creatorusers : frm.creatorusers;
I used the code for validating radio button as:
function valDistribution(frm) {
var mycreator = -1;
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : frm.creatorusers;
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
mycreator = 1;
//return true;
}
}
if(mycreator == -1){
alert("You must select a Creator User!");
return false;
}
}
Here is how to use the code you were given by #Tomalak but did not copy correctly
function valDistribution(frm) { // frm needs to be passed here
var myCreator=false;
// create an array if not already an array
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : [frm.creatorusers];
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
myCreator=true;
break; // no need to stay here
}
if (!myCreator){
alert("You must select a Creator User!");
return false;
}
return true; // allow submission
}
assuming the onsubmit looking EXACTLY like this:
<form onsubmit="return valDistribution(this)">
and the radio NAMED like this:
<input type="radio" name="creatorusers" ...>
You can try this script:
<html>
<script language="javascript">
function valbutton(thisform) {
myOption = -1;
alert(thisform.creatorusers.length);
if(thisform.creatorusers.length ==undefined) {
alert("not an array");
//thisform.creatorusers.checked = true;
if(thisform.creatorusers.checked) {
alert("now checked");
myOption=1;
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers.value);
}
}
else {
for (i=thisform.creatorusers.length-1; i > -1; i--) {
if (thisform.creatorusers[i].checked) {
myOption = i; i = -1;
}
}
if (myOption == -1) {
alert("You must select a radio button");
return false;
}
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers[myOption].value);
}
}
</script>
<body>
<form name="myform">
<input type="radio" value="1st value" name="creatorusers" />1st<br />
<!--<input type="radio" value="2nd value" name="creatorusers" />2nd<br />-->
<input type="button" name="submitit" onclick="valbutton(myform);return false;" value="Validate" />
<input type="reset" name="reset" value="Clear" />
</form>
</body>
</html>

Categories