Disable button only when text input is 0 - javascript

I have the following code:
var total = document.getElementById('total--input');
document.getElementById('btn-increment-total').addEventListener('click', function() {
if (total.value > 1) {
console.log('enabled');
document.getElementById('btn-decrement-total').enabled = true;
}
total.value++;
});
document.getElementById('btn-decrement-total').addEventListener('click', function() {
if (total.value == 0) {
console.log('disabled');
document.getElementById('btn-decrement-total').disabled = true;
}
total.value--;
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">
The 'decrement' button seems to work and will disable itself when conditions are met.
But the 'increment' button doesn't seem to re-enable the 'decrement' button. Anyone knows why and how to solve this?

There's no enabled attribute, you should use disable="false" :
document.getElementById('btn-decrement-total').disabled = false;
Instead of:
document.getElementById('btn-decrement-total').enabled = true;
_______________________________________________^^^^^^^
Working sample:
var total = document.getElementById('total--input');
document.getElementById('btn-increment-total').addEventListener('click', function() {
total.value++;
if (total.value > 0) {
console.log('enabled');
document.getElementById('btn-decrement-total').disabled = false;
}
});
document.getElementById('btn-decrement-total').addEventListener('click', function() {
total.value--;
if (total.value == 0) {
console.log('disabled');
document.getElementById('btn-decrement-total').disabled = true;
}
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">

enabled isn't a valid attribute, use disabled = false instead

You need to assign the input in an var/let or const.
try this way:
const total = document.querySelector("#total--input");

I had to add an return statement and change some lines of code but this should work.
const disableBtn = function (id, mode) {
document.getElementById(id).disabled = mode;
};
document.getElementById('btn-increment-total').addEventListener('click', function () {
let total = document.getElementById('total--input');
if (total.value >= 0) {
disableBtn('btn-decrement-total', false);
}
total.value++;
});
document.getElementById('btn-decrement-total').addEventListener('click', function () {
var total = document.getElementById('total--input');
total.value--;
if (total.value <= 0) {
disableBtn('btn-decrement-total', true);
return
}
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">

Try to parse the value from the input element to integer before comparing values...
var n1 = Number(document.getElementById('input_element').value).
Then you can check if it meets the condition

Related

How will i prevent duplication of value and empty value

How can I prevent duplicate values being added to a combobox? I also need to prevent the space value. This is my code but its not working.
An entry is entered the first time input but the second time I enter input its alerting me that I have entered a duplicate value even when I enter different values.
Please see this jsFiddle https://jsfiddle.net/adLxoakv/
<HTML>
<HEAD>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
Selected: <input type="text" name="selected" id="selected"/>
IMEI Selected: <input type="text" name="imei" id="imei"/>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
$("#txtCombo").on("keydown", function (e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function(){
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function () {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if (combo.length) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
</script>
To find the duplicate you can use following function(using jQuery)
function isDuplicate(value,text){
/*Get text of the option identified by given value form the combobox and then check if its text matches the given text*/
if($('#combo select option[value="' + value + '"]').text() == text)
return true;
else
return false;
}
Update:
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
var value = textb.value.trim();
option.text = value;
option.value = value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if ($('#combo option[value="' + value + '"]').text() == value ) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}

Basic Javascript onclick

here's my code, brand new to coding trying to get the box "points" to return the sum of pointSum if "Ben" is typed into the box "winner". Just trying to work on some basics with this project. Attempting to make a bracket of sorts
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
if (winnerOne = true){
pointSum+=firstRound
} else if (winnerTwo = true){
pointSum+=secondRound
} else if (winnerThree = true){
pointSum+=thirdRound
} else if (winnerFour = true){
pointSum+=fourthRound
} else if (winnerFive = true){
pointSum+=fifthRound
} else if (winnerSix = true){
pointSum+=finalRound
else
function tally() {if document.getElementById('winner') == "Ben" { winnerOne = true;
}
pointSum=document.getElementById("points").value;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
</body>
</html>
UPDATE***** new code, getting better, not returning console errors but still not getting anything in the "points" box upon clicking tally
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne == true;
}
pointSum = document.getElementById("points").value;
}
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<div class="updatePoints">
</div>
</body>
</html>
Your code has a few mistakes, lets change it a little bit!
First, you need to access 'value' atribbute of your winner element in your if statement, and surround all the statement in parenthesis
function tally() {
if (document.getElementById('winner').value == "Ben"){
winnerOne = true;
}
pointSum = document.getElementById("points").value;
}
Second, you use '==' to make comparison, you are using '=', it means that you are assign true to variables, and you're forgetting to put ';' at the end of lines! change this part:
if (winnerOne == true){
pointSum+=firstRound;
}
put all of your if/else like the example above!
Hint: when you are using if statement you can use like this:
if (winnerOne){ //you can omit == true, because if winnerOne is true, it will enter ind the if statement
//will enter here if winnerOne is true
}
if (!winnerOne){ //you can omit == false, because if winnerOne is not true, it will enter ind the if statement
//will enter here if winnerOne is false
}
You also have a left over else at the end of your if check which is invalid. You need to end the last else if statement with the };.
Are you trying to out put the text somewhere? I don't see any code that is handling this - you may want to add some HTML that will update like so:
<div class="updatePoints">
// leave empty
</div>
Then within your JavaScript you can always add some code to update the .updatePoints
var points = document.getElementByClass('updatePoints');
points.innerHTML = pointSum.value;
Have add some lines in your code and modify it with some comments. Can try at https://jsfiddle.net/8fhwg6ou/. Hope can help.
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne = true; // Use only one = symbol to assign value, not ==
pointSum = Number(document.getElementById("points").value); // moved from outside and convert to number
// This code will update point in Points box
document.getElementById("points").value = tally_pointsum(pointSum);
// The codes below will add the text in div, just remove the + sign if you don't like
document.getElementById("updatePoints").innerHTML += (tally_pointsum(pointSum) - pointSum) + " points added<br />";
}
}
// Wrap codes below become a function, lets call it tally_pointsum:
function tally_pointsum(pointSum) {
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
return pointSum; //return the sum to caller
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<!-- change class="updatePoints" to id="updatePoints" for document.getElementById("updatePoints") -->
<div id="updatePoints">
</div>
Happy coding.

Store default values and use in comparison in click event

The code is not complete atm but demonstrates what i'm trying to do. In my script i have a jQuery function that is storing the default values from all textareas when the pages is first loaded in an array "defaultValues". When the "click function is executed and the idea is to use the array "defaultValues" in the "CheckTextChange" function and check if anny item dosn't match "currentVal". If currentVal has another value a text change has been made and CheckTextChange will return true. I'm wondering, how can i access "defaultValues[]" inside CheckTextChange and how can i use defaultValues[] in the if-statement to check weather anny item dosn't match currentVal?
HTML:
<h3>Text1...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />
<h3>Text2...</h3>
<textarea class="txt">Hejdå</textarea><br/><br />
<h3>Text3...</h3>
<textarea class="txt">Hejsan</textarea><br/><br />
<input id="btnClick" type="button" value="Save" />
Script:
$('#btnClick').on("click", function () {
if (CheckTextChange()) {
alert('TRUE');
} else {
alert('FALSE');
}
})
var defaultValues = [];
$(document).ready(function(){
$('.txt').each(function () {
var defValue = $(this).get(0).defaultValue;
defaultValues.push(defValue);
var v = defaultValues[0];
});
});
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function () {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != previousVal) {
isChanged = true;
}
});
return isChanged;
}
you can save the default values as a data attrib...
$(document).ready(function() {
$(".txt").each(function() {
$(this).attr("data-deftxt", $(this).val());
});
});
$('#btnClick').on("click", function() {
if (CheckTextChange()) {
alert('TRUE');
} else {
alert('FALSE');
}
})
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function() {
var currentVal = $(this).val();
if ($(this).val() !== $(this).data("deftxt")) {
isChanged = true;
}
});
return isChanged;
}
Use an associative mapping:
var defaultValues = {};
$(document).ready(function(){
$('.txt').each(function () {
defaultValues[$(this).attr('id')] = $(this).val();
});
});
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function () {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != defaultValues[$(this).attr('id')]) {
isChanged = true;
}
});
return isChanged;
}
And set an ID to your fields:
<h3>Text1...</h3>
<textarea class="txt" id="field1">Hejsan</textarea><br/><br />
<h3>Text2...</h3>
<textarea class="txt" id="field2">Hejdå</textarea><br/><br />
<h3>Text3...</h3>
<textarea class="txt" id="field3">Hejsan</textarea><br/><br />
<input id="btnClick" type="button" value="Save" />
You have to break the loop as follow
function CheckTextChange() {;
var isChanged = false;
$('.txt').each(function (index) {
var currentVal = $(this).val();
//Check if anny item in defaultVaules[] match currentVal
if (currentVal != defaultVaules[index]) {
isChanged = true;
return;
}
});
return isChanged;
}

jQuery multiple validation

I have here a form validation. I used this validation in multiple editing records in php. I have two textbox that comparing it's value. I tried to mix my validation script and comparing value script but isn't working properly.
This what I have now but I'm having problem with this when I tried to input lower value in n_quanity field the validation error message is not working and it allowed the form to submit. I want to display error in span not alert the message. Help please?
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
for (var i = 0,len=textBox1.length; i < len;i++) {
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
return false;
} else {
$(this).next("span.val_qty").html("");
}
}
});
And this is my full code
<script>
jQuery(function($) {
var validation_holder;
$("form#register_form input[name='submit']").click(function() {
var validation_holder = 0;
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else {
$(this).next("span.val_qty").html("");
}
});
if(validation_holder == 1) { // if have a field is blank, return false
$("p.validate_msg").slideDown("fast");
return false;
} validation_holder = 0; // else return true
/* validation end */
}); // click end
}); // jQuery End
</script>
<script>
$('#sbtBtn').on('click', function () {
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
for (var i = 0,len=textBox1.length; i < len;i++) {
if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
alert('value is greater than quantity');
return false;
} else {}
}
});
</script>
<p> <label for="">PR Quantity</label> <input name="n_quantity[]" id="n_quantity" class="qty n_quantity" type="text"/><span class="val_qty"></span> </p>
<p style="display:none;"><input id="pr_total" class="pr_total" type="text"></p>

I want to Empty the Value of 2 Input-Type-Text, On Checked (Box)

Guys I Need Help I have the Code what can Empty the Value of Single Input by ID i have 2 Input lets say Start time and End time When i Click on All Day it should be Empty Start Time and End Time When i Check this Button...
Here is my Code....
<Input type="text" id="startime" />
<input type="text" id="endtime" />
<input type="check" id="remove" />
<script type="text/javascript">
var imgInput = document.getElementById('startime'),
remove = document.getElementById('remove'),
val = imgInput.value;
remove.onchange = function() {
if (this.checked) {
imgInput.value = "";
} else {
imgInput.value = val;
}
}
</script>
Help Appreciated...
For a checkbox, you should not use the onchange event handler, onclick will do what you need:
remove.onclick = function() {
if (this.checked) {
imgInput.value = "";
} else {
imgInput.value = val;
}
}
However it looks like you might be trying to save the value if it gets cleared so it can be repopulated, if this is the case then you also need to update val before you clear the text box:
remove.onclick = function() {
if (this.checked) {
val = imgInput.value;
imgInput.value = "";
} else {
imgInput.value = val;
}
}

Categories