Comparing form input and span value for keyup function - javascript

I have a form that lists a remaining quantity of a product and below it an input field that lets you put a quantity into the form to submit for purchase.
I have the remaining quantity wrapped in a span with an ID.
On keyup, I want to compare the value of the span with the input entered into the field.
If the input is greater than the value in the span, on keyup, I want to change the value of the input to 0 or the equivalent of the span ID value.
Here is my javascript I am trying to use to accomplish this:
<script>
$(document).ready(function () {
document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);
function Qty_check(){
var QTY1check = document.getElementById('one_and_done_stool_QTY_check').value;
var QTY1remain = document.getElementById('one_and_done_stool_QTY_remain').innerHTML;
if (QTY1check.value > QTY1remain.innerHTML)
alert("NOPE");
{document.getElementById("one_and_done_stool_QTY_check").value = 0;}
};}
</script>
And here is the html:
<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">

Your main issue is in this line:
document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);
You can rewrite:
document.getElementById('one_and_done_stool_QTY_check').onkeyup = Qty_check;
or you may use directly the input event:
document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);
or the jQuery way:
$('#one_and_done_stool_QTY_check').on('input', Qty_check);
The snippet:
document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);
function Qty_check(e) {
var QTY1check = +document.getElementById('one_and_done_stool_QTY_check').value;
var QTY1remain = +document.getElementById('one_and_done_stool_QTY_remain').textContent;
if (QTY1check > QTY1remain) {
console.log("NOPE");
document.getElementById("one_and_done_stool_QTY_check").value = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">

Related

How to clear text field automatically when enter minus value

`
<input type="number" id="qty">
<input type="button" onclick="add()" value="Add">
<script>
function add(){
qty = document.getElementById('qty').value
if(qty>0){
var tot = qty*25
document.write(tot)
}else{
qty = ""
alert("no")
}
}
</script>
'qty=""' is the correct way as mentioned on google. but not working for me.
Try
document.getElementById("qty").value = "";
and cast qty to number in your if
if(Number(qty) > 0)
Values of inputs are always string , try this one in your condition :
if(Number(qty)>0){
...
}
Use this below code to clear the input
qty.value = "";
The reason why qty = '' isn't working is that you've assigned the string value of the input to that variable. Setting it to an empty string won't make the value of the input change - you need to explicitly change the element's value.
So, a few things first:
It's often useful to cache your elements first.
Remove the inline JS and replace it with addEventListener and attach it to the button element (a more modern approach).
Use a <button> element instead of an <input type="button">
Assign the total to an element's text content/innerText instead of document.write for various reasons.
Then when the handler is called coerce the string value of the input to a number, and use that in the condition. If the number is less than zero assign an empty string to the input value.
// Cache the elements
const qty = document.querySelector('#qty');
const result = document.querySelector('#result');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', add);
function add() {
// Coerce the input value to a number
const val = Number(qty.value);
if (val > 0) {
// Instead of `document.write` assign
// the total to the text content of an element
result.textContent = val * 25;
} else {
// Set the value of the qty element to
// an empty string
qty.value = '';
console.log('no');
}
}
#result { margin-top: 0.5em; }
<input type="number" id="qty">
<button type="button">Add</button>
<div id="result"></div>
if you want to check in time when you enter a value (as I understood from the question), you must have a listener on <input type=" number" id="qty"> and event
'input'. qty.addEventListener('input', (e)=>{ // .... make your validation })

Setting values of dynamically added input fields changing all input fields

I have a form where users can create recipes. I start them off with one ingredient field (among others) and then use .append() to add as many more as they want to the div container that holds the first ingredient. The first input field has an id of IngredientName1 and dynamically added input fields are IngredientName2, IngredientName3, etc.
When they start typing in the input field, I pop a list of available ingredients filtered by the value they key into IngredientNameX. When they click on an ingredient in the list, it sets the value of the IngredientNameX field to the text from the div - like a search & click to complete thing. This all works very well; however, when you add IngredientName2 (or any beyond the one I started them with initially) clicking on an available ingredient sets the values of every single IngredientNameX field. No matter how many there are.
I hope this is enough context without being overly verbose, here's my code (I've removed a lot that is not relevant for the purpose of posting, hoping I didn't remove too much):
<div id="ingredientsContainer">
<input type="hidden" id="ingredientCounter" value="1">
<div class="ingredientsRowContainer">
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName1" placeholder="Ingredient" id="IngredientName1" data-ingID="1"><span class="focus-border"></span></div>
</div>
<input type="hidden" name="Ingredient1ID" id="Ingredient1ID">
</div>
<script>
$(document).ready(function(){
$(document).on('keyup', "[id^=IngredientName]",function () {
var value = $(this).val().toLowerCase();
var searchValue = $(this).val();
var valueLength = value.length;
if(valueLength>1){
var theIngredient = $(this).attr("data-ingID");
$("#Ingredients").removeClass("hidden")
var $results = $('#Ingredients').children().filter(function() {
return $(this).text() === searchValue;
});
//user selected an ingredient from the list
$(".ingredientsValues").click(function(){
console.log("theIngredient: "+theIngredient);//LOGS THE CORRECT NUMBER
var selectedIngredientID = $(this).attr("id");
var selectedIngredientText = $(this).text();
$("#IngredientName"+String(theIngredient)).val(selectedIngredientText);//THIS IS WHAT SETS EVERYTHING WITH AN ID OF IngredientNameX
$("#Ingredient"+String(theIngredient)+"ID").val(selectedIngredientID);
$("#Ingredients").addClass("hidden");
});
$("#Ingredients *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
} else {
$("#Ingredients").addClass("hidden")
}
});
$("#AddIngredient").click(function(){
var ingredientCounter = $("#ingredientCounter").val();
ingredientCounter++;
$("#ingredientCounter").val(ingredientCounter);
$('#ingredientsContainer').append('\
<div class="ingredientsRowContainer">\
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName'+ingredientCounter+'" placeholder="Ingredient" id="IngredientName'+ingredientCounter+'" data-ingID="'+ingredientCounter+'"><span class="focus-border"></span></div>\
</div>\
<input type="hidden" name="Ingredient'+ingredientCounter+'ID" id="Ingredient'+ingredientCounter+'ID">\
');
});
});
</script>
[UPDATE] I realized the problem is happening because the function is running multiple times. I assume this happening because I'm calling a function on keyup of a field whose id starts with IngredientName so when one has a key up event, all existing fields run the function. How do i modify my:
$(document).on('keyup', "[id^=IngredientName]",function () {
to only run on the field with focus?

Simple two button counter html jquery javascript

I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days.
I saw this tutorial:
http://www.codecademy.com/courses/a-simple-counter/0/1
I completed the tutorial and thought: "I should learn how to do this with Jquery".
So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript).
Here is my code:
HTML
<body>
<label for="qty">Quantity</label>
<input id="qty" type = "number" value = 0 />
<button class = "botton">-1</button>
<button class = "botton">+1</button>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
Jquery/Javascript:
//create a function that adds or subtracts based on the button pressed
function modify_qty(x) {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = $('#qty').val();
var new_qty = qty + x;
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').html(new_qty)
})
};
$(document).ready(modify_qty);
How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}).
Thank you
If you use data attributes on your buttons you can get the value you want.
HTML:
<button class = "botton" data-value="-1">-1</button>
<button class = "botton" data-value="1">+1</button>
JS:
function modify_qty() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = parseInt($('#qty').val());
var new_qty = qty + parseInt($(this).data('value'));
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').val(new_qty)
})
};
$(document).ready(modify_qty);
More compact JS:
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val());
$qty.val(Math.max(0, currentValue + parseInt($(this).data('value'))));
})
});
Update:
Realized you could do this without the data attributes if want to since your button text is the same as your value.
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val()),
newValue = currentValue + parseInt($(this).text());
$qty.val(Math.max(0, newValue));
})
});
Here's a fiddle to help you grasp the what's going on. Basically, the reference to the element that triggered the event is $(this) or event.target. Things get a bit more complicated with self refence depending on the context you are in, however for $('selector').on('event',function(event){ console.log($(this)) //is the reference to $('selector') });. .attr() -> list of the element's attributes.

Javascript and HTML input scanning and CSS changing

I'm trying to create an <input> that on "unfocus or deselect" asks a function if the data entered inside is valid(Like a password checker) If it is i want it to then change the colour of the inputs background depending on the validity of the response
Width of walls in meters: <input size="40" placeholder="Please enter a number between 1 and 25" type="number" onkeypress="ifTwo();" name="wallWidthInput"><br> <!-- Input Field for wallWidthInput-->
var wallWidthElem = document.getElementsByName("wallWidthInput")[0]; //Finds wallWidthInput, sets wallWidthElem
var wallWidth = parseFloat(wallWidthElem.value) //converts wallWidthElem into a float, sets wallWidth
function ifTwo(){
if (1<=wallWidth && wallWidth<=25) {} //if the wallWidth is between 1 and 25, do nothing. If not alert the user!
else{document.getElementsByName("numberOfWallsInput").style.background="red"; wallWidth=1;}}
Define two css classes as follow:
.ff {background-color:yellow;}
.noff {background-color: red;}
script is like:
$(function(){
var myinput=$("wallWidthInput");
function checkPassword(){
//check your rules here
}
myinput.on('focusout',function(){
if(!checkPassword()){
myinput.toggleClasscss("ff");
}else{myinput.toggleClass("noff");}
});
myinput.on('focus',function(){
myinput.toggleClasscss("ff"); // or any default style
});
});
If you want to solve it with plain JavaScript you could do something like this.
<script type="text/javascript">
function validateWidth(input){ //we'll get the input element as paramter
var wallWidth = parseFloat(input.value); //read the value each time
if (1<=wallWidth && wallWidth<=25){
input.style.background=""; //you'll probably want to reset the background
} else {
input.style.background="red";
input.value=1;
}
}
</script>
Width of walls in meters:
<input size="40" placeholder="Please enter a number between 1 and 25" type="number" onchange="validateWidth(this);" name="wallWidthInput"><br>
I've chosen to trigger the validation onchange, because then we validate even if someone uses the small arrows.
<script type="text/javascript">
$(document).ready(function(){
function checkPassword(){
//your logic return true or false based on condition
}
$(":input[name='pwd']").on('focusout',function(){ // When losing focus
if(!checkPassword()){
$(this).css('background',somecolorCode);
}else{$(this).css('background','#ffffff');}
});
$(":input[name='pwd']").on('focus',function(){ // When focus
$(this).css('background','#333');
});
});
</script>

Dynamically creating a specific number of input form elements

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>

Categories