Trying to de-increment only a positive number - javascript

The form code:
<td><form action="cart.php" method="get">
<input type="button" onclick="buttonSubtract1()" name="subtract1" value="-
"/>
<input type="text" size="4" id="qty1" name="quantity1" value="0"/>
<input type="button" onclick="buttonAdd1()" name="add1" value="+"/>
<input type="submit" name="product1" value="Add"/>
The javascript:
var i = 0;
var qty1 = document.getElementById('qty1').value;
function buttonAdd1() {
document.getElementById('qty1').value = ++i;
}
function buttonSubtract1() {
if (qty1 > 0) {
document.getElementById('qty1').value = --i;}
}
I changed the code to increment and de-increment using javascript which worked fine so I tried to make it so that de-incrementation only works if the number is positive but now incrementing is working fine but it is not allowing de-incrementation of any number. Why is this?

You just have to put the var qty1 = document.getElementById('qty1').value; into the subtract function like this:
var i = 0;
function buttonAdd1() {
document.getElementById('qty1').value = ++i;
}
function buttonSubtract1() {
var qty1 = document.getElementById('qty1').value;
if (qty1 > 0) {
document.getElementById('qty1').value = --i;}
}
}
In your Example, you just write the First Value (0) into the Window objekt.
It stays zero until you change it in the window object again.
But if you ask the Value everytime the function is called, you get always the newest number.
Fiddle:
http://jsfiddle.net/9wHU9/

Related

increment in the function name and id javascript

I have number of input types and buttons....every button on click increment the value in the relevant input types. But rather than creating a separate function for every button i want to do it by loop....where loop will increase in the function name and id......
<input type="number" id="s1"> <button onclick="increment_s1();">Add</button>
<input type="number" id="s2"> <button onclick="increment_s2()">Add</button>
<input type="number" id="s3"> <button onclick="increment_s3">Add</button>
here is JavaSc code
<script>
var i = 1;
for (i = 0; i < 5; i++) {
var data = 0;
document.getElementById("s"+i).innerText = data;
function ['increment_'+i]() {
data = data + 1;
document.getElementById("s"+i).placeholder = data;
i++;
}
}
</script>
You can't program the function name. You can set up a parameter in the function to make a difference. The param would be the identifier and you can put the whole input element id there.
After that, if you want to have the id s1, s2, and so on, you should initialize the i to start from 1 to 5 instead of 0 to less than 5.
Another thing is, you need to understand the role of placeholder and value attributes in input element. The placeholder works only when the value is empty and it doesn't count as the form value.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
// This is to initialize the 0 values
for (var i = 1; i <= 5; i++) {
var data = 0;
document.getElementById("s"+i).value = data;
}
<input type="number" id="s1"> <button onclick="increment('s1');">Add</button>
<input type="number" id="s2"> <button onclick="increment('s2')">Add</button>
<input type="number" id="s3"> <button onclick="increment('s3')">Add</button>
<input type="number" id="s4"> <button onclick="increment('s4')">Add</button>
<input type="number" id="s5"> <button onclick="increment('s5')">Add</button>
What if you would like to generate whole input and button with loops? You can get them by adding div and use the innerHTML, i.e.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
var divElem = document.querySelector('div');
// Set up empty first
divElem.innerHTML = "";
for(var i=1; i<=5; i++) {
// Create elements here
var innerElem = `<input type="number" id="s${i}" value="0"> <button onclick="increment('s${i}')">Add</button>`;
// Push them all into innerHTML
divElem.innerHTML += innerElem;
}
<div></div>
You can try these two workarounds. Perhaps you may need to learn more about basic HTML elements and their attributes also Javascript.

Creating a compressing function in HTML

So i've been asked for creating a function that compress a string.
I tried to create a javascript function to do that. But it seems, it is not doing anything for the moment. I don't understand why, regardless of the input, my function is not doing anything.
function compression(input) {
var charsToEscape = "#/%&+,!()*':;<=>?";
var escaped = [];
for (var i = 0; i < input.length; i++) {
var testChar = input.substr(i, 1);
if (charsToEscape.indexOf(testChar) > -1) {
escaped.push("%" + testChar.charCodeAt(0).toString(16).toUpperCase());
} else {
escaped.push(testChar);
}
}
return escaped.join("");
}
<label for="input">Input: Uncompressed Link URI</label>
<input type="text" id="input" class="form-control" name="input" value="">
<button onclick="compression(input)" name="button">Compressed </button>
<br><br>
<label for="compression">Output: Compressed Link URI</label>
<input type="text" id="compression" class="form-control" name="compression" value="">
You can see above, the html function is where i put my input, and the output, and the javascript function that is supposed to do the compression.
But for the moment he is not doing anything.
Thank you all in advance for any advice you could provide
1st: You didn't use the value of the input element, but the element itself. So input hase to be replaced with input.value
2nd: You returned a value, but didn't do anything with it.. So you could create a new function that will get the value and put it in the second input
3rd: Your ids' names are too generic. I changed them to be more specific and telling names which will not interfere with other elements in the same page.
function compression(input) {
var charsToEscape = "#/%&+,!()*':;<=>?";
var escaped = [];
for (var i = 0; i < input.value.length; i++) {
var testChar = input.value.substr(i, 1);
if (charsToEscape.indexOf(testChar) > -1) {
escaped.push("%" + testChar.charCodeAt(0).toString(16).toUpperCase());
} else {
escaped.push(testChar);
}
}
return escaped.join("");
}
function insertCompressed(output, value) {
output.value = value
}
<label for="input">Input: Uncompressed Link URI</label>
<input type="text" id="compressionInput" class="form-control" name="input" value="">
<button onclick="insertCompressed(compressionOutput, compression(compressionInput))" name="button">Compressed </button>
<br><br>
<label for="compression">Output: Compressed Link URI</label>
<input type="text" id="compressionOutput" class="form-control" name="compression" value="">
I've created an onCompress function which takes html element as input. The function gets the desired input element, compression and assigns the compressed value to it.
function onCompress(input) {
document.getElementById('compression').value = compression(input.value);
}
function compression(text) {
var charsToEscape = "#/%&+,!()*':;<=>?";
var escaped = [];
for (var i = 0; i < text.length; i++) {
var testChar = text.substr(i, 1);
if (charsToEscape.indexOf(testChar) > -1) {
escaped.push("%" + testChar.charCodeAt(0).toString(16).toUpperCase());
} else {
escaped.push(testChar);
}
}
return escaped.join("");
}
<label for="input">Input: Uncompressed Link URI</label>
<input type="text" id="input" class="form-control" name="input" value="">
<button onclick="onCompress(input)" name="button">Compressed </button>
<br><br>
<label for="compression">Output: Compressed Link URI</label>
<input type="text" id="compression" class="form-control" name="compression" value="">

Automatic array in PHP

How about, make this example, where we put an initial number and final number.
Example We insert the Initial and Final Number:
Initial Number = 1 Final Number = 4
Result = 1 2 3 4
The result is thrown when we press the SEND button.
What I want is that I throw my result without having to press the SEND button.
That the FOR cycle is performed and I throw the result without pressing the button.
That the result is automatic.
CODE:
<form action="" method="post">
<input type="text" name="inivalue" id="inivalue" placeholder="initial value"/>
<input type="text" name="finvalue" id="finvalue" placeholder="final value"/>
<input type="submit" name="submit" vale="submit" />
</form>
<?php
if(isset($_POST['submit']))
{
$num = (int)$_POST['inivalue'];
$numfin = (int)$_POST['finvalue'];
for($num=$num; $num <= $numfin; $num++)
{
echo $num;
}
}
?>
// Get your input elements using getElementById()
const initialValue = document.getElementById("inivalue");
const finalValue = document.getElementById("finvalue");
const result = document.getElementById("result");
let initialVal = "";
let finalVal = "";
// Every time you change the value in your <input> element
// save that value into the initialVal, finalVal variables.
initialValue.addEventListener("change", function(){
initialVal = this.value;
autoArray(initialVal,finalVal);
});
finalValue.addEventListener("change", function(){
finalVal= this.value;
autoArray(initialVal,finalVal);
});
// Loop using initialVal and finalVal
function autoArray(ini,fin){
numArray = [];
if (ini!= "" && fin != "") {
for(i = ini; i <= fin; i++){
numArray.push(i);
}
}
// Change the value of the result <input> element
result.value = numArray;
}
<input type="text" name="inivalue" id="inivalue" placeholder="initial value"/>
<input type="text" name="finvalue" id="finvalue" placeholder="final value"/>
<input type="text" id="result"/>
One way this can be done is using the onChange event.
set it in your final number field:
<input onchange = "rangefinder()" type="text" name="finvalue" id="finvalue" placeholder="final value"/>
then in your javascript function rangefinder():
function rangefinder(){
//get the value of both the invalue and finalvalue fields
//make sure they're both integers - just return if they're not.
//use a for loop to make a string of numbers from invalue to finalvalue
//insert this string where ever you want it.
}
I'll leave the actual JS up to you.

How to make sure every input field has greater value than the value of previous input?

How to make sure that every field has greater value than the value of previous input? If condition is true, then I can submit a form.
$('#add').on('click', function() {
$('#box').append('<div id="p1"><input required type="number" min="1" max="120" name="val" ></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
You need to loop through all the inputs, keeping the value of the previous one to compare it. Keep in mind, your current "add input" code will give all the inputs the same name, which will make it problematic to use on your action page. You can use an array for that.
$("#add").on("click", function() {
$("#box").append('<div id="p1"><input required type="number" min="1" max="120" name="val[]" ></div>');
});
$("form").submit(function(e) {
return higherThanBefore(); //send depending on validation
});
function higherThanBefore() {
var lastValue = null;
var valid = true;
$("input[name^=val]").each(function() {
var val = $(this).val();
if (lastValue !== null && lastValue >= val) { // not higher than before, not valid
valid = false;
}
lastValue = val;
});
return valid; // if we got here, it's valid
}
<a id="add" href="javascript:void(0);">Add </a>
<form action="test">
<div id="box"></div>
<input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
One line added, one line changed. Simply get the last input's value, and use that as the min value for the new input.
$('#add').on('click', function() {
// get the current last input, save its value.
// This will be used as the min value for the new el
var newMin = $("#box").find(".p1 input").last().val() || 1;
// Append the new div, but set the min value to the
// value we just saved.
$('#box').append('<div class="p1"><input required type="number" min="'+newMin+'" max="120" name="val" ></div>');
$(".p1 input").on("keyup mouseup", function(){
var triggeringEl = $(this);
if (triggeringEl.val() >= triggeringEl.attr("min") ) {
triggeringEl.removeClass("error");
}
triggeringEl.parent().nextAll(".p1").children("input").each(function(){
if($(this).attr("min") < triggeringEl.val() )
$(this).attr("min", triggeringEl.val() );
if ($(this).val() < $(this).attr("min")){
$(this).addClass("error");
} else {
$(this).removeClass("error");
}
})
})
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>
So I made changes, to reflect the comments (great catch, by the way), but there is a challenge here. If I set the minimum value when the current el's value changes, works great. But I can't assume that the current el is the highest value in the collection, so if the current el is being decremented, I haven't figured the logic to decrement all subsequent minimums. Sigh...
At any rate, the section that creates the new input and sets the minimum remains the same. Then I had to add a listener to handle changes to the input. If the input is changed, by either keyboard or mouse, all subsequent minimums (minima?) are checked against this value. Those that are lower are set to this value, and then all elements are checked, minimum vs. value, and an error signal is set if needed. Still needs work, as I can't figure how to handle decrementing a value, but it's a start.
You can use .filter(): for each input field you can test if the next one has a value greater then the current one.
$('#add').on('click', function() {
var idx = $('#box').find('div[id^=p]').length;
$('#box').append('<div id="p' + idx + '"><input required type="number" min="1" max="120" name="val' + idx + '" ></div>');
});
$('form').on('submit', function(e) {
var cachedValues = $('form [type=number]');
var noOrderRespected = cachedValues.filter(function(idx, ele) {
var nvalue = cachedValues.eq(idx + 1).val();
return (+ele.value < (+nvalue||+ele.value+1)) ? false : true;
}).length;
console.log('noOrderRespected: ' + noOrderRespected);
if (noOrderRespected > 0) {
e.preventDefault();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="add" href="javascript:void(0);">Add </a>
<form>
<div id="box"></div>
<input type="submit" value="Submit">
</form>

Multiply two values in a form

For my code, I am trying to call 2 parameters into a function. Once you have left the 2nd input box, and multiply the 2 numbers passed through and put it in the third text box. if either of the first 2 input boxes are empty, then color them light red. This is my code so far, what am I missing?
Javascript:
function multiply(one, two) {
if(one==""){
this.style.color='red';
}
if(two==""){
this.style.color='red';
}
else{
txt1=one * two;
return txt1;
}
}
HTML5:
First Value: <input type="text" name="mFirst" />
Second Value: <input type="text" name="mLast" onblur="multiply(mFirst.value, mLast.value)" />
Multiplication of First and Second Value: <input type="text" name="answer">
<input … onblur="multiply.call(this,this.form.elements.mFirst.value,this.form.elements.mLast.value)" >
function multiply(one, two) {
if(one && two){
this.form.elements.answer.value = one * two;
} else {
this.style.color='red';
}
}
Empty strings are non-truthy values, thus one && two will only be true if neither value is an empty string.
Using call allows you to set the value of this used inside the function.
Demo: http://jsfiddle.net/b5Ltt/
You might want to look at the HTML5 <output> element.
You are not passing this to your multiply() function.
If you want to change this.style you can pass this as an argument.
Also, you should change mFirst.value to this.form.elements.mFirst.value and the same for mLast.value
HTML:
First Value: <input type="text" name="mFirst" />
Second Value: <input type="text" name="mLast" onblur="multiply( this , mFirst.value, mLast.value)" />
Multiplication of First and Second Value: <input type="text" name="answer">
JavaScript:
function multiply( _this, one, two) {
var txt1 = 0;
if(one=="" || two==""){
// Should set both colors to red
_this.form.elements.mFirst.style.color = 'red';
_this.form.elements.mLast.style.color= 'red';
}else{
// parse float in the case of a decimal and set de
one = parseFloat(one);
two= parseFloat(two);
txt1 = one * two;
_this.form.elements.answer.value = txt1;
}
}
First Value: <input type="text" name="mFirst" id="mFirst" />
Second Value: <input type="text" name="mLast" id="mLast" onblur="multiply()" />
Multiplication of First and Second Value: <input type="text" name="answer" id="answer" />
function multiply()
{
var num_one = document.getElementById('mFirst').value;
var num_two = document.getElementById('mLast').value;
if(typeof num_one === 'number' && typeof num_two === 'number')
{
document.getElementById('answer').value = (parseInt(num_one) * parseInt(num_two));
}
else
{
document.getElementById('answer').style.color = 'red'; // not recommended method
}
}
Using a similar note, why this doesn't work?
function monetaryfields()
{
if (multiply) { total.value = unitary.value * quantity.value; }
else { unitary.value = total.value / quantity.value; }
}
<form>
<ul>
<li>Quantity: <input type="text" name="quantity" onblur="monetaryfields.call(true)" /></li>
<li>Unitary: <input type="text" name="unitary" onblur="monetaryfields.call(true)" /></li>
<li>Total: <input type="text" name="total" onblur="monetaryfields.call(false)" /></li>
</ul>
</form>

Categories