Please.. i need a help with this thing..
I wanna use a variable ID in HTML, to call a function in javascript page.
Example:
html
(MINUS BUTTON DONT WORK)
<button class="minus-button quantity-button button" type="button" name="subtract" onclick="javascript: subtractDiv2(document.getElementById('<ccom:field id='Code' />'));" value="-"> </button>
(THIS INPUT QUANTITY WORKS NORMAL)
<input class="quantity-input" value="<ccom:field id="Qtd"/>" maxlength="3" id='<ccom:field id="Code" />' name="div2" onkeypress="return somenteNumerico(event);"/>
(PLUS BUTTON WORKS NORMAL)
<button class="plus-button quantity-button button" type="button" name="add" onclick="javascript:document.getElementById('<ccom:field id='Code' />').value++;" value="+"></button>
javapage
function subtractDiv2(){
if(value - 1 < 0)
return;
else
value--;
};
You're not using the argument to the function. It should be:
function subtractDiv2(div) {
var value = parseInt(div.value, 10);
if (value < 1) {
return;
} else {
div.value = value - 1;
}
}
Related
I am working on a web store which offers 2 pre-assigned options (buy two for XX and buy 3 for XY). I also added a normal - 0 + system whith which the customer can select a different number of products.
I wrote a little code which works fine for +- or 2,3 alone, but if i wanna decrease a number added by 2,3 buttons, it doesn't go from 3 to 2 but to 0 or -1.
So, i want to be able to select pre-defined option 2 or 3 but i also want it to be editable by +- buttons.
Any suggestions?
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="0"></input>
<button class="plus" onclick="buttonClicDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
i++;
document.getElementById('gumb2').value = i;
if (i <= 0) {
i = 0;
display(i);
}
}
var i = 0;
function buttonClickDOWN() {
i--;
document.getElementById('gumb2').value = i;
if (i <= 0) {
i = 0;
display(i);
}
}
</script>
As I already mention in the comment, you have a typo in buttonClicDOWN .......missing k. You directly increment/decrement the value of the element. Please see the modified functions:
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>
I'd have this added as a comment, but was not able to for missing rep. So an answer:
In simple terms: you are not updating your global variable i when pressing the 2 or 3 button, so when you in/decrease i and assign it to the value property, you do override the old value.
I would recommend to drop the i (global) variable and just to work with the value property, e.g.
function buttonClickDOWN() {
var elm = document.getElementById('gumb2');
if (elm.value > 0)
elm.value--;
else
elm.value = 0;
}
P.S.: as you are using a text type input, you might also want to consider non-numbers the user might have entered.
Why not simply use input type="number"?
<button class="gumb_shop2" onclick="gumb2.value=2">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="gumb2.value=3">3 for 8,99 €</button>
<input type="number" id="gumb2" value="1" step="1" min="1" />
<input type="button" id="order" value="ORDER NOW" />
Here's a simple example that that meets your specs:
<button onclick="setAbs(event)" data-val="2">2 for 10,99 €</button>
<button onclick="setAbs(event)" data-val="3">3 for 8,99 €</button><br/><br/>
<button onclick="down()">-</button>
<input size="2" id="counter" value="0" />
<button onclick="up()">+</button><br/><br/>
<input type="submit" value="Submit" />
<script>
let counter = document.getElementById("counter");
function setAbs(event){
counter.value = event.target.dataset.val;
}
function up(){
counter.value = parseInt(counter.value) + 1;
}
function down(){
if(counter.value > 0){
counter.value = parseInt(counter.value) - 1;
}
}
</script>
this is the answer i was looking for.
Thank you #Mamun for quick response.
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>
I want to be able to increment and also decrement a value (5) and I would like to cover this with one function (I know how to do it with two).
Unfortunately I am not able to get it done and can't figure out what is wrong.
Here is my code:
HTML:
<form>
<button type="button" value="minus" onclick="updateAmount();">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount();">
+
</button>
</form>
JS:
var num = parseInt(document.getElementById('number');
var btn = document.querySelector('button');
btn.addEventListener('click', updateAmount);
function updateAmount(){
btn.value === "minus" ? num-- : num++;
document.getElementById('number').value = num;
}
Also at JSfiddle
I would prefer a vanilla JS solution if possible, but any suggestion is welcome :)
Thanks!
The minimal-changes to your approach is to pass an argument to the function:
function updateAmount(value) {
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(-1);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(1);">
+
</button>
</form>
Or use your value attribute and pass this into the function:
function updateAmount(btn) {
var value = btn.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>
That latter approach combines nicely with modern event handling:
// Scoping function so our `updateAmount` isn't global
(function() {
document.querySelector("button[value=minus]").addEventListener("click", updateAmount);
document.querySelector("button[value=plus]").addEventListener("click", updateAmount);
function updateAmount() {
var value = this.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
})();
<form>
<button type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus">
+
</button>
</form>
You could hand over the action as a parameter
<form>
<button type="button" value="minus" onclick="updateAmount('minus');">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount('plus');">
+
</button>
</form>
and then
function updateAmount(action) {
var num = parseInt(document.getElementById("number").innerHTML, 10);
switch(action) {
case 'minus':
num--;
break;
case 'plus':
num++;
break;
}
document.getElementById("number").innerHTML = num;
}
You can try this ...
<html>
<form>
<button type="button" value="minus" onclick="updateAmount(this.value);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this.value);">
+
</button>
</form>
<script>
function updateAmount(value){
var num = parseInt(document.getElementById('number').innerHTML);
value=='plus'?num++:num--;
document.getElementById('number').innerHTML = num;
}
</script>
</html>
You were close, as you have multiple elements use document.querySelectorAll() with valid selector to get there reference and bind event handlers.
As you are using <SPAN> element, it doesn't have value property, need to use textContent property.
var btns = document.querySelectorAll('button');
btns.forEach(function(btn) {
btn.addEventListener('click', updateAmount);
});
function updateAmount() {
var num = parseInt(document.getElementById('number').textContent.trim(), 10);
this.value === "minus" ? num-- : num++;
document.getElementById('number').textContent = num;
}
<button type="button" value="minus">-</button>
<span id="number">5</span>
<button type="button" value="plus">+</button>
Note: Get rid of ugly inline click handlers.
simply use like this updateAmount(this)
function updateAmount(that) {
var number = document.getElementById('number');
var num = parseInt(number.innerHTML);
num = (that.value == "minus") ? --num : ++num;
number.innerHTML = num;
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>
var minusBtn = document.querySelector('#minus');
var plusBtn = document.querySelector('#plus');
minusBtn.addEventListener('click', updateAmount('minus'));
plusBtn.addEventListener('click', updateAmount('plus'));
function updateAmount(action) {
return function() {
var numberElem = document.getElementById('number');
var number = numberElem.innerText;
number = parseInt(number, 10);
if (action === 'minus') {
number--;
} else if(action === 'plus') {
number++;
} else {
throw new Error('invalid operator');
}
numberElem.innerText = number;
};
}
<form>
<button id = "minus" type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button id = "plus" type="button" value="plus">
+
</button>
</form>
this is a good example for curry function, you can currify your updateAmount to accept action as a part of argument
Your code has just two small flaw, rest is perfect.
Firstly Your variable num is evaluating to NaN.
Secondly you should use textContent instead of value .
I am sharing correct way to evaluate num and then it will work.
var el =document.getElementById('number')
var num = parseInt(el.textContent);
Again, while updating
document.getElementById('number').textContent = num
Hope it helped.
I would like to keep count every time the user clicks a the add row button. Here's the code I have that's not working.
function add_more_row() {
var rows_count = ParseInt(document.getElementById("rows_count").value);
rows_count += 1;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
What am I doing wrong?
Your code only gets the value and increases it, does not assign the value to the input field. Add this line after the increment statement:
document.getElementById("rows_count").value = rows_count;
Also it's parseInt() with lowercase p not ParseInt().
function add_more_row() {
var inputRow = document.getElementById("rows_count"),
rows_count = parseInt(inputRow.value);
rows_count += 1;
inputRow.value = rows_count;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
function add_more_row() {
var rows_count = parseInt(document.getElementById("rows_count").value);
rows_count += 1;
document.getElementById("rows_count").value= rows_count;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
It is because you declare the variable inside the function.
So, the variable does not increase.
var rows_count=ParseInt(document.getElementById("rows_count").value);
function add_more_row()
{
rows_count += 1;
}
I'm creating a small survey in the creation of question i have the question text and the question choice .
By default i have three text box to fill if i want to add another text box i click on the add button or in the last text box to add another under him but the event is stuck in the same text box i want only the last text box to handle the event but i don't know want is wrong in my code:
JQuery:
<script>
$(document).ready(function () {
$('.dropdown_selector').change(function () {
var option = $(this).find('option:selected').val();
if (option == "Radio Button") {
$(".QuestionOption").html('<p>Q1:<input id="Text1" type="text" /></p> <p> Answer Choices:</p> <p><input id="Text2" type="text" /></p><p><input id="Text3" type="text" /></p> <p class ="last4"><input id="Text4" type="text" /></p>');
$(".ButtonField").html('<p><input id="Button1" type="button" value="Save" /> <input id="Button2" type="button" value="Cancel" /></p><p><input id="Checkbox1" type="checkbox" />Add a Common Field</p>');
}
else
if (option == "Check Box") {
$(".QuestionOption").html('<p>Q1:<input id="Text1" type="text" /></p> <p> Answer Choices:</p> <p><input id="Text2" type="text" /></p><p><input id="Text3" type="text" /></p> <p class ="last4"><input id="Text4" type="text" /></p>');
$(".ButtonField").html('<p><input id="Button1" type="button" value="Save" /> <input id="Button2" type="button" value="Cancel" /></p><p><input id="Checkbox1" type="checkbox" />Add a Common Field</p>');
}
});
});
</script>
<script>
$(document).ready(function () {
var counter = 5;
var nb = counter - 1;
$(".QuestionOption").on("click", "p.last"+nb, function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('p')).attr("class", 'last' + counter);
newTextBoxDiv.after().html('<input type="text" id="Text' + counter + '" value="" > ');
newTextBoxDiv.appendTo(".QuestionOption");
counter++;
nb = counter - 1;
});
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('p')).attr("class", 'last' + counter);
newTextBoxDiv.after().html('<input type="text" id="Text' + counter + '" value="" > ');
newTextBoxDiv.appendTo(".QuestionOption");
counter++;
});
$("#removeButton").click(function () {
if (counter == 3) {
alert("No more textbox to remove");
return false;
}
counter--;
$(".last" + counter).remove();
$("#Text"+counter).remove();
});
});
Html code:
<asp:DropDownList ID="dropdown_selector" runat="server" CssClass="dropdown_selector">
<asp:ListItem>Radio Button</asp:ListItem>
<asp:ListItem>Check Box</asp:ListItem>
</asp:DropDownList>
<input id="addButton" type="button" value="Add" />
<input id="removeButton" type="button" value="Remove" />
<div id="QuestionOption" runat="server" class="QuestionOption" ></div>
<div id="ButtonField" runat="server" class="ButtonField" ></div>
Image of the question and choice
$(".QuestionOption").on only gets run once, when the page loads. It adds a listener to the element(s) matching p.last"+nb using whatever value nb has at startup (4, by the looks of it). The event is never attached to any subsequently created elements because they don't match p.last4. You need to keep switching the events on for each textbox as it's created, and off for the one just clicked.
var counter = 5; //moved these outside document.ready
var nb = counter - 1;
$(document).ready(function () {
$(".QuestionOption").on("click", "p.last"+nb, newTextBox); //run newTextBox function when this is triggered
//...
}); //end of document.ready function
//re-usable function to create new textbox
function newTextBox()
{
if (counter > 10) {
alert("Only 10 textboxes allowed"); //N.B. corrected grammar from "allow" to "allowed"
return false;
}
var newTextBoxDiv = $("<p/>").attr("class", 'last' + counter);
newTextBoxDiv.after().html('<input type="text" id="Text' + counter + '" value="" > ');
newTextBoxDiv.appendTo(".QuestionOption");
$(".QuestionOption").off("click", "p.last"+nb, newTextBox); //remove event handler for the current textbox (which has just been clicked)
counter++; //increment the counter
nb = counter - 1;
$(".QuestionOption").on("click", "p.last"+nb, newTextBox); //run newTextBox function for the newly added textbox
}
I have simple plus and minus button on either side of input field as in the code below
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%" onclick="subst()" />
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="<?php echo set_value('noOfRoom'); ?>" name="noOfRoom" />
<input type="button" value="+" id="adds" onclick="add()" class="btn btn-default" />
with aim to add or subtract rooms while adding rooms and the jquery functions as
function add() {
var a = $("#noOfRoom").val();
a++;
if (a => 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
but the following problems are shown
when i click on subtract (-) button at the initial phase -1 is shown in input box, where by default the subtract (-) button should be disabled to make rooms number negative.
Each time when I click on PLUS or MINUS buttons the numbers are added or subtracted by 2. How could I solve it?
Update add a fiddle https://fiddle.jshell.net/n7ug52dr/
Each time you click will only add and sub by 1, and it never show the -1
You can edit code like this:
function add() {
var a = $("#noOfRoom").val();
a++;
if (a && a >= 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
// this is wrong part
if (b && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
Moving comments to answer as no-one took onboard the suggestions:
I suggest not using inline onclick= handlers with jQuery. They separate the event handler from the event code for no reason and don't allow for the extra features of jQuery event handlers.
Use prop and not attr for DOM element properties (like disabled). This has the extra advantage of taking a boolean value.
You can then simply use !a to control the disabled state (as you are only checking for 0).
As a good habit always select DOM elements once and save the selector.
e.g.
$('#adds').click(function add() {
var $rooms = $("#noOfRoom");
var a = $rooms.val();
a++;
$("#subs").prop("disabled", !a);
$rooms.val(a);
});
// Set initial disabled state
$("#subs").prop("disabled", !$("#noOfRoom").val());
$('#subs').click(function subst() {
var $rooms = $("#noOfRoom");
var b = $rooms.val();
if (b >= 1) {
b--;
$rooms.val(b);
}
else {
$("#subs").prop("disabled", true);
}
});
JSFiddle: https://jsfiddle.net/k7nyv84b/4/
Here you go, champ! Made your code a little cleaner as well
See the working example below
$(function(){
$('#adds').on('click',add);
$('#subs').on('click',remove);
});
function add(){
var input = $('#noOfRoom'),
value = input.val();
input.val(++value);
if(value > 0){
$('#subs').removeAttr('disabled');
}
}
function remove(){
var input = $('#noOfRoom'),
value = input.val();
if(value > 0){
input.val(--value);
}else{
$('#subs').attr('disabled','disabled');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%"/>
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="0" name="noOfRoom" />
<input type="button" value="+" id="adds" class="btn btn-default" />
take a look at this solution
<input type="button" value="-" id="subs" onclick="subst()" disabled>
<input type="text" id="noOfRoom">
<input type="button" value="+" id="adds" onclick="add()">
function add() {
var a = $("#noOfRoom").val();
a++;
if (a >= 1) {
$("#subs").removeAttr("disabled");
}
alert(a);
$("#noOfRoom").val(a);
}
function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
b--;
alert(b);
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
//alert('works well');
}
The simplest way is to use DOM to navigate through elements and get its current value and then increase/decrease them.
I extended the code to make sure when minus button is clicked value isn't reduce below zero.
<input type="button" value="-" class="qtyminus" field="quantity">
<input type="number" class="input-lg" id="quantity" name="quantity" value="1" min="1" style="padding:0px;height:30px;">
<input type="button" value="+" class="qtyplus" field="quantity">
<input type="submit" name="add" id="add" class="btn btn-large btn-border btn-dark" value="GET IT NOW" style="opacity: 1;">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
// This button will increment the value
$('.qtyplus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>
<button onClick="myfun()">+</button>
<!--<button onClick="myfun()" id="pluse">+</button>-->
<input type="text" id="pluse" >
<button onClick="myfun1()">_</button>
var a = 0;
function myfun(){
a++;
document.getElementById('pluse').value = a;
//document.getElementById('pluse').innerHTML = a;
}
function myfun1(){
a--;
document.getElementById('pluse').value = a;
}