I stuck around 5 hours on this issue, I am trying to assign multiple levels to a Sudoku grid (one grid for 3 different levels).
But it's not working, no matter what it's giving me the result of the first function, I mean I write code with function for each level I called the levels- Baby, not so hard, nightmare
gave any one of a specific function but only one working, I gave the same function to all of them but its keep choosing the first one no matter what I am doing.
HTML Coding-
<form method="get" action="./bord.html">
<button onclick="baby()" id="level_1" value="1">Baby</button>
</form>
<form method="get" action="./bord.html">
<button onclick="notSoHard()" id= "level_2" type="submit" value="2">Not so
hard
</button>
</form>
<form method="get" action="./bord.html">
<button onclick="nightmare()" id= "level_3" type="submit"
value="3">Nightmare
</button>
</form>
var level =0
function baby(level){
end()
var level = 30
return level
}
function notSoHard(level){
end()
var level = 50
return level
}notSoHard(level)
function nightmare(level){
end()
var level =70
return level
}nightmare(level)
function end(){
// debugger
if (baby(level) == 30){
return 30;
}if(notSoHard(level) == 50){
return 50;
} if(nightmare(level) == 70){
return 70;
}
}
console.log(end())
I need that the result on the console will be what I chose( 30,50,70)
its giving me 30 all over.
God bless you
How about like this:
function end(event) {
event.preventDefault();
const value = parseInt(event.currentTarget.value);
var level = 0;
if(value === 1) {
level = 30;
} else if (value === 2) {
level = 50;
} else if (value === 3) {
level = 70;
};
console.log(level);
//Add anything else you want to do with the level here
return level;
};
<form method="get" action="./bord.html">
<button onclick="end(event)" id="level_1" value="1">Baby</button>
</form>
<form method="get" action="./bord.html">
<button onclick="end(event)" id= "level_2" type="submit" value="2">Not so hard</button>
</form>
<form method="get" action="./bord.html">
<button onclick="end(event)" id= "level_3" type="submit" value="3">Nightmare</button>
</form>
You only really need one function to get the value. Here, the value attribute of the button (1, 2 or 3) is being used to define which level to apply. You could instead pass in an argument to the end function to differentiate between the buttons.
Your code above would get into a stack overflow when I tried it, because the functions were calling each other recursively. It's better to keep it simple :)
Related
In my HTML form, it's possible to add additional inputs dynamically by clicking a button. I've got this part to work, however I need each input to have a unique name.
This is my code so far,
<div class="control-group field_wrapper">
<label class="control-label"><strong> Phone Number 1</strong></label>
<input type="text" class="input-medium" name="phone_number[]">
<button class="btn btn-success add-number" type="button" title="Add">Add</button>
</div>
<div class="additionalNumber"></div>
My JS as below,
$(document).ready(function(){
var maxField = 10;
var addButton = $('.add-number');
var wrapper = $('.additionalNumber');
function fieldHTML(inputNumber) {
return `<div class="control-group field_wrapper">\
<label class="control-label"><strong> Phone Number ${inputNumber}</strong></label>\
<input type="text" class="input-medium" name="phone_number[${inputNumber}]">\
<button class="btn btn-danger remove" type="button">Remove</button>\
</div>`;
}
var x = 1;
$(addButton).on('click', function(e) {
if (x < maxField) {
x++;
$(wrapper).append(fieldHTML(x));
}
if (x >= maxField) {
alert('Limited to 10.');
}
});
$(wrapper).on('click', '.remove', function(e) {
e.preventDefault();
$(this).parents('.control-group').remove();
x--;
});
});
Using this code, I can get unique name for each input which are created by dynamically. But my problem is name[x] index not works properly when it is removing. That mean, just think I have added 3 input and delete second one and again I am adding new one, then it has same name twice. In this case, it is phone_number[3] for second input and phone_number[3] for thirt one also.
This is the fiddle from above code. Any help is appreciated.
You don't need to index the inputs for PHP either - 3x inputs named phone_number[] will automatically be indexed 0 - 2 on the back end:
<input type="text" name="phone_number[]">
<input type="text" name="phone_number[]">
<input type="text" name="phone_number[]">
[phone_number] => Array
(
[0] => a
[1] => b
[2] => c
)
That doesn't help with your plain text Phone Number n label though. And maybe you have your own reasons to want an input name index.
If you think about it, if you're going to allow deletions of any item in the list, and you need the results to be sequential, the only option is to renumber everything each time you make a change. You don't need to include any numbering when you add a new element, just regenerate all numbering.
Here's a working snippet doing that. My changes:
No need to pass the count x to fieldHTML(), we're going to renumber everything after you add the element;
Add a <span class='count'></span> in your label, which we can target and update;
Add a reNumber() function which will iterate over all inputs on the page and number them sequentially;
Call that function after any change;
Notes:
The 2 separate tests if (x < maxField) and if (x >= maxField) can be combined into a single if/else;
If you want to get rid of the duplication of your HTML block, you could give the first one an id like template, and then instead of duplicating that HTML in your JS, just copy the template, eg :
let $copy = $('#template').clone();
wrapper.append($copy);
wrapper and addButton are already jQuery objects, no need to wrap them with $() a second time to use them;
If you do want to number your input names, for consistency the first should probably be phone_number[1];
$(document).ready(function() {
var x = 1;
var maxField = 10;
var addButton = $('.add-number');
var wrapper = $('.additionalNumber');
function fieldHTML() {
return `<div class="control-group field_wrapper">\
<label class="control-label"><strong> Phone Number <span class='count'></span></strong></label>\
<input type="text" class="input-medium" name="phone_number[]">\
<button class="btn btn-danger remove" type="button">Remove</button>\
</div>`;
}
/**
* Iterate over all inputs and renumber sequentially
*/
function reNumber() {
let count;
wrapper.find('.field_wrapper').each(function (i) {
// .each() index is 0-based, and input #1 is already on the page,
// so extras start at #2
count = i + 2;
$('.count', $(this)).html(count);
// If you want to index your input names, but you can safely leave
// this out, PHP will index them anyway
$('input', $(this)).attr('name', 'phone_number[' + count + ']')
});
}
addButton.on('click', function(e) {
if (x < maxField) {
x++;
wrapper.append(fieldHTML());
reNumber();
} else {
alert('Limited to 10.');
}
});
wrapper.on('click', '.remove', function(e) {
e.preventDefault();
$(this).parents('.control-group').remove();
x--;
reNumber();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="control-group field_wrapper">
<label class="control-label"><strong> Phone Number 1</strong></label>
<input type="text" class="input-medium" name="phone_number[]">
<button class="btn btn-success add-number" type="button" title="Add">Add</button>
</div>
<div class="additionalNumber"></div>
I'm very new to Javascript and want to build a vending machine for my first Project. I have the problem that I want to make it so that if the right amount is paid, there is an alert saying 'You have paid for your item', but currently it's not working when the display reaches 0. I think it's because the variable amount isn't changed and instead it just displays a different number. How do I get it to actually alert when I have inserted the right amount of 1 cent coins. I tried to google my problem but I don't even know how exactly to describe it.
var item1 = 100;
var ct1 = 1;
function showPrice1()
{
document.getElementById("display").innerHTML = item1;
}
function insert1cent()
{
document.getElementById("display").innerHTML = item1 -= ct1;
}
if (item1 == 0)
{
alert('You have paid for your item');
}
and this is the HTML:
<body>
<div id="display">
</div>
<button id="button1" type="button" onclick="showPrice1()">
1
</button>
<button id="ct1" type="button" onclick="insert1cent()">
1ct
</button>
</body>
Thank you in Advance for your help.
The if statement should be inside your function to check on every click and it should return false to avoid decrementing once your counter reaches 0. As demonstrated in the fiddle.
var item1 = 10;
var ct1 = 1;
function showPrice1() {
document.getElementById("display").innerHTML = item1;
}
function insert1cent() {
if (item1 == 0) {
alert('You have paid for your item');
return false;
}
item1 -= ct1;
document.getElementById("display").innerHTML = item1;
}
<div id="display">
</div>
<button id="button1" type="button" onclick="showPrice1()">
1
</button>
<button id="ct1" type="button" onclick="insert1cent()">
1ct
</button>
I want to assign the value of input id qty1 to input id qty1send and then send it via POST method when the button Add to cart is pressed. How do I do it? Help!!
<button class="qtyBtn" onclick="increase_by_one('qty1');">+</button>
<input id="qty1" type="text" value="1" name="J1" />
<button class="qtyBtn" onclick="decrease_by_one('qty1');" />-</button>
<form action="somehwere.php" method="POST">
<input id="qty1send" type="hidden" name="qty1" value="" >
<button type="submit"> Add to cart </button>
</form>
my JS code
// Quantity spin buttons
function increase_by_one(field) {
nr = parseInt(document.getElementById(field).value);
document.getElementById(field).value = nr + 1;
}
function decrease_by_one(field) {
nr = parseInt(document.getElementById(field).value);
if (nr > 0) {
if ((nr - 1) > 0) {
document.getElementById(field).value = nr - 1;
}
}
}
You need to create a function and then assign value of qty1 to qty1send using onclick function for submit button. The following code need to be incorporated into your code. Hope it helps :)
HTML Code:
<button type="submit" onclick="myFunction()"> Add to cart </button>
JS Code:
function myFunction() {
document.getElementById("qty1send").value = document.getElementById("qty1").value;
}
The other option is to use the following statement in both of your increase and decrease functions as mentioned by #Rob Moll
document.getElementById("qty1send").value = document.getElementById("qty1").value;
You could add this to each function:
document.getElementById("qty1send").value = document.getElementById(field).value;
So your js would look like:
// Quantity spin buttons
function increase_by_one(field) {
nr = parseInt(document.getElementById(field).value);
document.getElementById(field).value = nr + 1;
document.getElementById("qty1send").value = document.getElementById(field).value;
}
function decrease_by_one(field) {
nr = parseInt(document.getElementById(field).value);
if (nr > 0) {
if ((nr - 1) > 0) {
document.getElementById(field).value = nr - 1;
document.getElementById("qty1send").value = document.getElementById(field).value;
}
}
}
Honestly though, that would just add more bad code to this unusual approach. No disrespect intended, but you should look at some examples and maybe start over with this. Intended as constructive criticism.
I'm having a little trouble with an assignment a teacher dished out to my class involving javascript arrays. What they essentially want us to do is to create sort of cart / calculator hybrid that allows users to input numbers, store them and array and display those numbers on the webpage, then be able to either add them together for a total or reset them and start over.
I think I more or less know how to make a reset button, and I believe I've figured out how to add items to the array efficiently enough, but I'm kinda stumped on how to show those items on an html page and how to add them together to make and show a total. Any help would be appreciated, I'm kinda new at this and so far the instructions from our source material are a bit vague and hard to understand, at least for me!
So far I have some simple html for the input field and an "add number" button which will add the input field to the array (I will limit it to numbers only later and will).
<form onsubmit="return userNumber()">
<p>Number:</p>
<input type="text" id="box" />
<br>
<input type="button" value="Add Number" />
<input type="button" value="Calculate" />
<input type="button" value="Reset" />
</form>
I've no code yet for the Calculate or Reset button, but for the Add Number button which does seem to work properly when I bring up the console, I just need it to also display on the webpage. Here's what I have for that.
var numbers = [];
function userNumber() {
boxvalue = document.getElementById('box').value;
numbers.push(boxvalue);
console.log(numbers);
return false;
}
I've attached an image of what our teacher showed us, they want us to make it only similar in function, looks are not as important.
Once again, thank you to anyone who can assist, I'm very lost on where to go from here!
First, give them all an id. It's a lot easier to work with them when they all have the "names". And then you can easily handle the events (clicks in this example).
Notice, when you click on the "Add" button, before push you need to use parseInt(string, base) since input.value is a string, and + operator is concatenation for string, not addition. Like sum += numbers[i]; below.
And there is a couple of protection for corner cases when you click the "Calculate" button with an empty numbers array for example.
var numbers = [];
var boxInput = document.getElementById("box");
var addBtn = document.getElementById("add");
var calculateBtn = document.getElementById("calculate");
var resetBtn = document.getElementById("reset");
var allNumbers = document.getElementById("all-numbers");
var calculatedNumbers = document.getElementById("calculated-numbers");
addBtn.addEventListener("click", function() {
if (boxInput.value.length > 0) {
numbers.push(parseInt(boxInput.value, 10));
boxInput.value = "";
}
allNumbers.innerHTML = numbers.join(" ");
});
calculateBtn.addEventListener("click", function() {
if (numbers.length === 0) {
return;
}
for (var i = 0, sum = 0; i < numbers.length; i++) {
sum += numbers[i];
}
calculatedNumbers.innerHTML = numbers.join(" + ") + " = " + sum;
});
resetBtn.addEventListener("click", function() {
numbers = [];
boxInput.value = "";
allNumbers.innerHTML = "";
calculatedNumbers.innerHTML = "";
});
<p>
<label for="box">Number:</label>
<input id="box" type="number" />
</p>
<p>
<input type="button" id="add" value="Add Number" />
<input type="button" id="calculate" value="Calculate" />
<input type="button" id="reset" value="Reset" />
</p>
<h3>Numbers added:</h3>
<p id="all-numbers"></p>
<h3>Sums of numbers added:</h3>
<p id="calculated-numbers"></p>
I am trying to make an e-commerce-like webpage (for practice) wherein a click on any of the buttons would update the cart value by the number (quantity) specified on the input element.
So far, I was only able to update the cart from the first form because when I try to assign the function on every form using a loop, the cart updates for a millisecond then returns to zero. I assume its because of the scope.
I know there's an easier way to do this without manually assigning the function for every document.forms[n]
JS
window.onload = function()
{
var getForm = document.forms[0];
var numItems = 0;
getForm.onsubmit = function(event)
{
event.preventDefault();
var getInput = getForm.elements["num-item"].value;
if(parseInt(getInput))
{
numItems = numItems + parseInt(getInput);
var getCart = document.getElementById("item-count");
getCart.innerHTML = numItems;
getForm.reset();
}
else
{
alert("Please enter a valid number");
}
}
HTML
Cart:
<div class="basket">
<p><i class="fa fa-shopping-basket"></i></p>
<p id="item-count">0</p>
</div>
HTML Form: For brevity, I'm only posting 1 form example, but in reality, I have 6 other forms that are exactly the same.
<div class="buy-config">
<form class="buy-form" name="buy-form">
<label>Quantity:</label>
<input type="text" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
</div>
Loop through all of the forms by querying the selector (using whatever method you prefer, depending on performance requirements and markup flexibility -- I've used getElementsByClassName) and executing a for loop.
Inside the loop, bind a function to the "submit" event using addEventListener. You can define the function in-line (as I've done), or define the function elsewhere, assign it to a variable, and reference the variable when binding to the event.
Within the event listener function, you will refer to the form that was submitted as this.
On top of the changes described above, I've made some minor changes to your code:
Your previous version was overwriting the contents of the cart each time. This may have been on purpose, depending on whether you have one "basket" for each item or one overall (this wasn't clear in the question). So, rather than initialize numItems to zero, I've initialized it to the current number of items in the cart.
Consider using input type="number" HTML form elements. They're supported by nearly every browser and only accept digits -- they also have up/down arrows and can be set with the scroll wheel. On browsers that don't support them, they fall back to a basic text input.
var forms = document.getElementsByClassName("buy-form");
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener("submit", function(event) {
event.preventDefault();
var numItems = parseInt(document.getElementById("item-count").innerHTML);
var getInput = this.getElementsByClassName("num-item")[0].value;
if (parseInt(getInput)) {
numItems = numItems + parseInt(getInput);
var getCart = document.getElementById("item-count");
getCart.innerHTML = numItems;
this.reset();
} else {
alert("Please enter a valid number");
}
});
}
<div class="basket">
<p><i class="fa fa-shopping-basket"></i></p>
<p id="item-count">0</p>
</div>
<div class="buy-config">
<form class="buy-form" name="buy-form">
<label>Quantity:</label>
<input type="number" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
</div>
<div class="buy-config">
<form class="buy-form" name="buy-form">
<label>Quantity:</label>
<input type="number" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
</div>
<div class="buy-config">
<form class="buy-form" name="buy-form">
<label>Quantity:</label>
<input type="number" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
</div>
You can use the jQuery selector.
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$(document).ready(function() {
$('.buy-btn').click(function(){
$(this).parent('form').submit();
});
});
</script>
<form class="buy-form">
<label>Quantity:</label>
<input type="text" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
The code above will setup a function for each HTML elements that has the css class buy-btn.
You can select anything using parent, children, prev, next or find function from jQuery.
Of course this is just a basic exemple I'm showing here, and again some simple example could be :
$('.buy-btn').click(function(){
$(this).parent('form').submit();
//var itemCount = $('#item-count').html();
//itemCount++;
//$('#item-count').html(itemCount);
var numItem = $(this).prev('.num-item').val();
$('#item-count').html(numItem);
});
Unfortunately, you're going to have to loop through the elements in your JavaScript and assign the function to each, however you can do it a bit simpler with some querySelector methods thrown in:
window.onload = function() {
var getCart = document.getElementById('item-count');
var forms = document.querySelectorAll('.buy-form');
var numItems = 0;
var isNum = function(n) {
return(!isNaN(parseFloat(n)) && isFinite(n));
};
var handler = function(e) {
(e || event).preventDefault();
var getInput = this.querySelector('.num-item').value;
if(isNum(getInput)) {
numItems += parseInt(getInput);
getCart.innerHTML = numItems;
this.reset();
} else {
alert("Please enter a valid number");
}
};
for(var i = 0, len = forms.length; i < len; i++) {
forms[i].addEventListener('submit', handler);
}
};