I have three buttons, + value -. in this when i click + button value will increase and - value will be decrease .. i have wote the code in jSFIDLLE. it working.
And the value should not be minus. so i added one if condition. then my code is not working.
html-
<input type="Button" id='AddButton' value="+" />
<input type="Button" id='BoqTextBox' value="0" />
<input type="Button" id='MinusButton' value="-" />
javascript -
$('#AddButton').on('click', function () {
var input = $('#BoqTextBox');
input.val(parseFloat(input.val(), 10) + 1);
})
$('#MinusButton').on('click', function () {
var input = $('#BoqTextBox');
if(input>0)
{ input.val(parseFloat(input.val(), 10) - 1);}
})
You are comparing a HTML element with 0. You need to compare its value with 0
Try
if (input.val() > 0)
You need to use
if(input.val() > 0)
As
if(input > 0)
Means that you are trying to see if the object, not it's value is bigger than 0, which is not the case as it is an element
Use if(input.val()>0) instead of if(input>0)
You are trying to compare input with 0. You should instead compare the value of input with 0.
Replace
if (input > 0)
with
if (parseInt(input.val()) > 0)
Here it is
$('#AddButton').on('click', function () {
var input = $('#BoqTextBox');
input.val(parseFloat(input.val(), 10) + 1);
})
$('#MinusButton').on('click', function () {
var input = $('#BoqTextBox');
if(input.val()>0)
{ input.val(parseFloat(input.val(), 10) - 1);}
})
Try this:
if(input.val() > 0)
Related
My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/
For example I have, input type with predefined length.
I want to achieve, when the input value is bigger or equal to 3, to replace that part of string[3] with '/';
<input type="text" id="number" maxlength="6" placeholder="MM/YY"/>
And here is jquery
$('#number').on('keypress',function(){
if(this.value.length <= 3) {
this.value.replace(this.value[3],'/');
}
});
So in short when user types inside input field for example: 1234, the number 3 needs to be replaced with '/' and than the value would be 12/2017, like expiration date of credit card. Thanks in advance
You can try something like this. Had to change the maximum length of input's value from 6 to 7.
Try with e.g. 12/2017.
$('#number').on('keypress', function() {
if (this.value.length >= 2) {
this.value = this.value.slice(0, 2) + '/' + this.value.slice(3, this.value.length)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="number" maxlength="7" placeholder="MM/YY" />
You could try the following.
Where delimeterIndeces is where in the string you want to check and change the values. InputString is the string returned from the input tag.
let delimeterIndices = [2,5]; // "02[/]15[/]2017";
let inputString = "123152017";
let resultString = inputString.split('').map((char, index) => {
if(delimeterIndices.indexOf(index) !== -1) {
return '/';
} else {
return char;
}
}).join('');
console.log(resultString);
I have a form that the user can use to enter 5 numbers. I have given all five input boxes the same id and a different name. I want to perform a validation of each input box. I want to be able to change background color of the input boxes based on the number they enter. For example, every input box with number in range 0-5 should change its background color to red and those between 6-10 should be green.
I have been able to write a code that would cause the color to change for one input box, however I cannot think of a way to optimize my code and avoid having to write the same code five times. Here is what I have got so far:
Form:
<form id="numbers">
Number1: <input id ="color" name="num1" type="number" onchange="check();">
<br><br>
Number2: <input id ="color" name="num2" type="number" onchange="check();">
<br><br>
Number3: <input id ="color" name="num3" type="number" onchange="check();">
<br><br>
</form>
Function:
function check() {
var inputVal = document.getElementById("color").value;
if (inputVal=="" || inputVal ==null) {
document.getElementById("color").style.backgroundColor = "white";
}
else if (inputVal >= 0 && inputVal <= 5) {
document.getElementById("color").style.backgroundColor = "red";
}
else if (inputVal >= 6 && inputVal <= 10) {
document.getElementById("color").style.backgroundColor = "green";
}
}
If I change inputVal to an array and use a for loop to save values of document.getElementById("color").value, it will save the first number entered by the user five times and will only update the color of the first box.
Here is what I tried:
var inputVal = new Array();
for(var i=0; i<5; i++) {
inputVal[i]= document.getElementById("color").value;
}
You can have the clicked element as a parameter
function check(element) {
var inputVal = element.value;
if (inputVal=="" || inputVal ==null) {
element.style.backgroundColor = "white";
}
else if (inputVal >= 0 && inputVal <= 5) {
element.style.backgroundColor = "red";
}
else if (inputVal >= 6 && inputVal <= 10) {
element.style.backgroundColor = "green";
}
}
and pass the argument for each input
<form id="numbers">
Number1: <input id ="color1" name="num1" type="number" onchange="check(this);" />
<br/><br/>
Number2: <input id ="color2" name="num2" type="number" onchange="check(this);" />
<br/><br/>
Number3: <input id ="color3" name="num3" type="number" onchange="check(this);" />
<br/><br/>
</form>
But ID's must be unique. Here is a FIDDLE
You can use jquery to achieve this. First remove all the id value, they should not be same. Then use $('input').on('change', function (){
$(this).css("background-color","red")})...
This way you can change colors based on values.
First, you can simplify your JavaScript by designating it to target this, since you're executing the function onchange.
Second, you should never leave an open-ended IF...THEN...ELSE, just bad habit for when they can result in BIG changes.
Third, as noted by others, id must be unique across the page.
Give this a try:
function check(tar) {
var inputVal = tar.value;
if(inputVal == '' || inputVal == null) {
tar.style.backgroundColor = 'white';
} else if(inputVal >= 0 && inputVal <= 5) {
tar.style.backgroundColor = 'red';
} else if(inputVal >= 6 && inputVal <= 10) {
tar.style.backgroundColor = 'green';
} else {
tar.style.backgroundColor = 'yellow';
}
}
<form id="numbers">
Number1: <input class ="color" name="num1" type="number" onchange="check(this);" />
<br><br>
Number2: <input class ="color" name="num2" type="number" onchange="check(this);" />
<br><br>
Number3: <input class ="color" name="num3" type="number" onchange="check(this);" />
</form>
Here's a JSFiddle: http://jsfiddle.net/v1daq6sx/
I hope this helps. ^^
When the user changes their value it fires the function giveInputColor. You can use this one function to check infinitely many inputs with the class hello.
Working Example: http://codepen.io/anon/pen/bNqraN
HTML
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
jQuery
$('input.hello').keyup(function(event) {
/* Act on the event */
var value = $(this).val();
$(this).css('backgroundColor', giveInputColor(value));
});
function giveInputColor(value) {
// Give Input a color based on value parameter
if (value >= 0 && value <= 5) return 'Red';
else if (value >= 6 && value <= 10) return 'Green';
else return 'White';
}
Without going into any major redesign of your logic (you could make it more efficient, but I focused on just getting the behavior that you are looking for), you can simply add the function to each element with an event listner, and then use e.target to determine which element is the one that changed and triggered the function call. Note - the aproach is a little more streamlined in jQuery, but I will stick with native JS here.
First off, lets give all of these inputs a common class ("number-field"), to make them easier to find:
<form id="numbers">
Number1: <input id="num1" name="num1" type="number" class="number-field">
<br><br>
Number2: <input id="num2" name="num2" type="number" class="number-field">
<br><br>
Number3: <input id="num3" name="num3" type="number" class="number-field">
<br><br>
</form>
I also made the id attributes unique and remover the onchange attributes, since we whill add the event listener dynamically.
Then we needed updated the check() function to accept the change event as a parameter (e) which is used in the first line of the function to determine the element that triggered the change event, using e.target (note - e.srcElement is to support older versions of IE).
function check(e) {
var inputEl = e.target || e.srcElement;
var inputVal = inputEl.value;
if (inputVal == "" || inputVal == null) {
this.style.backgroundColor = "white";
}
else if (inputVal >= 0 && inputVal <= 5) {
this.style.backgroundColor = "red";
}
else if (inputVal >= 6 && inputVal <= 10) {
this.style.backgroundColor = "green";
}
}
The rest of the code is simply updated to point to the variable that was determined in the first line.
Finally, the function needed to be bound to the number inputs, so, using the class attribute that I added earlier, you can find all of those inputs, cycle through them, and add event listeners to each one.
var numInputs = document.getElementsByClassName("number-field");
for (i = 0; i < numInputs.length; i++) {
numInputs[i].addEventListener('change', check);
}
I checked it out locally and it is behaving the way that I believe that you were wanting it to.
I am having the following HTML block in my page.
<input type="text" id="fillingInput"/>
<input type="text" id="filledInput" maxlength="5"/>
<input type="button" onclick="$('#filledInput').val($('#fillingInput').val());"/>
when the button is clicked, the value of fillingInput is set as value for filledInput.
But the maxlength is not considered while setting value like this.
Any solution?
Try slice:
<input type="button"
onclick="$('#filledInput').val($('#fillingInput').val().slice(0,5));"/>
Try this
$(document).ready(function () {
$('#add').click(function () {
var str = $('#fillingInput').val();
if (str.length > 5) {
str = str.substring(0, 5);
$('#filledInput').val(str);
}
});
});
one way to get this is ... removing all charaters after 5th character. using substring()
<input type="button" id="add" />
JS
$('#add').click(function(){
var str=$('#fillingInput').val();
if(str.length > 5) {
str = str.substring(0,5);
}
$('#filledInput').val(str);
});
fiddle ..
it is recommended not to use inline javascript.
if you are using jQuery you can add a "valHook" which hooks into each call of .val()
$.valHooks.input = {
set: function(element, value) {
if ("maxLength" in element && value.length > element.maxLength)
value = value.substr(0, element.maxLength);
element.value = value;
return true;
}
};
I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
THanks
You have to put the counter variable outside the event handler, otherwise you will be starting over from zero each time.
You should put the code that adds the elements inside the if statement, so that you either show a messare or add the elements.
There is no point in reading the value from the button that you just added, when you already have the value. Besides, an id should be unique, so you would not get the value from the last button but the first.
The comparison operator is ==, if you use = you will instead assign a value to the variable, so the condition would always end up being true.
$(document).ready(function(){
var sliderCount = 0;
jQuery('#add_slider_image').click(function() {
if (sliderCount == 5) {
alert('Limit reached');
} else {
sliderCount++;
jQuery('.form-table').append('<tr><td><input type="text" value="" name="slider[]" /><input type="button" name="sliderbut" value="Upload" rel="'+ sliderCount +'" /></td><tr>');
}
});
});
I guess something like this should work:
jQuery('#add_slider_image').click(function() {
var count = jQuery("input[name='sliderbut']").length;
if (count < 5){
jQuery('.form-table').append("<tr><td><input type='text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' /></td><tr>");
}
})
A bit simplified fiddle there: http://jsfiddle.net/Daess/fukxu/
When you try to compare the "count" with the number 5 you have to use == instead.
count = 5 will set count to 5 and always return true if you use count == 5 it will compare your variable with the number 5 and return true or false, depending on the value of the variable.
Also I think you can easily count the number of buttons by using length, sth like: $('.button').length should return the number of elements with the class (not ID) "button".
var i = 0
var plus = ++i;
This part means that plus will always be zero and i == 1, so your rel attribute always reads 0.
var count = jQuery.('#button').attr('rel');
You are using an ID selector. And ID can exist only once per page. As you use an ID selector, you get only the first matched element which will obviously not be the one you want as you want the number in the last element.
if(count=5){
..but it doesn't matter anyway because now you're just telling that count equals 5 and the alert will always execute. What you are looking for is the comparison operator ==.
Easiest way to do this is to ditch the counts and whatnots, and just check if there are already too many elements before inserting:
jQuery('#add_slider_image').click(function() {
if($('.form-table .myRow').length < 5) {
jQuery('.form-table').append('<tr class="myRow"><td><input type="text" name="slider[]" /><input type="button" name="sliderbut" value="Upload" class="button" /></td><tr>');
}
});
Note that I added the myRow class to help identify which rows are appended and changed the id="button" to class="button".
Try this.
jQuery('#add_slider_image').click(function() {
var myHTML = "";
var current_count = jQuery('.form-table tr').length();
if (current_count >= 5) return;
for (var i = current_count; i <= 5; i++) {
myHTML += "<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button" + plus + "' rel='" + plus + "' /></td><tr>";
}
//touch DOM once
jQuery('.form-table').append(myHTML);
});