Automatically check date checkbox - javascript

I have 3 checkboxes and 2 inputs.
The second checkbox is parent() of the 1 input type number and the third checkbox is parent() of the 2 input type number:
$calendar .= "<td bgcolor='$color' data-semana=''><font size='2px'/>
<input type='checkbox' name='arrachar[$year, $month, $day][dia]' value='$year-$month-$day' $marcado_data $disabled> <strong style='color:#5ca2df'>$year-$month-$day</strong> <br />
<div style='width:60%;position:relative;float:left'><input type='checkbox' name='arrachar[$year, $month, $day][OpcaoA]' value='Peq_Almoço' $marcado_pequeno $disabled> <strong style='color: #000000'>Peq. Almoço</strong></div> <div style='width:40%;position:relative;float:left'><input $disabled min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd]' value='$marcado_pequeno_qtd' style='width:65px; height: 22px' /> <br /> </div>
<div style='width:60%;position:relative;float:left'><input type='checkbox' name='arrachar[$year, $month, $day][opcaoB]' value='Almoço' $marcado_almoco $disabled> <strong style='color: #000000'>Almoço</strong></div> <div style='width:40%;position:relative;float:left'><input $disabled min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd1]' value='$marcado_almoco_qtd' style='width:65px; height: 22px' /> <br /> </div></font></center></td>";}
To automatically mark the 2 and 3 checkbox by putting a value greater than zero in the input type number I have estre script:
<script>
var inputs_ = document.querySelectorAll("[type='number'][name^='arrachar']");
for(var x=0; x<inputs_.length; x++){
inputs_[x].addEventListener("input", function(){
var box = this.parentNode.previousElementSibling.querySelector("[type='checkbox']");
box.checked = this.value > 0 ? true : false;
});
}
</script>
when filling in the 1 or 2 input type number, in addition to automatically marking the checkbox parent() of it, I also want to automatically check the first checkbox of the date.
Is it possible to adapt my script to do this?
The solution would be this by changing the script:
<script>
var inputs_ = [...document.querySelectorAll("[type='number'][name^='arrachar']")];
for(var x=0; x<inputs_.length; x++){
inputs_[x].addEventListener("input", function(){
var box = this.parentNode.previousElementSibling.querySelector("[type='checkbox']");
box.checked = !getValuesLessorEqualZero([this]);
var firstBox = document.getElementById('firstCB');
firstBox.checked = this.value > 0 ? true : false;
var valueAllLessOrZero = getValuesLessorEqualZero(inputs_);
if(valueAllLessOrZero) firstBox.checked = false;
});
}
const getValuesLessorEqualZero = (inputs) => {
var lengthInputs = inputs.length;
var valueLessOrZero = true;
for(let i = 0; i < lengthInputs && valueLessOrZero; i++) {
valueLessOrZero = inputs[i].value <= 0 ? true : false;
}
return valueLessOrZero;
};
</script>
But there is a problem, when I put a value greater than zero in an input, it automatically marks the checkbox of day one and not the date according to the input that I am filling. For example, I put value in the input of the day 2018-11-18 and select the checkbox of the date of the day 2018-11-01.
Image problem example:
Imagem
How can I solve this problem?

First of all on the first line you wrote double equal:
$marcado_pequeno =$marcado_almoco =$marcado_pequeno_qtd =$marcado_almoco_qtd='';
Second of all, it's quite unclear so if anything just remember that you need to put the input's in form tag's and get the information with "get" or "request" or "post" globals.
Lastly, for your issue.
while ((the input) == 1){
<script>
document.getElementById("checkbox id").checked = true
</script>
}

Related

How can I pattern match ID only making sure the variable number matches without having to hardcode all of the possibilities?

I've recently become familiar with Jquery selectors....and they work great. Starts with...ends with....
The problem I have currently is that all of my variable names essentially start with similar patterns and end with similar patterns. This ID is generated from somewhere else so I'm hoping I can do something to use it effectively.
The pattern ID format essentially looks like...
"#id_newbudgetlineitem_set-0-line_item_october"
"#id_newbudgetlineitem_set-0-line_item_november"
"#id_newbudgetlineitem_set-0-line_item_december"
I want to essentially matching on the set-* but only if it's identical to the other ids in my array. Is this even possible without having to hard code anywhere from set-0 to set-1000? Unfortunately the class for each one is the same as is the name situation. Is there someway to say if the set numbers all match in a given array then add them up? I can't use starts with or ends with in this case...and don't want to hardcode 1000 possibilities. Thanks in advance for any ideas or thoughts.
I am trying to do something like.....
function update_total()
{
var total = 0;
$('.budget').each(function(index, element) {
"#id_newbudgetlineitem_set-0-line_item_october" +
"#id_newbudgetlineitem_set-0-line_item_november" +
"#id_newbudgetlineitem_set-0-line_item_december"
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
});
$("#id_total").val(total);
}
Here's a working solution........
function update_total_total_total()
{
var ret = +$("input[name$='set-0-line_item_january']").val() + +$("input[name$='set-0-line_item_february']").val() + +$("input[name$='set-0-line_item_march']").val() + +$("input[name$='set-0-line_item_april']").val() + +$("input[name$='set-0-line_item_may']").val() + +$("input[name$='set-0-line_item_june']").val() + +$("input[name$='set-0-line_item_july']").val() + +$("input[name$='set-0-line_item_august']").val() + +$("input[name$='set-0-line_item_september']").val() + +$("input[name$='set-0-line_item_october']").val() + +$("input[name$='set-0-line_item_november']").val() + +$("input[name$='set-0-line_item_december']").val();
$("input[name$='set-0-line_item_total']").val(ret);
}
But I could have up to 1000 different set values. Is there some other way to do this without having to hard code this 999 more times?
This is a lot closer....but total still says 0. It's updating all of the totals to 0...so that's progress but not getting the actual totals. Forward progress thanks to Swati.
function update_total_total_total() {
//get length of input line_total for each sets..
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
//get all inputs but not line_item _total
$(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(index, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
})
$(`input[id$=set-${i}-line_item_total]`).val(total); //set value..of input
}
}
You can get length of total input whose name ends with line_item_total so this value will be counter for for-loop.
Then , inside for loop you can use $(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total])`) this will fetch values from all inputs expect the line_total_item then add value on each iteration .
Lastly , use $(`input[name$=set-${i}-line_item_total]`).val(total); to set total inside line_total_item textbox.
Demo Code :
function update_total_total_total() {
//get length of input line_total for each sets..
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
//get all inputs but not line_item _total
$(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(i, element) {
var val = parseFloat($(element).val());
if (!isNaN(val)) {
total += val;
}
})
$(`input[name$=set-${i}-line_item_total]`).val(total); //set value..of input
}
}
update_total_total_total()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
SET 0 :
<input type="text" name="id_newbudgetlineitem_set-0-line_item_october" value="5">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_november" value="51">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_december" value="15">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-0-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_description">
</div>
<br/>
<div>
SET 1
<input type="text" name="id_newbudgetlineitem_set-1-line_item_october" value="5">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_december" value="534">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-1-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_description">
</div>
<br/>
<div>
SET 2
<input type="text" name="id_newbudgetlineitem_set-2-line_item_december" value="4">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_oct" value="5">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-2-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_description">
</div>
This was the final working code. As Swati suggested it was an incorrect name reference.
function update_total_total_total() {
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
$(`input[name*=newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(i, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
})
$(`input[name$=set-${i}-line_item_total]`).val(total);
}
}

Limit number of characters in collection of number input fields

I have used the reference from from this question and I want to achieve exactly what the question asked however for multiple input text fields. I would like to restrict the user to not type further and have used getElementsByClassName instead of getElementById.
HTML
<td>
<input id="quantity_scroll" cart_id="<?php echo $cart_row['id']; ?>" min="1" type ="number" max="99" value="<?php echo $cart_row['quantity'] ;?>" oninput = "checkLength()" class="form-control form-quantity" style=" width: 60px;text-align: left;" >
</td>
Javascript
function checkLength(){
var elements = document.getElementsByClassName("form-quantity");
var y;
var ele = elements.length/2;
for(y=0; y < ele; y++){
var length = elements[y].value.length;
if(length <= 2){
return true;
}else{
var value = elements[y].value;
value = value.substring(0, value.length-1);
document.getElementsByClassName("form-quantity")[y].value = value;
}
}
}
However the user is restricted only in the first input box and not in the others. I tried different ways however cannot understand why it isn't happening.
Check the below code. It will restrict users to not enter more than 3 digit numbers. You just need to ensure that all your input fields have the same class form-field:
$(".form-field").on('input', function() {
var enteredVal = $(this).val();
if (enteredVal.length > 3) {
$(this).val(enteredVal.substring(0, enteredVal.length - 1));
console.log('More than 3 characters not allowed.');
return;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='form-field' />

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

How to manipulate value based on textbox value?

If I enter negative value in textbox, while in onclick the value will be reduced by some other value.
If I enter positive value in textbox, while in onclick the value will be add by some other values.
Make a simple comparison.
function go() {
var value = parseFloat(document.getElementById("value").value),
positiveValue = 5,
negativeValue = -1;
value += value < 0 ? negativeValue : positiveValue;
document.getElementById("value").value = value
}
<input id="value" onchange="go()">
Change the value of the textbox comparing it on button click.
HTML :
<input type="text" id="inputTextBox" />
<input type="button" id="changeButton" value="update value"/>
javaScript :
var paddingValue = 10;
document.getElementById("changeButton").onclick = function(){
var inputTextBox = document.getElementById("inputTextBox");
if(inputTextBox.value < 0){
inputTextBox.value = parseInt(inputTextBox.value) - paddingValue;
}else{
inputTextBox.value = parseInt(inputTextBox.value) + paddingValue;
}
};
jsFiddle demo

How to create a validation on textbox?

I have 3 textboxes, I want to create a validation in textbox. For Example textbox1 value is 10, then textbox2.1stquarter value is 5, textbox3.2ndquarter should have atleast 5 or lower than 5. If the combine value of textbox2 and textbox3 is equal to 10 allow it but if the combine value of textbox2 and textbox3 is greater than 10 should not allow it. How to do it?
Just like this code. I want to get the value of textbox1so the two other textbox should have >10
function CompareValues() {
var textBox1=document.GetElementById('ID_OF_TextBox1');
var textBox2=document.GetElementById('ID_OF_TextBox2');
var textBox3=document.GetElementById('ID_OF_TextBox3');
if ( textBox1.value>textBox2.value + textBox3.value ) {
the value is greater than textbox1
}
}
Seriously you could have done it by yourself mate... Check if the below fiddle helps u... :)
var textBox1=document.getElementById('textbox1').value;
var textBox2=document.getElementById('textbox2').value;
var textBox3=document.getElementById('textbox3').value;
if((+textBox2 + +textBox3) >= 10){
$('#textbox1').val('');
$('#textbox2').val('');
$('#textbox3').val('');
return false;
}else{
alert('value ok');
}
http://jsfiddle.net/B5cKr/
HTML:
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<input id="txt3" type="text" />
<DIV id="btnValid">CLICK</DIV>
JS:
$("#btnValid").on('click', function () {
var txt1 = $("#txt1").val();
var txt2 = $("#txt2").val();
var txt3 = $("#txt3").val();
var combine_2_3 = Number(txt2) + Number(txt3);
if (Number(txt1) > Number(txt2) || Number(txt1) > Number(txt3)) {
if (Number(txt1) > Number(combine_2_3)) {
alert("txt1 value is greater then combine value ");
}
else {
alert("combine value txt2, txt3 is greater then txt1");
$("#txt1").val("");
$("#txt2").val("");
$("#txt3").val("");
}
}
});
DEMO
Updated DEMO

Categories

Resources