I have a page whereby the user can press left + right buttons to scroll through numbers between 1-10.
The default value is 0 which displays blank.
There are two buttons at the bottom which allow the user to 'Clear' the number - reseting it to 0. Or to 'Shuffle', picking a random number.
After this the user can submit these numbers into a database.
My issue is, if the user were to scroll to 5 (for example), click shuffle then submit, it would submit '5' instead of the random number it should have generated.
Also if the user only clicks 'shuffle' then submit, it'll input '0'.
The issue with the 'clear' button is similar, if the user scrolls to 5, then hits reset, the variable would stay at '5' when submitted.
I'm probably overcomplicating something very simple, and im sorry if i am, but this is annoying me.
Thankyou ~
I'm not entirely certain what the problem is without looking at your code. I get the feeling it is something like this:
Javascript
var opNumb = 0; //default number
left = function(){if (opNumb>0) opNumb--;
updateNumb(opNumb);}
right = function(){if (opNumb<10) opNumb++;
updateNumb(opNumb);}
def = function(){opNumb=0;
updateNumb(opNumb);} //function to return to default
randomNumb = function(){opNumb = Math.floor(Math.random() * 11);
updateNumb(opNumb);}
updateNumb = function(Numb){document.forms[0].opVal.value = Numb;}
window.onkeydown = press; //bind keydown to press function
function press(e){
if (e.keyCode == 37) left();
if (e.keyCode == 39) right()
}
HTML form
<form id="frm1">
<input type="text" name="opVal" value="0"/><br />
<input type="button" value="left" onclick="left()"/><input type="button" value="right" onclick="right()"/><input type="button" value="Clear" onclick="def()"/><input type="button" value="Shuffle" onclick="randomNumb()"/><br />
<input type="button" value="Submit form" onclick="alert(opNumb);"/>
</form>
What does your form look like? You're most likely having a problem setting a value?
Link to example
It sounds like your number isn't saving so whenever you update the number on the screen I would save the number then that way you should always be sending the number that you see.
var number = 0;
//All your events to call the different functions
function moveLeft{
//logic
reset(num);
}
function moveRight{
//logic
reset(num);
}
function shuffle{
//logic
reset(num);
}
function reset{
//logic
reset(num);
}
reset(num){
number = num;
//update the HTML
}
Related
I need help. I am doing a project and am creating a simple survey. The code I have should work. Upon pressing the "yes" button, it should add 1 to the "artscore" variable. Then when I press "submit" it should check if the variable is over 1 and if it says "You are an artist" and if it isn't bigger than 1 it should say "You are something different". However whenever I do this and press submit it always says "You are something different", even when I have clicked "yes" multiple times. It should work but it doesn't. I am a complete beginner and the answer may be very simple. I have made multiple prototypes but I want to figure out how to make a survey this way.
Thank you for any help.
BTW the HTML part of this code got taken away. This website wouldn't let me put it in. This is just the javascript part without the beginning script tag. The beginning HTML just had some buttons which when click ran the two functions. The yes button runs the artFunction function and the submit button runs the submitFunction function. I also don't know why the code below is in two parts. Thanks for any help on why this code doesn't work.
var artscore = 0;
function artFunction(){
artscore = artscore + 1;
}
function submitFunction(){
if (artscore > 1){
alert("You are an artist");
} else {
alert("You are something different");
}
}
I am not completely sure whether this will solve the problem, but the problem may be in the if statement in the submit function. You are currently checking for if artscore is greater than 1, but in your art function you are adding one to artscore. You should instead check for if artscore is greater than or equal to 1. Hope that helps!!
You are missing >=, you are using >, because of > when ever you click Art button first time it is showing "You are something different" message instead of "You are an artist"
var artscore = 0;
function artFunction(){
//console.log(artscore);
artscore = artscore + 1;
}
function submitFunction(){
//console.log(artscore);
if (artscore >= 1){
alert("You are an artist");
} else {
alert("You are something different");
}
}
<div id="wrapper">
<h1>What type of field are you interested in?</h1>
<p>Take this questionnaire to find out!</p>
<h2> ART1 <h2>
<input id="button" type="submit" name="button" onclick="artFunction();" value="Yes"/>
<button type="button">No</button>
<input id="button" type="submit" name="button" onclick="submitFunction();" value="Submit"/>
</div>
I would suggest being more specific with your code i.e.
function submitFunction(){
if (artscore >= 1){
alert("You are an artist");
} else if (artscore < 1){
alert("You are something different");
} else {
alert("An error has occurred!");
}
}
Change
if (artscore > 1)
to
if (artscore >= 1)
and also check if you are calling the funcation.
Hello guys need some help here. i want to have limit the numbers inputted in my input field by putting max attribute to it. i have no problem with that until i use my keyboard to input data on it. seems like the max attribute is not filtering the input coming from the keyboard.
e.g
<input type="number" max="5" />
i can't go until 6 using the up and down arrow but when i manually put 6 using keyboard it's accepts it. how can i prevent? thank you
You would need to use JavaScript to do it. This will not let the user enter a number higher than 5:
<input type="number" max="5" onkeyup="if(this.value > 5) this.value = null;">
Another possible solution is to completely block the keyboard input by replacing onkeyup=".." event in the code above with onkeydown="return false".
have no problem with that until i use my keyboard to input data on it.
seems like the max attribute is not filtering the input coming from
the keyboard
This is how HTML5 validation/constraint work. However, it will invalidate when the form submits. Alternatively, you can validate it yourself. To validate yourself, you need to wire up Javascript and call the checkValidity() on the input element.
checkValidity() of the constraints API will check the validity state of the element and will return the state of whether the input element validate or not. This will also set the validity object on the input so that you can query more details.
Ref: https://html.spec.whatwg.org/multipage/forms.html#constraints and https://html.spec.whatwg.org/multipage/forms.html#form-submission-algorithm
You can also use the :invalid selector in CSS to highlight invalid inputs.
Example Snippet:
var input = document.getElementById('test'),
result = document.getElementById('result');
input.addEventListener('blur', validate);
function validate(e) {
var isValid = e.target.checkValidity();
result.textContent = 'isValid = ' + isValid;
if (! isValid) {
console.log(e.target.validity);
}
}
input[type=number]:invalid {
border: 2px solid red;
outline: none;
}
<label>Enter value and press tab: </label><br/>
<input id="test" type="number" min="1" max="10" />
<hr/>
<p id="result"></p>
You can use javascript to restrict the maximum input value to 5.
HTML
using oninput as a event handler
<input type="number" max="5" oninput="checkLength(this)" />
JS
function checkLength(elem) {
// checking if iput value is more than 5
if (elem.value > 5) {
alert('Max value is 5')
elem.value = ''; // emptying the input box
}
}
DEMO
An Utility Function to Solve Two Problem
Problem 1: Limit user input to maximum n digit
For this use n number of 9 as max parameter. As an example if you want to limit user input in 4 digit then max param value will be 9999.
Problem 2: Limit user input at a maximum value
This is intuitive. As an example If you want restrict the user input to maximum 100 then max param value will be 100.
function getMaxInteger(value, max) {
if(!value) return;
if( parseInt(value) <= max ) {
return value;
}
return getMaxInteger(value?.substr(0, value?.length-1), max);
}
function maxInt(value, max) {
return getMaxInteger(value?.replace(/\D/,''), max);
}
Use this maxInt method on input change handler
ngModelChange for Angular
onChange for React
v-on:change or watch for Vue
onkeyup="if(this.value > <?=$remaining?>) this.value = null; else if(this.value < 1) this.value = null;"
I have a form with inputs which also has an iFrame embedded in the form which also has inputs (pseudo HTML):
<input type="text" name="one" value="one" />
<input type="text" name="two" value="two" />
<input type="text" name="three" value="three" />
<iframe
<input type="text" name="bacon" value="bacon">
</iframe>
<input type="text" name="four" value="four" />
<input type="text" name="five" value="five" />
When the user presses tab they are taken from input to input even inside the iframe fields selecting bacon after three. We all love bacon.
I also have some javascript that attempts to focus the next input on enter key:
$(document).ready(function() {
$(document).on('keydown', 'input', function(ev) {
// Move to next on enter
if (ev.which === 13) {
var inputs = $(':tabbable');
var next = inputs.index(this) + 1;
var input = inputs.eq(next == inputs.length ? 0 : next);
input.focus();
return false;
}
});
});
The problem is the javascript enter key code never focuses the bacon field, it will skip right over it. jsfiddle:
https://jsfiddle.net/54n8mqkh/4/
Let's all skip answers that include not using the iFrame. I know it is not an ideal implementation. However, I would accept ANY answer that allows the enter key to move through all the fields consistently including the iframe using any type of javascript. It does not have to be jquery specific.
I have tried a few different approaches to solve this but none I have found works. Thanks in advance to anyone who has a solution.
You need to focus inside of the iframe like so :
var frameBody = $("#IFrame_input").contents().find("input");
frameBody.focus();
I am going to answer my own question - after a few more hours I was able to solve my use case by expanding my selector to include the iframe. Then I build the array of inputs manually and while iterating I checked the node type for an iframe. If / when I encountered an iframe, I did the same select inside the iframe and added the inputs within the iframe:
$(document).ready(function() {
// Parent level helper function
window.tabToNext = function(me) {
var selector = ':tabbable, iframe';
var inputElems = [];
$(selector).each(function(index) {
var nodeName = $(this).prop('nodeName').toLowerCase();
if (nodeName == 'iframe') {
$(this).contents().find(selector).each(function(index) {
inputElems.push(this);
});
} else {
inputElems.push(this);
}
});
var inputs = $(inputElems);
var next = inputs.index(me) + 1;
if (next == inputs.length) next = 0;
var input = inputs.eq(next);
input.focus();
return false;
}
$(document).on('keydown', 'input', function(ev) {
// Move to next on enter
if (ev.which === 13) {
return window.tabToNext(this);
}
});
// Focus the first input
$('input[name=one]').focus();
});
FWIW: I could not just expand the selector as best I could tell and also I tried to use $.add to build the collection starting with an empty jQuery collection:
var foo = $([]);
foo.add(someElement);
... but it does not honor the order you add. It will re-order to the DOM according to the docs which SEEMS like it should be right, but for some reason my iframe child fields always ended up last and messed up the tab order.
Anyhow, I hope if someone else has this issue some day you find this helpful. Working solution:
https://jsfiddle.net/wbs1zajs/6/
Would someone be able to take a look at my code and see what I'm missing here?
I have a multi-page form with quite a lot of inputs, and I would like to keep "next page" buttons and the final "submit" buttons disabled until all the fields are full.
I am trying to recreate the process on a smaller scale but in my tests, I cannot seem to re-enable the disabled submit input. I've checked the console and the JS is logging the variable elements so I'm not sure what I'm missing.
function checkForm()
{
var elements = document.forms[0].elements;
var cansubmit= true;
for(var i = 0; i < elements.length; i++)
{
if(elements[i].value.length == 0 || elements[i].value.length == "" || elements[i].value.length == null)
{
cansubmit = false;
}
document.getElementById("myButton").disabled = !cansubmit;
}
};
<form>
<label for="firstName">First Name:</label> <input type="text" id="firstName" onkeyup="checkForm()" />
<br />
<label for="lastName">Last Name:</label> <input type="text" id="lastName" onkeyup="checkForm()" />
<button type="button" id="myButton" disabled="disabled">Test me</button>
</form>
Your elements array includes your button, which has no value. This will cause your loop to always evaluate to cansubmit = false;.
Try this instead: https://jsfiddle.net/e00sorLu/2/
function checkForm()
{
var elements = document.forms[0].elements;
var cansubmit= true;
for(var i = 0; i < elements.length; i++)
{
if(elements[i].value.length == 0 && elements[i].type != "button")
{
cansubmit = false;
}
}
document.getElementById("myButton").disabled = !cansubmit;
};
Answer was already accepted, but here are a few other things you might consider:
The way you have it set up now, for absolutely anything other than an empty string "" you're setting button.disabled = false and enabling the button.
You're checking value.length 3 times, but you actually want to
check .value instead. The length property is only a numeric
value for how many code units are in the string - it won't ever be
"" or null, so the only thing you're really checking is the very
first condition for an empty string of length 0.
You're also not accounting for multiple white spaces in a blank string, so " " would be valid) ... or
special characters, so this would be valid: (function goodByeWorld(evil){//do the bad things})();
You're running the checkForm() function on all form elements
(including the <button>) after every single keystroke. This is unnecessary.
Aside from including <button>, which was pointed out in the accepted answer & will always cause this to fail, you should either validate each individual form element with inline error checking
(preferable), or validate all of them once just prior to submission (preferable to server-side validation & kicking it back after submission).
You could bind to onblur() instead and send the current element's value as an argument once that field loses focus. e.g. change to: function checkValue(value) {//validate the value}) and either onblur = checkValue(this) in the HTML or preferably a non-inline event handler that lives in the JS file instead.
You could still do it onkeyup = checkValue(this) to check after every keystroke, but change the function to only check 1 element instead of checking t.h.e. e.n.t.i.r.e. f.o.r.m. dozens of times.
This approach would let you individually keep track of each separate form element's validity (lots of options here depending on what "valid" means - store an array of values, objects with values or "valid/invalid" flags, etc, switch on the field labels to validate this for different types of information). You can run additional validation on the individual elements as well (e.g. min/max name length, eliminating special characters, etc), and display real-time error checking messages next to each form element.
You're defaulting to cansubmit = true which doesn't make much sense, given what you intend for this code to do. Using !cansubmit only serves to confuse yourself & others reading the code. For readability, consider inverting it to disableSubmit so it's in sync with the button.disabled state, which should only be true or false.
Or you can use jQuery.
<script type="text/javascript">
function checkForm() {
var cansubmit = false;
$('form input[type="text"]').each(function (index, element) {
if (element.value == "") {
cansubmit = true;
}
});
document.getElementById("myButton").disabled = cansubmit;
}
</script>
I am trying to display a button, starting with "unmarked". As the user clicks the button, I need it to change to the next button, "form". When each of these clicks happen, I would like a post request made through ajax to update the value in the database associated with the ID of the button. This ID comes from the database where other information is being shown next to the button. I believe that part is done with an onclick=functionname(123456) event? When the user reaches the end (completed), another click simply starts it over at unmarked.
I've been searching stackoverflow for hours however have not been able to find anything related to what I am trying to do and very new to jquery/ajax/javascript
<button type="button" name="Unmarked" value="0" class="btn btn-default"/>Unmarked</button>
<button type="button" name="Form" value="1" class="btn btn-info"/>Form</button>
<button type="button" name="Frame" value="2" class="btn btn-primary"/>Frame</button>
<button type="button" name="S/NB" value="3" class="btn btn-warning"/>S/NB</button>
<button type="button" name="S/B" value="4" class="btn btn-danger"/>S/B</button>
<button type="button" name="Completed" value="5" class="btn btn-success"/>Completed</button>
I'm hoping someone can at least point me in the right direction.
Based on your comment...
We have an array of the item id's that you want to iterate through.
var buttonArray = ["unmarked", "form", "frame", "snb", "sb", "completed"];
We keep track of which items is currently visible
var currentItemIndex = 0;
Finally we will call the function to change visibility on every button click.
function changeButtonVisibility() {
var buttonClicked = $("#" + buttonArray[currentItemIndex]);
var nextItemIndex = 0;
if(currentItemIndex + 1 > buttonArray.length - 1) {
nextItemIndex = 0;
} else {
nextItemIndex = currentItemIndex + 1;
}
var nextButton = $("#" + buttonArray[nextItemIndex]);
currentItemIndex = nextItemIndex;
buttonClicked.addClass("hidden");
nextButton.removeClass("hidden");
}
Essentially you take the current button, add the class hidden, take the next button, remove the class hidden. The if statement ensures that if you hit the last item, you start over again with the first item.
Lastly, bind the function as a click event to your buttons.
$("#unmarked").click(function() {
changeButtonVisibility();
});
$("#form").click(function() {
...
Depending on your specific use case, you could probably come up with a more elegant way to solve this. Also you can definitely eliminate some lines of code. However, I hope the example gives you a good starting point or idea on how to tackle the problem.
Working example: jsbin.com/xeyejesaxe