This is my first time using JavaScript, and I'm having a hard time integrating HTML, CSS, and JavaScript. I've written (with the help of many) a program that can increase/decrease the number of products by clicking a button as shown here:
HTML
<body>
<table>
<tr>
<td>Shirt</td>
<td>2$</td>
<td>
<form id='shirt' method='POST' action='' >
<input type='button' value='-' class='qtyminus' field='shirt_count' />
<input type='text' name='shirt_count' value='0' class='qty' readonly="readonly"/>
<input type='button' value='+' class='qtyplus' field='shirt_count' />
</form>
</td>
</tr>
<tr>
<td>Suit</td>
<td>3$</td>
<td>
<form id='suit' method='POST' action='#' >
<input type='button' value='-' class='qtyminus' field='suit_count' />
<input type='text' name='suit_count' value='0' class='qty' readonly="readonly"/>
<input type='button' value='+' class='qtyplus' field='suit_count' />
</form>
</td>
</tr>
</table>
<h4>
Total items: <span id="displayCount">0</span>
<p>
Total price: <span id="displayCount">0</span>
</h4>
</body>
JavaScript
jQuery(document).ready(function(){
$('.qtyplus').click(function(e){
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (currentVal == 10) {
$('input[name='+fieldName+']').val(currentVal);
}
else if (!isNaN(currentVal) ) {
$('input[name='+fieldName+']').val(currentVal + 1);
}
else {
$('input[name='+fieldName+']').val(0);
}
});
$('.qtyminus').click(function(e) {
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal) && currentVal > 0) {
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
});
Also can be seen here: http://jsfiddle.net/51ob29sL/
But the problem is, I want the 'total items' to increase/decrease as I click on the buttons. Is there a way to call 2 functions on 1 click?
Also, for the 'total price' part, I want to add the items' respective price into the variable. I feel like I might need to create an object for each item, but failed trying to do so.
Any help or tips would be appreciated.
Welcome to stack overflow :-)
Please make sure you search Stack overflow before asking your own question to avoid getting down voted...
As answered here... jQuery - Append an event handler to preexisting click event
You can add another function to click even by calling...
$('.qtyminus').click(function(e) {
// Function code here
})
But you can just create a function that does what you want it to do, something like this ( assuming id of price span is displayPrice not duplicate displayCount )...
function updateItemsAndPrice() {
var suits = parseInt($('input[name=suit_count]').val()),
shirts = parseInt($('input[name=shirt_count]').val());
$('#displayCount').html(suits + shirts)
$('#displayPrice').html(suits * 3 + shirts * 2)
}
And call it in the same event handlers at the bottom so that after updating the value price and total items are recalculated...
$('.qtyplus').click(function(e){
// Your other code
updateItemsAndPrice();
});
$('.qtyminus').click(function(e) {
// Your other code
updateItemsAndPrice();
});
Here's a fiddler... but try to do without looking at it first ;-)
http://jsfiddle.net/51ob29sL/4/
As #guest271314 said, ids must be unique. Luckily you only had one instance of breaking that rule.
Here is what you need to add to the bottom of each click function:
var shirts = parseInt($("input[name='shirt_count']").val());
var shirtsPrice = shirts * 2;
var suits = parseInt($("input[name='suit_count']").val());
var suitsPrice = suits * 3;
$("#displayCountItems").text(shirts + suits);
$("#displayCountPrice").text(shirtsPrice + suitsPrice);
Get the values from each, add them, display them
Get the values from each, multiply by price, display them
Changed ids:
Total items: <span id="displayCountItems">0</span>
Total price: <span id="displayCountPrice">0</span>
Fiddle: http://jsfiddle.net/51ob29sL/2/
Related
So I have a list of items, on html page, in fact in form, something like this:
ITEM 1 - ID - "checkbox" "number box"
ITEM 2 - ID - "checkbox" "number box"
I have around 400 items like this, and I found a code to copy selected items (where checkbox is selected) to clipboard and paste them where I want. But I can't make it work with quantity. So basicaly what I would like to achieve is to copy selected items with quantity to clipboard.
Can someone please help me about this problem?
<input type="button" id="prikaz" value="show" onclick="displayMaterial();" /> button for the script
<form id="myFrm" name="myFrm"> - form id
<div id="materialValues"></div> - this shows the selected item, where you can copy it
<ul id="myUL"> - ignore this this is just how i made a list
<li><span class="item"><div class=""><table><tr> <td> ARC 4012718 P2-HD-RXR-SA </td> <td> 160771 </td> <td> <input type="checkbox" id=" 160771 " name=" 160771 " value=" 160771 | ARC 4012718 P2-HD-RXR-SA "> </td> </tr></table></div></span></li>
this is just one item from my list
</ul>
and the code: (this is not my code, i found it somewhere and it works for this purpose, but I woud like to add quantity as well, but I don't have enaught knowledge to place part of the script that would handle that, somwhere around tha IF selected part.
<script type="text/javascript">
function displayMaterial()
{
var str = '';
var elem = document.getElementById('myFrm').elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].checked)
str += elem[i].value +"<br>";
}
document.getElementById('materialValues').innerHTML = str;
}
</script>
Can anyone help me on my issue, it seems that my loop doesn't work. I created a random number guessing game, and I wanted to have only 5 tries. And once it hits the 5th try, it will display a message. But it seems that I was able to do it countless time.
function RandomNumber()
{
//get value from random number textbox
var lol=document.getElementById("guess").value;
//get new value from user
var ass=document.getElementById("textbox").value;
var maxtries=5;
for(var i=0;i<=maxtries;i++)
{
if(ass == lol)//if user guess correctly
{
document.getElementById("correct").innerHTML="Correct"
}
else if(ass!=lol)//if user guess wrongly
{
document.getElementById("correct").innerHTML="Not correct"
}
else if (i==maxtries)
{
document.getElementById("correct").innerHTML="No more tries"
}
}
}
This is my <form> codes
<td style="text-align:center">
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()"><br/>
<br/><span id="numbers"></span>
</td>
</tr>
<tr>
<td style="text-align:center">
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()"><br/>
<br/><span id="numbers1"></span>
</td>
</tr>
<tr>
<td style="text-align:center">
<br/><input id="rand" type="submit" value="submit" onclick="Random()" disabled><br/>
<input id="guess" type="text" value="Random Number Generator">
</td>
</tr>
<tr>
<td style="text-align:center">
<br/>Enter your number<br/>
<input id="textbox" type="text"><br/>
<input id="guessing" type="button" value="Random" onclick="RandomNumber()"><br/>
<br/><span id="correct"></span>
</td>
There's a couple problems here. The first and biggest (maybe) is that your loop counts down right away and doesn't give the guesser a chance to make another guess. The second problem is that the 3rd if statement that checks for the number of guesses can never be reached. I have refactored this check to the beginning on the function.
You should call RandomNumber when the user submits a new guess
You can fix this like:
function RandomNumber()
{
if (!this.guesses) {
this.guesses = 1;
} else {
this.guesses++;
if (this.guesses > 5) {
document.getElementById("correct").innerHTML="No more tries";
return; // max guesses exceeded
}
}
//get value from random number textbox
var lol=document.getElementById("guess").value;
//get new value from user
var ass=document.getElementById("textbox").value;
if(ass == lol)//if user guess correctly
{
document.getElementById("correct").innerHTML="Correct"
}
else if(ass!=lol)//if user guess wrongly
{
document.getElementById("correct").innerHTML="Not correct"
}
}
Right now, your loop runs 6 times in a row. What you want is no loop at all, but a simple counter that can keep track of how many guesses have been made and when the count reaches the max, the guessing is over.
Other Notes:
You seem to have an excessive amount of input elements and since
this is just a game and you are not actually submitting the data
anywhere, you shouldn't be using submit buttons and adding name
attributes to the form fields.
You should not be using tables for page layout - - that's the job of
CSS.
Don't use .innerHTML when you aren't working with strings that
contain HTML as .innerHTML has security and performance
implications. Use .textContent instead.
Don't use inline HTML event attributes. Do you JavaScript separately
from your HTML.
Don't use self-terminating syntax.
const checkAnswer=document.getElementById("guessing");
const d1= document.getElementById("digit1");
const d2= document.getElementById("digit2");
const guess = document.getElementById("guess");
const rand = document.getElementById("rand");
const result = document.getElementById("correct");
const maxtries=5;
let count = 1;
let answer = null;
d2.addEventListener("blur", function(){
rand.removeAttribute("disabled");
});
rand.addEventListener("click", function(){
console.log(d1.value, d2.value);
answer = Math.floor(Math.random() * (d2.value - d1.value + 1) + d1.value);;
console.log(answer);
});
checkAnswer.addEventListener("click", randomNumber)
function randomNumber() {
if(count < maxtries){
if(guess.value == answer){
result.textContent="Correct";
} else {
result.textContent="Guess " + count + " Not correct";
}
count++; // Increase the counter
} else {
result.textContent="No more tries";
}
}
<div>
Lowest number: <input id="digit1" type="text">
<br><span id="numbers"></span>
</div>
<div>
Highest number: <input id="digit2" type="text">
<br><span id="numbers1"></span>
</div>
<div>
<input id="rand" type="button" value="Generate Random" disabled><br>
</div>
<div>
Enter your number<br>
<input id="guess" type="text"><br>
<input id="guessing" type="button" value="Check Answer"><br>
<span id="correct"></span>
</div>
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.
I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:
var clicks = 0;
function clickME() {
clicks += 1;
if (clicks == 2) {
clicks = 0;
}
document.getElementById("clicks").innerHTML = clicks;
}
<input type="Button" id="bt" />
Considering each button (or more generically each element) is part of the DOM (Document Object Model), each one is an object, so no one makes you unable to use them: you can set the field clicks for each button DOM object:
function clickME(event) {
var btn = event.target;
btn.clicks = ((btn.clicks || 0) + 1) % 2;
window.clicks = (window.clicks || 0) + btn.clicks * 2 - 1;
document.getElementById("clicks").innerText = window.clicks;
}
Checking out your code, I also simplified your logic replacing the if to check zero with the MOD (%) operator. Furthermore I replaced innerHTML with innerText because the number we won't to be rendered as HTML code, but as plain text, although in this case, it doesn't make difference.
Note:
Don't forget to pass the event data object with the onclick attribute in HTML:
<input onclick="clickME(event)" ...>
Check out this fiddle:
https://jsfiddle.net/57js0ps7/2/
You need to maintain a counter per each button individually - use an array to keep track of how many times a button has been clicked. If you don't the clicks var in your code will be two when you select 2 buttons and reset.
On your html:
lets say you have 50 of these
<button type="button" data-clicked="false">1</button>
<button type="button" data-clicked="false">2</button>
and on your javascript
var buttons = document.querySelectorAll('button');
buttons.forEach(function(button) {
button.addEventListener('click', function() {
if (this.dataset.clicked == 'false') {
this.dataset.clicked = 'true';
this.innerHTML = parseInt(this.innerHTML) + 1;
}
else {
this.dataset.clicked = 'false'
this.innerHTML = parseInt(this.innerHTML) - 1;
}
})
});
EDIT: Here is a working fiddle
Since you have this tagged as jQuery here is a solution using jQuery. The solution involves using the data- attribute to hold the click count for each button (input). Not sure why you use inputs instead of buttons, but I kept that the same
It also has a getTotal() function that goes through each element and tallies the click to see how many slots were selected and displays that number for you.
$(document).ready(function() {
$(".btn").on("click", clickME);
});
function clickME() {
var clicks = $(this).data("clicks");
var newClicks = parseInt(clicks) + 1;
if(newClicks > 1){
newClicks = 0;
}
// set the new click count on the element
$(this).data("clicks", newClicks);
setTotal();
}
function setTotal(){
var total = 0;
$(".btn").each(function(imdex, btn) {
var currClicks = parseInt($(btn).data("clicks"));
total += currClicks;
});
$("#clicks").text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Button" class="btn" data-clicks=0 value="0" />
<input type="Button" class="btn" data-clicks=0 value="1" />
<input type="Button" class="btn" data-clicks=0 value="2" />
<input type="Button" class="btn" data-clicks=0 value="3" />
<input type="Button" class="btn" data-clicks=0 value="4" />
<input type="Button" class="btn" data-clicks=0 value="5" />
<input type="Button" class="btn" data-clicks=0 value="6" />
<div>
<p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>
I've got a screen that allows users to add & remove rows which they'll use to input their scores. The input rows gets created based on sample type selected & a pre-configured "template" (eg, going by my picture... I select hearts, and "germs, wholebird" & "Pseudomonas, Crubming" gets added as a default), but they can also append or remove rows as they see fit.
I'd like it so that when a user tabs, it'll only tab through the textboxes, and not the dropdown boxes.
The code
Index
#Html.ActionLink("New Row...", "AddRow", null, new { id = "addItem" })
<div id="overflw" style="height: 260px; width: 885px; overflow: auto; border: 1px solid black">
<div id="editorRows">
#if (Model.Micros != null)
{
foreach (var item in Model.Micros)
{
Html.RenderPartial("MicroRow", item);
}
}
</div>
</div>
<script type="text/javascript">
$(".deleteRow").button({ icons: { primary: "ui-icon-trash" },
text: false
});
</script>
MicroRow
<div class="editorRow" style="padding-left: 5px">
#using (Html.BeginCollectionItem("micros"))
{
ViewData["MicroRow_UniqueID"] = Html.GenerateUniqueID();
#Html.EditorFor(model => model.Lab_T_ID, new { UniqueID = ViewData["MicroRow_UniqueID"] })
#Html.EditorFor(model => model.Lab_SD_ID, new { UniqueID = ViewData["MicroRow_UniqueID"] })
#Html.TextBoxFor(model => model.Result)
<input type="button" class="deleteRow" title="Delete" value="Delete" />
}
</div>
Well, the simplest way I can think of is to hijack your tab key whenever you are within one of your text boxes. I've put up a fiddle here which might give a general idea as to what I meant.
<input type='text' id='n1' data-key='1' />
<input type='text' id='n2' data-key='2' />
<input type='text' id='n5' value = 'Tab skips me'/>
<input type='text' id='n3' data-key='3' />
<input type='text' id='n4' data-key='4' />
$(function(){
$('input[type="text"]').keydown(function(e){
if(e.which === 9){
e.preventDefault();
var self = $(this),
myIndex = parseInt(self.data('key'),10),
nextIndex = myIndex + 1,
nextElement = $('input[data-key="'+ nextIndex +'"]');
nextElement.focus();
}
});
});
Edit - Using TabIndexes
While the piece of code above works as advertised, you may also want to check out using tabindex. I will admit, this is something that I did not know existed. But after reading through comments, decided this was something that may be more suited to your requirement. I've updated a fiddle to show how it works. Check it out
<input type='text' id='n1' tabindex='1' value="I'm first" />
<input type='text' id='n2' tabindex='3' value="I'm third" />
<input type='text' id='n5' value="I'm last"/>
<input type='text' id='n3' tabindex='2' value="I'm second" />
<input type='text' id='n4' tabindex='4' value="I'm fourth" />
Use a hidden feild in the view store the current tab index value.
As you have tagged Jquery here. Add the code for the below in Jquery
Whenever user clicks on add New row then read the tab index hidden feild value and increment it and set it to the newly added textbox
Whenever user clicks on delete decrement the value of index hidden field.
I have a webpage. There is a button called add. When this add button is clicked then 1 text box must be added. This should happen at client side only.
I want to allow the user to add at most 10 text boxes.
How can I achieve it using javascript?
example:
only 1 text box is displayed
user click add >
2 text boxes displayed
user clicks add >
I also wants to provide a button called "remove" by which the user can remove the extra text box
Can anyone provide me a javascript code for this??
Untested, but this should work (assuming an element with the right id exists);
var add_input = function () {
var count = 0;
return function add_input() {
count++;
if (count >= 10) {
return false;
}
var input = document.createElement('input');
input.name = 'generated_input';
document.getElementbyId('inputs_contained').appendChild(input);
}
}();
add_input();
add_input();
add_input();
A solution using the jQuery framework:
<form>
<ul class="addedfields">
<li><input type="text" name="field[]" class="textbox" />
<input type="button" class="removebutton" value="remove"/></li>
</ul>
<input type="button" class="addbutton" value="add"/>
</form>
The jQuery script code:
$(function(){
$(".addbutton").click(){
if(".addedfields").length < 10){
$(".addedfields").append(
'<li><input type="text" name="field[]" class="textbox" />' +
'<input type="button" class="removebutton" value="remove"/></li>'
);
}
}
// live event will automatically be attached to every new remove button
$(".removebutton").live("click",function(){
$(this).parent().remove();
});
});
Note: I did not test the code.
Edit: changed faulty quotation marks
I hope you are using jQuery.
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript"><!--
$(document).ready(function(){
var counter = 2;
$("#add").click(function () {
if(counter==11){
alert("Too many boxes");
return false;
}
$("#textBoxes").html($("#textBoxes").html() + "<div id='d"+counter+"' ><label for='t2'> Textbox "+counter+"</label><input type='textbox' id='t"+counter+"' > </div>\n");
++counter;
});
$("#remove").click(function () {
if(counter==1){
alert("Can u see any boxes");
return false;
}
--counter;
$("#d"+counter).remove();
});
});
// --></script>
</head><body>
<div id='textBoxes'>
<div id='d1' ><label for="t1"> Textbox 1</label><input type='textbox' id='t1' ></div>
</div>
<input type='button' value='add' id='add'>
<input type='button' value='remove' id='remove'>