Javascript JQuery - Hide a button if value is 0, display if not - javascript

I have this:
<input type="button" id="total_items" value="0">
The value is increasing as items added to the site.
What I need is to hide it if the value is 0 and start to displaying as the value is increasing.
I know JQuery has an option to add a css display:none option, but I don't know how. Thank you for all the help!

Try this code below, Just you must call checkValue() function every time number count of objects changed.
var btn = $('#total_items');
$(document).ready(function() {
checkValue();
})
btn.change(function() {
checkValue();
});
function AddNumber(count) {
btn.prop('value', parseInt(btn.attr('value')) + count);
checkValue();
}
function checkValue() {
if (parseInt(btn.prop('value')) === 0)
btn.css("display", "none"); //btn.hide();
else
btn.css("display", ""); //btn.show()
console.log("Current value is:" + btn.prop('value'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="total_items" value="0">
<hr>
<button type="button" onclick="AddNumber(1)">+</button>
<button type="button" onclick="AddNumber(-1)">-</button>

if the element with id total_items is fixed then you can use the css3's attribute selector to make the visibility as hidden and then call the increment logic to make it visible again.
Here is a sample snippet handling the visibility of the total_items based on the value it has:
var btntotal_item = document.getElementById('total_items');
function incrementValue() {
btntotal_item.value++;
}
function decrementValue() {
btntotal_item.value--;
if (btntotal_item.value < 0)
btntotal_item.value = 0;
}
#total_items[value="0"] {
visibility: hidden
}
<input type="button" id="total_items" value="0">
<input type="button" onclick="incrementValue()" value="increment by 1"><input type="button" onclick="decrementValue()" value="decrement by 1">

You can also do this using vanilla javascript =>
if no results are equal to 0 then hideShow button will not show up.
Button press will hide results with value 0.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
.noDisplay {
display: none;
}
</style>
</head>
<body>
<button id="p1" class="noDisplay">Hide-Show</button>
<table style="width:100%">
<tr>
<th>name</th>
<th>result</th>
</tr>
<tr id="0">
<td>Jill</td>
<td class="result">0</td>
</tr>
<tr id="1">
<td>Eve</td>
<td class="result">30</td>
</tr>
<tr id="2">
<td>john</td>
<td class="result">0</td>
</tr>
</table>
<script>
window.addEventListener('load', HideShowBtn);
let z = [];
function HideShowBtn() {
let x;
fields = document.getElementsByClassName('result');
// Hack to convert nodelists to array
fieldsArr = Array.prototype.slice.call(fields);
x = fieldsArr.map(e => {
return parseInt(e.innerText);
});
let y = document.getElementById('p1').classList;
function check(x) {
return x <= 0;
}
x.forEach(e => {
if (e === 0) {
y.remove('noDisplay');
}
});
for (const i in x) {
if (x[i] === 0) {
z.push(x.indexOf(0, i));
}
}
}
document.getElementById('p1').addEventListener('click', () => {
z.forEach(e => {
document.getElementById(e).classList.toggle('noDisplay');
});
});
</script>
</body>
</html>

You can achieve this effect with CSS alone.
If you want the button to disappear, but leave a button-sized space, use:
visibility: hidden;
If you want the button to disappear completely, use:
display: none;
If you want the button to be invisible (and still clickable), use:
opacity: 0;
Working Example:
input[type="button"][value="0"] {
visibility: hidden;
}
<input type="button" id="total_items" value="2">
<input type="button" id="total_items" value="1">
<input type="button" id="total_items" value="0">
<input type="button" id="total_items" value="1">
<input type="button" id="total_items" value="2">

Where you set the value
$("#total_items").val(value).toggle(value>0)

Related

Multiply output by inputs

I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>

Converter boxes, How to make it both output boxes work?

I am doing a project of a converter. When I put a number in the number box, it shows up fine in the box2. But when I try to enter a number in box2, and it won't show the answer in box1. Can anyone help me? I don't know jquery and I am a starter of html and javascript. Hopefully, someone can help me. Thanks
function NumberToSquare(num)
{
var sqrt;
sqrt = Math.sqrt(num);
return sqrt;
}
function SquareToNumber(sqrt)
{
var num;
num = Math.pow(sqrt,2);
return num;
}
<html>
<head>
<title>Program Assignment 5</title>
<script type = text/javascript src = "calculate.js"> </script>
<script type="text/javascript">
function ConvertToSqrt()
//Assumes: Number contains a number
//Results: displays the square root in box2
{
num = parseFloat(document.getElementById('box1').value);
sqrt = NumberToSquare(num);
box2.value=sqrt;
}
function ConvertToNum()
//Assumes: Square contains a number of square root
//Results: displays the number in box1
{
sqrt = parseFloat(document.getElementById('box2').value);
num = SquareToNumber(sqrt);
box1.value=num;
}
</script>
</head>
<body>
<div style="border: solid; width: 300px; background-color: #83CAFF">
<table>
<th></th> <th>Square Root Calculation</th>
<tr>
<th>Enter Number:</th><th><input type="number" id="box1" value=""></th>
<tr>
<th>SquareRoot:</th><th><input type="number" id="box2" value=""></th>
<tr>
<th></th><th><input type="button" value="Calculate" onclick="ConvertToSqrt(); ConvertToNum();">
</table>
</div>
If it helps any, here's a quick sample. It's not pretty but you can take what pieces you need and use it with your own.
<html>
<head>
<title></title>
<script>
function calc(which) {
var newVal;
if (which == "sqrt") {
newVal = parseFloat(document.getElementById("num").value);
newVal = Math.sqrt(newVal);
}
else if (which == "num") {
newVal = parseFloat(document.getElementById("sqrt").value);
newVal = Math.pow(newVal, 2);
}
document.getElementById(which).value = newVal;
}
</script>
</head>
<body>
<div style="width:400px;padding:25px;display:inline-block;line-height:150%;background-color:#83CAFF;font-weight:bold;border:solid 1px black;">
<div style="width:200px;float:left;">
<label>Number:</label>
<br />
<label>SquareRoot:</label>
</div>
<div style="width:200px;float:right;">
<input type="number" id="num"/>
<br />
<input type="number" id="sqrt"/>
</div>
<button type="button" style="width:100%;" onclick="calc('sqrt');">Calc Sqrt</button>
<button type="button" style="width:100%;" onclick="calc('num');">Calc Num</button>
</div>
</body>
</html>

Shading a cell in a table when button is clicked

I have a function that shades every other row in a cell, but can't figure out how to get it so when the button is clicked again, the cells get un-shaded. I'd also like it to not select the first row with the row headers. Any ideas would be appreciated!
$(document).ready(function() {
$('#nbrTxt').focus();
function addItem() {
var value = $('#nbrTxt').val();
var usrName = prompt("Name?");
for (var i = 1; i <= value; i++) {
$('table').append('<tr><td></td><td></td></tr>');
$('table tr:last td:first').html(i);
$('table tr:last td:last').html(usrName);
$(this).focus().select();
};
};
$('#btnGo').click(addItem);
$('#nbrTxt').keydown(function(e) {
if (e.which === 13)
addItem();
})
$(document).on('click', '#shade', function() {
$('tr:even').css('background', '#A0A0A0');
})
$(document).on('click', '#drkLine', function() {
if ($('#nbrTxt').val() % 10 === 0) {
($('#nbrTxt').val()).css('textDecoration', 'line-through');
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<title>JQuery Selector</title>
<style type="text/css">
body {
font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
}
</style>
<script src="jquery-1.11.3.min.js"></script>
<script src="jqueryselector.js"></script>
</head>
<body>
<h1>JQuery Selector</h1>
Enter Number:
<input type="number" name="nbrTxt" id="nbrTxt" />
<input type="button" value="GO" id="btnGo" />
<div id='buttons'>
<input type="button" value="Shade Even Rows" id="shade" />
<input type="button" value="Show Dark Line Every 10 Rows" id="drkLine" />
</div>
<table id="table" width="500" border="1">
<tr>
<td>No. Count</td>
<td>Name</td>
</tr>
</table>
</body>
</html>
Add class shade in your style and use toggleClass() function to add/remove it, check example bellow.
If you don't want to select the first row you can use :not(:first-child) :
$('tr:not(:first-child):even')
Hope this helps.
Snippet
$(document).ready(function() {
$('#nbrTxt').focus();
function addItem() {
var value = $('#nbrTxt').val();
var usrName = prompt("Name?");
$('table>tbody').empty();
for (var i = 1; i <= value; i++) {
$('table').append('<tr><td></td><td></td></tr>');
$('table tr:last td:first').html(i);
$('table tr:last td:last').html(usrName);
$(this).focus().select();
};
};
$('#btnGo').click(addItem);
$('#nbrTxt').keydown(function(e) {
if (e.which === 13)
addItem();
})
$(document).on('click', '#shade', function() {
$('tr:not(:first-child):even').toggleClass('shade');
})
$(document).on('click', '#drkLine', function() {
if ($('#nbrTxt').val() % 10 === 0) {
($('#nbrTxt').val()).css('textDecoration', 'line-through');
}
})
});
tr.shade{
background: #A0A0A0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>JQuery Selector</h1>
Enter Number:
<input type="number" name="nbrTxt" id="nbrTxt" />
<input type="button" value="GO" id="btnGo" />
<div id='buttons'>
<input type="button" value="Shade Even Rows" id="shade" />
<input type="button" value="Show Dark Line Every 10 Rows" id="drkLine" />
</div>
<table id="table" width="500" border="1">
<thead>
<tr>
<td>No. Count</td>
<td>Name</td>
</tr>
</thead>
</table>

check box code not working

<script>
function edit(em) {
var ch = em.value;
var ed = $("td.td" + ch).value;
if ($(ed).is(: checked)) {
$(this).show();
} else {
$(this).hide();
}
}
</script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" value="25" onclick="edit(this)">
<input type="checkbox" value="26" onclick="edit(this)">
<input type="checkbox" value="27" onclick="edit(this)">
<table>
<tr>
<td class="td25" value="25">Edit</td>
<td class="td26" value="26">Edit</td>
<td class="td27" value="27">Edit</td>
</tr>
</table>
</body>
</html>
here is a bug:
if($(ed).is(:checked))...
shoul be:
if($(ed).is(':checked'))...
Following is what you are trying to do.
$('input[type="checkbox"]').click(function() {
var ch = this.value;
if ($(this).is(':checked')) {
$(".td" + ch).hide();
}
else
{
$(".td" + ch).show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" value="25" >
<input type="checkbox" value="26" >
<input type="checkbox" value="27" >
<table>
<tr>
<td class="td25" value="25">Edit25</td>
<td class="td26" value="26">Edit26</td>
<td class="td27" value="27">Edit27</td>
</tr>
</table>
</body>
</html>
This is what I think you're trying to do:
function edit(em) {
var ch = em.value;
var ed = $("td.td" + ch);
if ($(em).is(':checked')) {
ed.show();
} else {
ed.hide();
}
}
If that's what you're trying to achieve, then here are things you weren't doing right:
As #yangguang said, you were missing quotes for checked (':checked')
You wanted to take td not its value.
You were checking whether td (or its value) is checked which
instead you should have done it for the checkbox.
$(this) refers to the checkbox, but you wanted to show/hide the td

Stuck trying to assign JS vars to hidden fields

I've been fighting with this for a couple of days now...need some guidance please.
I have pared down a much bigger form to a "sample" size to demonstrate what I am after.
The area in question is blocked off in a very recognizable area in the calcFees function.
I also tried to get fancy and have the vars self post to the form so they could be seen, but that does not work.
UPDATE: Here is a bit more info as to what I am running into.
//At this point the var regularfee is = 26.5
// (confirmed by console.log(regularfee);)
// I want to assign it to the hidden field with the id="regularfee"
// I have tried both of the following lines:
document.getElementById('regularfee').value=regularfee.value;
// console.log(document.getElementById('regularfee.value')); shows "null"
document.getElementById('regularfee').value=regularfee;
// console.log(document.getElementById('regularfee')); shows "[object HTMLDivElement]"
What am I doing wrong?
END OF UPDATE *****************************
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="multiForm" action="post.php" method="POST" id="app" name="app">
<div id="page1" class="page" style="visibility:visible;">
Name: <input type="text" size="40" name="name1" >
<br><br>
<table border="1" cellpadding="5" width="50%">
<tbody>
<tr>
<td align="center" colspan="3"><strong>Membership Classification</strong></td>
</tr>
<tr><td width="1000">
<input name="paymethod" type="radio" class="pay" id="paypal" value="paypal" />I would like to use PayPal   
<input name="paymethod" type="radio" class="pay" id="check" value="check" />I would like to pay by check
</td>
<td style="width:150px" align="right">Fee
</td>
<td style="width:150px">
</td></tr>
<tr>
<td><input name="memberclass" type="radio" class="membership" id="regular" value="regular"/> Regular Membership</td>
<td align="right"><div id=regularfee></td>
<td><div align="right" id=regselectedfee></td>
</tr>
<tr><td colspan="2" align="right">Total </td>
<td><div align="right" id=total>
</td></tr></tbody>
</table>
<input type="hidden" name="regularfee" id="regularfee" value="">
<input type="hidden" name="regselectedfee" id="regselectedfee" value="">
<input type="hidden" name="total" id="total" value="">
</form>
<br>
<input type="button" id="C1" value="Continue" onClick="showLayer('page2')">
</td></tr>
</table>
</div>
<div id="page2" class="page">
<b>Page 2
<br><br>
<input type="button" id="B1" value="Go Back" onClick="showLayer('page1')">
<input type="submit" name="submit" value="Click to see Vars" />
</div>
</form>
</body>
</html>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script language="JavaScript">
var paypalselected
var checkselected
var regularfee
var memberfee1
var total
$(function () {
function clearForm()
{
paypalselected = "0";
checkselected = "0";
regularfee = 0.0;
memberfee1 = 0.0;
total = 0.0;
$("#regselectedfee").text(memberfee1.toFixed(2));
$("#total").text(total.toFixed(2));
// clear all radio buttons
$("#regular").prop("checked", false );
}
function calcFees()
{
total = (memberfee1);
$("#total").text(total.toFixed(2));
// **********************************************************************************
// Here is where I want to plug in the 3 JS vars to the hidden fields
// regularfee, regselectedfee, total
// Here is what I've tried:
// vars are not getting plugged in
// If possible, I would like the vars to be plugged in dynamically
// just as the form is updateddynamically when user selects buttons
document.getElementById('regularfee').value=regularfee;
document.getElementById('regselectedfee').value=regselectedfee;
document.getElementById('total').value=total;
// **********************************************************************************
}
function selectPayment()
{
$(".pay").change(function () {
clearForm();
if ($("#paypal").prop("checked")) {
regularfee = 26.50;
$("#regularfee").text(regularfee.toFixed(2));
paypalselected = "1";
checkselected = "0";
}
if ($("#check").prop("checked")) {
regularfee = 25.0;
$("#regularfee").text(regularfee.toFixed(2));
checkselected = "1";
paypalselected = "0";
}
});
}
clearForm();
selectPayment();
//start of membership button selection
$(".membership").change(function () {
if (paypalselected == "1"){
if ($("#regular").prop("checked")) {
memberfee1 = 26.5;
$("#regselectedfee").text(memberfee1.toFixed(2));
calcFees();
}
} //end of paypalselected test
if (checkselected == "1"){
if ($("#regular").prop("checked")) {
memberfee1 = 25.0;
$("#regselectedfee").text(memberfee1.toFixed(2));
calcFees();
}
} //end of checkselected test
}); //end of $(".membership").change(function () {
});
//end of main function
var currentLayer = 'page1';
function showLayer(lyr){
hideLayer(currentLayer);
document.getElementById(lyr).style.visibility = 'visible';
currentLayer = lyr;
window.scrollTo(0,0);
}
function hideLayer(lyr){
document.getElementById(lyr).style.visibility = 'hidden';
}
</script>
<style>
body{
font: 10pt sans-serif;
}
.page{
position: absolute;
top: 10;
left: 100;
visibility: hidden;
}
p.small
{
line-height: 5px;
}
p.smalltext12
{
font-size:12px
}
</style>
You have 2 elements #total. Only the first is given a value:
document.getElementById('total').value = total;
Same for the others.
IDs must be unique to be useful.

Categories

Resources