I'm having trouble in doing a javascript that will do the following:
Increase/decrease number inside textbox when image clicked.
setting a limit for that textbox (not below zero, not above x)
please know i have many text boxes in the same page, so how can this issue be fixed?
You don't need to (and shouldn't) set ids for each and every image and input field. You will need to set name attributes for each input field though (so your server code can tell them apart - but not for JS).
If the "add" section for each row looks like:
<div>
<img src='minus.png' onclick="increment(this.parentNode.getElementsByTagName('input')[0]);" />
<input type='text' name='product_1010101011' />
<img src='plus.png' onclick="decrement(this.parentNode.getElementsByTagName('input')[0]);" />
</div>
use this javascript:
function increment(myInput) {
// use Mike Samuel's code here
myInput.value = (+myInput.value + 1) || 0;
}
function decrement(myInput) {
// use Mike Samuel's code here
myInput.value = (myInput.value - 1) || 0;
}
I think this should get you going:
<form>
<input type="button" id="minus" value="-"
onClick="textb.value = (textb.value-1)">
<input type="text" id="textb" name="name" value="1" />
<input type="button" value="+"
onClick="textb.value = (+textb.value+1)">
</form>
Live example here
To increment
myInput.value = (+myInput.value + 1) || 0;
To decrement
myInput.value = (myInput.value - 1) || 0;
The || 0 will reset any value that doesn't parse as an integer to a default value, 0.
Related
First of all, please help me figure this purely in JavaScript. No jQuery or any plugins. I'm trying to code this to work in Cordova/PhoneGap. I'm teaching myself JavaScript at the same time as I'm playing with Cordova/PhoneGap so please be gentle.
I've got a textbox with buttons on either side, right for adding 1 to the textbox value (+ on it) and left for minusing 1 from the text box (- on it). My purpose is to have the page/app load for the first time showing a 0 value in the text box. As soon as someone presses the + button, the textbox should increment from 0 to 1 and by a further 1 with every click of the +. If the app is closed and re-opened, it should remember the last number that was in the textbox before the app was closed.
It works in browser testing, it causes PhoneGap's iPhone app to no longer recognize PhoneGap gestures of resetting the app and such, pressing the +/- button increments/decrements the textbox too slowly, and it can go negative despite setting min="0". What am I doing wrong? (I know localStorage can't be done in the code snippet due to sandboxing so if you'd rather I put up a JSFiddle or something, just tell me what to do.)
window.onload = function(){
var CapsNum = localStorage.getItem("CapsNum");
if(CapsNum == null) {
CapsNum = "0";
} else {
document.getElementById("caps").value = CapsNum;
}}
window.onbeforeunload = function(){
localStorage.setItem("CapsNum", document.getElementById("caps").value);
}
function PlusCaps(){
localStorage.setItem("CapsNum",document.getElementById("caps").value++);
}
function MinusCaps(){
localStorage.setItem("CapsNum",document.getElementById("caps").value--);
}
<input type="button" id="plus" class="button" value="+" style="margin-left:10px" onclick="MinusCaps()" />
<input type="tel" id="caps" maxlength="3" size="3" min="0" max="999" pattern="[0-9]" value="0" />
<input type="button" id="minus" class="button" value="-" style="margin-right:10px" onclick="PlusCaps()" />
So it seems like you are changing and persisting the value into local storage. This won't update the value on the page. I create a small function by modifying your example that can update the state in localstorage and it updates the value in the textbox at the same time.
window.onload = function() {
//var CapsNum = localStorage.getItem("CapsNum");
if (CapsNum == null) {
CapsNum = "0";
} else {
document.getElementById("caps").value = CapsNum;
}
}
window.onbeforeunload = function() {
localStorage.setItem("CapsNum", document.getElementById("caps").value);
}
function PlusCaps() {
var nextValue = parseInt(document.getElementById("caps").value) + 1;
setNextValue(nextValue);
}
function MinusCaps() {
var nextValue = parseInt(document.getElementById("caps").value) - 1;
setNextValue(nextValue);
}
function setNextValue(nextValue) {
//localStorage.setItem("CapsNum", nextValue);
document.getElementById("caps").value = nextValue;
}
<input type="button" id="plus" class="button" value="+" style="margin-left:10px" onclick="PlusCaps()" />
<input type="tel" id="caps" maxlength="3" size="3" min="0" max="999" pattern="[0-9]" value="0" />
<input type="button" id="minus" class="button" value="-" style="margin-right:10px" onclick="MinusCaps()" />
I am trying to create a page that lets the user enter three numbers, and have the max and min values printed below from the input. I've used both the Math.max/min functions and also tried an if statement but When I click submit nothing shows up. Some insight would be greatly appreciated, thanks!
function max() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var z = document.getElementById("num3").value;
var maximum = Math.max(parseInt(x), parseInt(y), parseInt(z));
document.getElementById("max").innerHTML= maximum;
}
function min() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
var z = parseInt(document.getElementById("num3").value);
document.getElementById("min").innerHTML = Math.min(x,y,z);
}
And here is my html
<p>Enter First Number:</p>
<input type="text" name = "number1" id="num1"><br>
<p>Enter Second Number</p>
<input type="text" name = "number2" id="num2"><br>
<p>Enter third number</p>
<input type="text" name = "number3" id="num3"><br>
<input type="submit" value="Submit" onclick="max(); min(); "><br />
<p>Max =</p><p id ="max"></p><br />
<p>Min =</p><p id ="min"></p><br />
replace <input type="submit"/> to <button type="submit" value="" onclick="minmax();">Submit</button>
and add JS function:
function minmax() {
min();
max();
}
Your problem seems related to how you are attaching your event.
It works OK when I use:
document.querySelector( '[type="submit"]' ).addEventListener( 'click', function() {
max();
min();
}, false );
http://jsfiddle.net/yemxrmqq/
You just need to change the tag related to the button, instead of:
<input type="submit" value="Submit" onclick="max(); min(); "><br />
just put:
<button type="submit" value="Submit" onclick="max(); min()">Click</button><br />
None of the answers here tell you why your code didn't work.
Identifiers in inline listeners are first resolved as properties of the element on which they are placed. Input elements have a default max attribute, so within an inline listener, the identifier max will reference the input's max property. Hence in any document:
<input onclick="console.log(max)">
shows '' (i.e. empty string).
So you can either change the names of the functions to something more meaningful, or change the context from which they are called so that the identifiers aren't resolved on the element, and the OP code works. e.g.
<input type="submit" value="Submit" onclick="callBoth()">
and
function callBoth() {
max();
min();
}
Incidentally, an input type submit outside a form is just a button, so you should use:
<input type="button" ...>
i am looking for solution i want to disable button if value of input box matched.
i got two buttons and an input box
<button type="button" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button>
<button type="button" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>
<input type="text" id="count" value="0"/>
i want to disable buttonpassvalue if input box (count) is zero and disable second button buttonpassvalue1 if value of (count) is 5
thanks for your help.
Made a JSFiddle for you!
http://jsfiddle.net/fRHm9/
Basically, you make a change event listener and, when it changes, grab the element whose id is equal to the input's value. I assigned the buttons ids of -1 and 1. Check out the fiddle.
Basically, you could achieve this quite easily using plain javascript. But, when using javascript in order to be able to find a specific element efficiently you will need to specify an id for that element. So I would recommend you to change your buttons so that they use id attributes as follows...
<button type="button" id="buttonpassvalue" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button>
<button type="button" id="buttonpassvalue1" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>
<input type="text" id="count" value=""/>
Note, that I added id attributes to each buttons. Now, you can run attach this javascript function to the keyup event of the text input element...
var input = document.getElementById('count');
input.onkeyup = function(){
var buttonpassvalue = document.getElementById('buttonpassvalue');
var buttonpassvalue1 = document.getElementById('buttonpassvalue1');
var val = this.value.trim();
if(val == "0"){
buttonpassvalue.setAttribute("disabled","disabled");
buttonpassvalue1.removeAttribute("disabled");
}
else if(val == "5"){
buttonpassvalue.removeAttribute("disabled");
buttonpassvalue1.setAttribute("disabled","disabled");
}
else{
buttonpassvalue.removeAttribute("disabled");
buttonpassvalue1.removeAttribute("disabled");
}
};
I have created a JS Fiddler where you can see a quick demo. Also, note that this solution is using plain javascript.
I'm currently using a YUI gadget. I also do have a Javascript function to validate the output that comes from the div that YUI draws for me:
Event.on("addGadgetUrl", "click", function(){
var url = Dom.get("gadget_url").value; /* line x ------>*/
if (url == "") {
error.innerHTML = "<p> error" /></p>";
} else {
/* line y ---> */
/* I need to add some code in here to set the value of "gadget_url" by "" */
}
}, null, true);
Here is my div:
<div>
<p>URL</p>
<input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input"/>
<input type="button" id="addGadgetUrl" value="add gadget"/>
<br>
<span id="error"></span>
</div>
As you can see my question is, how can I set the value of gadget_url to be ""?
Javascript
document.getElementById('gadget_url').value = '';
jQuery
$("#gadget_url").val("");
YUI
Dom.get("gadget_url").set("value","");
document.getElementById('gadget_url').value = '';
The following works in MVC5:
document.getElementById('theID').value = 'new value';
Depending on the usecase it makes a difference whether you use javascript (element.value = x) or jQuery $(element).val(x);
When x is undefined jQuery results in an empty String whereas javascript results in "undefined" as a String.
document.getElementById('gadget_url').value = 'your value';
I'm not using YUI, but my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).
Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.
Shortest
gadget_url.value=''
addGadgetUrl.addEventListener('click', () => {
gadget_url.value = '';
});
<div>
<p>URL</p>
<input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input" value="some value" />
<input type="button" id="addGadgetUrl" value="add gadget" />
<br>
<span id="error"></span>
</div>
This is the shortest working solution (JSFiddle).
<html>
<head>
<title>Tip Calculator</title>
<script type="text/javascript"><!--
function calculateBill(){
var check = document.getElementById("check").value;
/* I try to get the value selected */
var tipPercent = document.getElementById("tipPercent").value;
/* But it always returns the value 15 */
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
--></script>
</head>
<body>
<h1 style="text-align:center">Tip Calculator</h1>
<form id="f1" name="f1">
Average Service: 15%
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<br />
Excellent Service: 20%
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
<br /><br />
<label>Check Amount</label>
<input type="text" id="check" size="10" />
<input type="button" onclick="calculateBill()" value="Calculate" />
</form>
<br />
Total Bill: <p id="bill"></p>
</body>
</html>
I try to get the value selected with document.getElementById("tipPercent").value, but it always returns the value 15.
In HTML, Ids are unique. Try changing the id attributes to tipPercent1, tipPercent2, etc.
Both radio buttons have the same ID - this is incorrect in HTML, as IDs should be unique. The consequence is that document.getElementById cannot be used.
Try document.getElementsByName and loop through the resulting array to find out which one is checked and what its value is.
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
First of all, id's are required to be unique identifiers, so giving two elements the same id will make problems. document.getElementById("tipPercent") after all tries to get one element, so which of those two different input elements should it return?
Second, you can only check if a radio input is checked or not, so you will need to loop through all those inpud fields and check which one is checked to get the current value.
You have two equal ids "tipPercent". getElementById returns only one first result
You should use different ids for each radio. Try something like follows:
<script type="text/javascript">
//a variable that will hold the index number of the selected radio button
for (i=0;i<document.f1.tipPercent.length;i++){
if (document.document.f1.tipPercent[i].checked==true)
var tipPercent= document.f1.tipPercent[i].value;
}
</script>
You may want to change the calculateBill() function with the following:
function calculateBill() {
var tipPercent = 0;
var check = document.getElementById("check").value;
var radioElements = document.getElementsByName("tipPercent");
for (var i = 0; i < radioElements.length; i++) {
if (radioElements[i].checked)
tipPercent = parseInt(radioElements[i].value);
}
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
Note the use of document.getElementsByName(), as Oded suggested in another answer.
You should also remove the id attribute from your radio buttions:
<input type="radio" name="tipPercent" value="15" />
<input type="radio" name="tipPercent" value="20" />
The following is a screenshot showing that the above function works fine with the 20% radio button:
How can I read the value of a radio button in JavaScript? http://img695.imageshack.us/img695/6214/tipcalc.png
The id of an element has to be unique, so you can't have two elements with the same id.
When you try to get all radio buttons as a single element, you will get one of them. Which one you get is entirely up to how the browser choose to handle the incorrect id's that you have set. You could get either of the elements, or null, depending on the implementation. In this case you happen to use a browser that gets the first element.
Give the elements their own id:
Average Sevice: 15%<input type="radio" id="tipPercent15" name="tipPercent" value="15" />
<br />
Excellent Sevice: 20%<input type="radio" id="tipPercent20" name="tipPercent" value="20" />
Getting the value attribute from the element will only get the value that you have specified for each of them. Instead you used the checked attribute:
var tipPercent;
if (document.getElementById("tipPercent15").checked) tipPercent = 15;
if (document.getElementById("tipPercent20").checked) tipPercent = 20;