Check,reset buttons active after all inputs were completed - javascript

how can i make check and reset buttons active after 6 inputs were completed? I have tryed:
if($('.input') == ""){
checkBtn.disabled = true;
resetBtn.disabled = true;
}
else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
EDIT 2 with fiddle : http://jsfiddle.net/usPMd/88/

Edit : Your Jsfiddle return error 404... So I developed a basic example (it is not perfect).
Jsfiddle
Javascript solution :
<body>
<form>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input id="send" type="submit" disabled/>
<input id="reset" type="reset" disabled/>
</form>
<script type="text/javascript">
var checkBtn = document.getElementById("send");
var resetBtn = document.getElementById("reset");
var inputTag, lengthInputTag, nbCompleted;
function forEach( a, fn ) {
return [].forEach.call(a, fn);
};
function checkInput(){
inputTag = document.getElementsByTagName("input");
lengthInputTag = inputTag.length;
nbCompleted = 0;
console.log(inputTag);
forEach(inputTag, function(el) {
if(el.value != ""){
nbCompleted++;
}
});
if(nbCompleted < 6){
checkBtn.disabled = true;
resetBtn.disabled = true;
}else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
};
</script>
</body>

if($('.input').length == 6){
checkBtn.disabled = false;
resetBtn.disabled = false;
}else{
checkBtn.disabled = true;
resetBtn.disabled = true;
}

So, use length then:
if($('.input').length == 7){ //after 6 is 7th input
checkBtn.disabled = true;
resetBtn.disabled = true;
}
And also there might be a typo .input should be input but not 100% sure because this might also be class.

Ok, Here you go:
Workign demo: JSFiddle
HTML (partial):
<button id="validateButton" class="validateButton" type="button" disabled="disabled">Check</button>
<button id="resetButton" class="resetButton" type="button" disabled="disabled">Reset</button>
JS:
$(document).on('change blur', '.input', function(){
var count = 0;
$('.input').each(function(){
var elem_v = $.trim ( $(this).val() );
if (elem_v != "") {
count++;
}
})
$('button').prop('disabled', true);
if (count===6){
$('button').prop('disabled', false);
}
});

Related

Maintain visibility of a form-textinput when checkbox is checked

In my HTML I have a form, where a user can select the checkbox "other" and a textbox appears. Otherwise the textbox is hidden. Below you can find my code. But if the user selects "other", types in his text und submits the form, the textbox is hidden again-although the checkbox maintain checked (saved in localStorage). I cannot find my mistake here.
Form:
<label class="form-check">
<input class="form-check-input" name="filetype" type="checkbox" id="other" value="" onclick="save()">
<span class="form-check-label"
<input placeholder="e.g. 'msg'" name="other" onsubmit="save();" class="form-control input-lg" type="text" id="otherValue" value="{{extension}}">
</span>
</label> <!-- form-check -->
Visible/Hidden
<!--"Other"-filter-->
<script type="text/javascript">
var otherCheckbox = document.querySelector('input[id="other"]');
var otherText = document.querySelector('input[id="otherValue"]');
otherText.style.visibility = 'hidden';
otherCheckbox.onchange = function(){
if(otherCheckbox.checked) {
otherText.style.visibility = 'visible';
otherCheckbox.value = otherText.value;
save();
} else {
otherText.style.visibility = 'hidden';
}
};
</script>
Tried to solve this Problem by saving the info in the sessionStorage but it still does not work.
<!--Save Checkbox-State-->
<script type="text/javascript">
const checkboxen = [...document.querySelectorAll("[type=checkbox]")].map(inp => inp.id); //list of all checkbox-IDs
function save(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checkbox = document.getElementById(id);
sessionStorage.setItem(id,checkbox.checked);
}
var other = document.getElementById('otherValue');
sessionStorage.setItem('otherValue',other.style.visibility);
}
function load(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checked =JSON.parse(sessionStorage.getItem(id));
document.getElementById(id).checked = checked;
}
var other = JSON.parse(sessionStorage.getItem('otherValue'));
document.getElementById('otherValue').style.visibility = other;
}
function deleteCheckbox(){
sessionStorage.clear();
}
</script>
Thanks for any help <3
with prop jquery:
<script>
$(function(){
var other = localStorage.input === 'true'? true: false;
$('input').prop('checked', other);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>
this is my solution:
<script type="text/javascript">
var other = document.getElementById('other');
var otherText =document.querySelector('input[id="otherValue"]');
$(document).ready(function(){
if (other.checked){
otherText.style.visibility = 'visible';
otherText.value = "{{extension}}";
other.value = "{{extension}}";
} else {
otherText.style.visibility = 'hidden';
otherText.value = "";
}
});

Disable textboxes depending on the value of another textbox

I got three textboxes in my Form. My goal is to disable the validate and evaluate textbox if the number in digit textbox is not equal to 0. How do i accomplish this?
Pseudo code
if(digit.Text != 0 )
{
validate.enable = false;
evaluate.enable = false;
}
else
{
validate.enable = true;
evaluate.enable = true;
}
My Attempt
function disableME()
{
var numberTextBox = document.getElementById('number'),
validateTextBox = document.getElementById('validate'),
evaluateTextBox = document.getElementById('evaluate');
if (numberTextBox.value != 0)
{
validateTextBox.disable = true;
evaluateTextBox.disable = true;
}
else
{
validateTextBox.disable = false;
evaluateTextBox.disable = false;
}
}
<form action="welcome.php" method="post" id="myForm">
Number: <input type="number" id="number" onchange="disableME()"><br>
Validate: <input type="text" id="validate" onchange="disableME()"><br>
Evaluate: <input type="text" id="evaluate" onchange="disableME()"><br>
</form>
You should use ELEMENT.disabled instead of ELEMENT.disable.
Here is the change to your code:
function disableME()
{
var numberTextBox = document.getElementById('number'),
validateTextBox = document.getElementById('validate'),
evaluateTextBox = document.getElementById('evaluate');
if (numberTextBox.value != 0)
{
validateTextBox.disabled = true;
evaluateTextBox.disabled = true;
}
else
{
validateTextBox.disabled = false;
evaluateTextBox.disabled = false;
}
}
<form action="welcome.php" method="post" id="myForm">
Number: <input type="number" id="number" onchange="disableME()"><br>
Validate: <input type="text" id="validate" onchange="disableME()"><br>
Evaluate: <input type="text" id="evaluate" onchange="disableME()"><br>
</form>

Disable textbox when two textbox is equal

How can i disable textbox when selected (textbox name) and quantity (textbox name) is equal. i used this codes its working but when selected (textbox name) is equal to 3 the txtCombo (textbox name) is not disabled but when equal to 4 it became disabled how should i work on this ? thank you in advance.
// disable button if equal
// $('#button').click(function(){
$('#button').click(function() {
var firstValue = $("#quantitytotransfer").val();
var secondValue = $("#selected").val();
if ((firstValue == secondValue)) {
$("#txtCombo").prop("disabled", true);
}
});
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value.trim();
option.value = textb.value.trim();
option.selected = true;
if ($('#combo option[value="' + textb.value.trim() + '"]').text() == textb.value.trim()) {
alert("Duplicate found or you entered empty value");
return false;
}
try {
combo.add(option, null); //Standard
} catch (error) {
combo.add(option); // IE only
}
textb.value = "";
}
$("#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);
});
});
$(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();
var previousOption;
$('select[name=combo] option').each(function() {
if (this.text == previousOption) $(this).remove();
previousOption = this.text;
});
// 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 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<BODY style="font-family: sans-serif">
<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" />Quantity:
<input type="text" name="quantity" value="3" id="quantitytotransfer" />
<br>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>Combobox:
<select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
You can achieve this easily :
function checkIfEqual(){
if($("#selected").val() === $("#quantitytotransfer").val())
$("#txtCombo").prop("disabled", true);
else
$("#txtCombo").prop("disabled", false);
}
$("#button").click(function(){
$("#selected").val($("#combo option:selected").length);
checkIfEqual();
});
demo here
Have you tried this:
function addCombo() {
var txtSelected = $('#selected').val();
var qty = $('#quantitytotransfer').val();
if(parseInt(txtSelected) == parseInt(qty)) {
alert('Equal');
document.getElementById('txtCombo').disabled = true;
} else {
alert('Not equal');
document.getElementById('txtCombo').disabled = false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<BODY style="font-family: sans-serif">
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/><br>
Selected: <input type="text" name="selected" id="selected" class="toggle"/><br>
IMEI Selected: <input type="text" name="imei" id="imei"/><br>
Quantity: <input type="text" name="quantity" value="3" id="quantitytotransfer" class="toggle"/><br>
<input type="button" id="button" value="Add" onclick="addCombo()"><br>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>

onSubmit validation changing label style

I'm trying to get this form to change label color after submission if the field is empty and then return back to normal when the field is filled in.
It's behaviour would be something similar to:
Onsubmit validate change background requried fields?
Except I can't figure out how to link the inputs to the labels. I'm using the jsFiddle from the link above at:
http://jsfiddle.net/interdream/cpG2r/7/
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
My JavaScript isn't so good. Please help!
Here is your Working sample</>
You should look around Knockoutjs style binding with dom value.
you could add label tags, like:
<form action="" id="myForm">
<label for="field1">Required field:</label> <input type="text" name="field1" class="required" /><br />
<label for="field2">Required field 2:</label> <input type="text" name="field2" class="required" />
<input type="submit" value="Go" />
</form>
And in js part
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
var lbl = document.getElementsByTagName("label")[i]; //get label
if(!fields[i].value) {
lbl.style.color = "red";
console.log(lbl );
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
lbl.style.color = "black";
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
See : updated Fiddle
Try
<form action="" id="myForm">
<label>Required field: </label><input type="text" class="required" /><br />
<label>Required field 2: </label><input type="text" class="required" />
<input type="submit" value="Go" />
</form>
And
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
var prev = fields[i].previousSibling;
while(!/label/i.test(prev.tagName)){
prev = prev.previousSibling;
}
prev.style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
Demo: Fiddle
You can use jquery validation Plugin ... it has support for all types of validations as well as changing label colors & Can display suitable error messages
Here is very simple, smart yet effective way to doing this by using amazing knockout binding here is working sample :JsFiddle Link
var viewModel = {
validation: ko.observable(function(){})
};

Jquery filtering through a multiple range of numbers

Think I'm getting stuck... I'm attempting to take a list of items and create filters based on attributes to the object. I stripped it down into an easier example of books with a cost and year. I currently have a list of books on the page and filters (checkboxes) that can be selected to only show books within a range of cost and/or year. Here is the code I have so far:
<div id="filters">
<h1>FILTERS</h1>
<div class="filter filter_cost">
<input class="target" type="checkbox" min="0" max="9" />Under $10.00<br/>
<input class="target" type="checkbox" min="10" max="19" />$10-$19<br/>
<input class="target" type="checkbox" min="20" max="29" />$20-$29<br/>
<input class="target" type="checkbox" min="30" max="39" />$30-$39<br/>
<input class="target" type="checkbox" min="40" max="1000" />$40 and Over<br/>
</div>
<div class="filter filter_year">
<input class="target" type="checkbox" min="1700" max="1799" />18th Century<br/>
<input class="target" type="checkbox" min="1800" max="1899" />19th Century<br/>
<input class="target" type="checkbox" min="1900" max="1999" />20th Century<br/>
<input class="target" type="checkbox" min="2000" max="2999" />21st Centruy<br/>
</div>
</div>
<div id="books">
<h1>BOOKS</h1>
<div class="book">
<h1>Book 1</h1>
<input type="hidden" name="cost" value="13" />
<input type="hidden" name="year" value="1997" />
</div>
<div class="book">
<h1>Book 2</h1>
<input type="hidden" name="cost" value="22" />
<input type="hidden" name="year" value="1872" />
</div>
</div>
And my jQuery (using 1.6.2):
$(document).ready(function () {
$("input.target").change(function () {
filterResults();
});
});
function filterResults(){
$(".book").each(function () {
var cost = $(this).find("input[name='cost']").val();
var year = $(this).find("input[name='year']").val();
var cover = $(this).find("input[name='cover']").val();
var isHidden = false;
//console.log("Cost in Range: "+filterRange(cost, ".filter_cost"));
//console.log("Year in Range: "+filterRange(year, ".filter_year"));
var filterCost = filterRange(cost, ".filter_cost")?showBook($(this)):hideBook($(this));
var filterYear = filterRange(year, ".filter_year")?showBook($(this)):hideBook($(this));
isHidden?"":filterCost;
isHidden?"":filterYear;
function showBook(obj) {
obj.show();
}
function hideBook(obj) {
isHidden = true;
obj.hide();
}
})
}
function filterRange(amount, elem) {
var checkedInputs = $(elem).find("input:checked").length;
var totalInputs = $(elem).find("input").length;
var inRange = function(){
$(elem).find("input:checked").each(function () {
var min = $(this).attr('min');
var max = $(this).attr('max');
if(amount >= min && amount <= max){
return true;
} else {
return false;
}
});
};
if(checkedInputs == 0 || totalInputs == checkedInputs ){
return true;
}
if(inRange()){
return true;
} else {
return false;
}
}
My issue is that in the filterRange function I'm not sure how to create a range of conditionals based on each input that is checked. So that a price range could be 10-19 and 30-39. My attempt (var inRange) was to go through each checked input, check if the cost was with in the range, then return true, else return false. I think I'm just fundamentally getting off track and unsure if this method would work at all. Any input would be much appreciated.
In the jquery each loop on dom element return statement breaks out of the loop. So your implemenation is wrong. Try this.
function filterRange(amount, elem) {
var checkedInputs = $(elem).find("input:checked").length;
var totalInputs = $(elem).find("input").length;
var returnValue = false;
$(elem).find("input:checked").each(function () {
var min = $(this).attr('min');
var max = $(this).attr('max');
if(amount >= min && amount <= max){
returnValue = true;
return true;
}
});
return (checkedInputs == 0 || totalInputs == checkedInputs || returnValue );
}
Try:
function filterRange(amount, elem) {
var checkedInputs = $(elem).find("input:checked").length;
var totalInputs = $(elem).find("input").length;
var inRange = false;
$(elem).find("input:checked").each(function () {
var min = $(this).attr('min');
var max = $(this).attr('max');
if (amount >= min && amount <= max) {
inRange = true;
return false;
}
});
if (checkedInputs == 0 || totalInputs == checkedInputs) {
return true;
}
if (inRange) {
return true;
} else {
return false;
}
}

Categories

Resources