jQuery how to DRY the similar onclick event calls - javascript

I want to listen to two input change events, when one of the changes, check the checkbox and disable the element. Likewise, it needs to roll the checkbox back to the previous state when the value of input boxes back to the default values. The click function looks like 90% resemblance, how to DRY them?
var payment = 'old payment';
var billAdr = 'old billAdr';
$('#payment').val(payment);
$('#bill-adr').val(billAdr);
$('#payment').on('input', function() {
var newPayment = $('#payment').val();
if(newPayment !== payment) {
$("#save-nxt-time").attr('checked', true);
$("#save-nxt-time").prop('disabled', true);
} else {
var newBillAdr = $('#bill-adr').val();
if(newBillAdr === billAdr) {
$("#save-nxt-time").prop('disabled', false);
$("#save-nxt-time").attr('checked', false);
}
}
});
$('#bill-adr').on('input', function() {
var newBillAdr = $('#bill-adr').val();
if(newBillAdr !== billAdr) {
$("#save-nxt-time").attr('checked', true);
$("#save-nxt-time").prop('disabled', true);
} else {
var newPayment = $('#payment').val();
if(newPayment === payment) {
$("#save-nxt-time").prop('disabled', false);
$("#save-nxt-time").attr('checked', false);
}
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="/#">
<label for="payment">payment</label>
<input type="text" id="payment" name="payment">
<br>
<label for="bill-adr">bill address</label>
<input type="text" id="bill-adr" name="bill-adr">
<br>
<input type="checkbox" id="save-nxt-time">
<label for="save">Save to next time</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

const oldPa = 'old payment';
const oldBi = 'old billAdr';
const $next = $('[name="save-nxt-time"]');
const $paym = $('[name="payment"]').val(oldPa);
const $bill = $('[name="bill-adr"]').val(oldBi);
const $paBi = $paym.add($bill);
$paBi.on('input', () => {
const bool = $paym.val() !== oldPa || $bill.val() !== oldBi;
$next.prop({disabled: bool, checked: bool});
});
form label {display: block;}
<form action="/#">
<label><span>Payment</span> <input type="text" name="payment"></label>
<label><span>Billing address</span> <input type="text" name="bill-adr"></label>
<label><input type="checkbox" name="save-nxt-time"> <span>Save to next time</span></label>
<input type="submit" value="Submit">
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Like this ?
// first load
checkTest(true);
$('#payment, #bill-adr').on('input', function() {
checkTest(false, $(this).attr('id'), $(this).val(), "#save-nxt-time");
});
function checkTest(init = false, id, value, input) {
var payment = 'old payment', billAdr = 'old billAdr';
if (init === true) {
$('#payment').val(payment);
$('#bill-adr').val(billAdr);
}
console.clear();
console.log(value);
if (value === billAdr || value === payment) {
$(input).prop('disabled', false).attr('checked', false);
} else {
$(input).attr('checked', true).prop('disabled', true);
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="/#">
<label for="other">payment</label>
<input type="text" id="payment" name="fname">
<br>
<label for="other">bill address</label>
<input type="text" id="bill-adr" name="fname">
<br>
<input type="checkbox" id="save-nxt-time">
<label for="save">Save to next time</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

how about putting the text and ids of the elements in an array and looping through
run snippet below
$(document).ready(function() {
const p = new PaymentMgr();
p.init();
});
class PaymentMgr {
constructor() {
this.data = [{
text: 'old payment',
id: 'payment'
}, {
text: 'old bill address',
id: 'bill-adr'
}];
}
init() {
this.data.forEach(element => $(`#${element.id}`)
.val(element.text)
.on("input", (e) => {
['checked', 'disabled'].forEach(attribute =>
$("#save-nxt-time")
.attr(attribute, $(e.target).val() !== element.text))
})
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/#">
<label for="payment">payment</label>
<input type="text" id="payment" name="payment">
<br>
<label for="bill-adr">bill address</label>
<input type="text" id="bill-adr" name="bill-adr">
<br>
<input type="checkbox" id="save-nxt-time">
<label for="save">Save to next time</label><br><br>
<input type="submit" value="Submit">
</form>

Related

Uncheck all checkboxes if "Other" checkbox is checked and get value

So, I have 4 checkboxes:
Heating
AC
Cold Chain
Others
The condition is, you can multiple check the three: Heating, AC, and Cold Chain. But when you check on "Other", the three will be unchecked. And when you check again on any of the three, the Other checkbox will be unchecked.
When the Others is checked, a "Please specify" input text will appear.
And in the summary, Looking for solutions in Others - [value]
This is my fiddle
$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox() {       
$("input:checkbox").change(function() {                 
selectedCB = [];        
notSelectedCB = [];                
CountSelectedCB.length = 0;        
$("input:checkbox").each(function() {            
if ($(this).is(":checked")) {                
CountSelectedCB.push($(this).attr("value"));            
}        
});                
$('input[name=solutions]').val(CountSelectedCB).blur();    
});
}   
$(document).ready(displayRadiobox);
CountSelectedRB = [];
function displayRadiobox() {       
$("input:radio").change(function() {                 
selectedRB = [];        
notSelectedRB = [];                
CountSelectedRB.length = 0;        
$("input:radio").each(function() {            
if ($(this).is(":checked")) {                
CountSelectedRB.push($(this).attr("value"));            
}        
});                
$('input[name=existing]').val(CountSelectedRB).blur();     
});
}
$('#solutions, #existing').bind('keyup blur', function() {            
$('#summary').val('You are looking for solutions in ' +                               $('#solutions').val() +                               (' \n') +                              'Are you using an existing customer? ' +                               $('#existing').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> Looking for a solutions in:<br>
<input type="checkbox" value="Heating">Heating<br>
<input type="checkbox" value="Ac">AC<br>
<input type="checkbox" value="Cold Chain">Cold Chain<br>
<input type="checkbox" value="Others">Others<br>
</div>
<input name="specify" type="text" id="specify" style="display: none">
<input name="solutions" type="text" id="solutions">
<div><br>Are you an exisiting customer?<br>
<input type="radio" value="Yes" name="radio">Yes<br>
<input type="radio" value="No" name="radio">No
</div>
<input name="existing" type="text" id="existing">
<br><br> Summary:
<br>
<textarea type='text' id="summary"></textarea>
Made a simple example for you how you can do this using the prop() and siblings() functions.
Added some classes for better selectors.
$('#wrapper .some-checkbox').on('change', function() {
var $this = $(this);
if ($this.prop('checked')) {
if ($this.is('.some-others')) {
$this.siblings().prop('checked', false);
}
else {
$this.siblings('.some-others').prop('checked', false);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
<input class="some-checkbox" type="checkbox" value="Heating">Heating<br>
<input class="some-checkbox" type="checkbox" value="Ac">AC<br>
<input class="some-checkbox" type="checkbox" value="Cold Chain">Cold Chain<br>
<input class="some-checkbox some-others" type="checkbox" value="Others">Others<br>
</div>
You need to check if the checkbox Others is checked, then uncheck the other checkboxes with $('<your-checkbox->').prop('checked', false);
For example:
$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox(){    
    $("input:checkbox").change(function() {          
        selectedCB = [];
        notSelectedCB = [];
        
        CountSelectedCB.length = 0;
        $("input:checkbox").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedCB.push($(this).attr("value"));
if ($(this).attr("value") === "Others") {
CountSelectedCB = []; // reset result
$("input:checkbox").each(function() {
if ($(this).attr("value") !== "Others") {
$(this).prop('checked', false); // uncheck
}
});
$('input[name=solutions]').hide(); // toggle input
$('input[name=specify]').show(); // toggle input
}
            }
        });
        
        $('input[name=solutions]').val(CountSelectedCB).blur();
    });
}    
$(document).ready(displayRadiobox);
CountSelectedRB = [];
function displayRadiobox(){    
    $("input:radio").change(function() {          
        selectedRB = [];
        notSelectedRB = [];
        
        CountSelectedRB.length = 0;
        $("input:radio").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedRB.push($(this).attr("value"));
            }
        });
        
        $('input[name=existing]').val(CountSelectedRB).blur(); 
    });
}
$('#solutions, #existing').bind('keyup blur', function() {
        
    $('#summary').val('You are looking for solutions in ' + 
                             $('#solutions').val() + 
                             (' \n') +
                             'Are you using an existing customer? ' + 
                             $('#existing').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> Looking for a solutions in:<br>
<input type="checkbox" value="Heating">Heating<br>
<input type="checkbox" value="Ac">AC<br>
<input type="checkbox" value="Cold Chain">Cold Chain<br>
<input type="checkbox" value="Others">Others<br>
</div>
<input name="specify" type="text" placeholder="Please specify" id="specify" style="display: none">
<input name="solutions" type="text" id="solutions">
<div><br>Are you an exisiting customer?<br>
<input type="radio" value="Yes" name="radio">Yes<br>
<input type="radio" value="No" name="radio">No
</div>
<input name="existing" type="text" id="existing">
<br><br>
Summary:<br>
<textarea type='text' id="summary"></textarea>
Well, I modified your displayCheckbox() function. Please try like this. I think your problem will be solved.
function displayCheckbox(){    
$("input:checkbox").change(function() {
selectedCB = [];
notSelectedCB = [];
CountSelectedCB.length = 0;
if($('input:checkbox[value="Others"]').is(":checked")){
$('input:checkbox').not(this).prop('checked', false);
CountSelectedCB.length = 0;
CountSelectedCB.push($(this).attr("value"));
}else{
$("input:checkbox").each(function() {
if ($(this).is(":checked")) {
CountSelectedCB.push($(this).attr("value"));
}
});
}
$('input[name=solutions]').val(CountSelectedCB).blur();
});
}
Thank you.
  
I've updated your Fiddle code. Please see this, it will solve your problem.
Here is the snippet:
$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox() {       
$("input:checkbox").change(function() {                 
selectedCB = [];        
notSelectedCB = [];
selectedValue = $(this).attr("value");                
CountSelectedCB.length = 0;
if (selectedValue === "Others" && $(this).is(":checked")) {
uncheckAllCheckBox();
$(this).prop('checked', true);
CountSelectedCB.push(selectedValue);
} else {
$("input:checkbox").each(function() {
if ($(this).attr("value") === "Others")
$(this).prop('checked', false);
if ($(this).is(":checked")) {
CountSelectedCB.push($(this).attr("value"));
}
});
}                        
$('input[name=solutions]').val(CountSelectedCB).blur();    
});
}
function uncheckAllCheckBox() {
$("input:checkbox").each(function() {
$(this).prop('checked', false);
CountSelectedCB.length = 0;
});
}
$(document).ready(displayRadiobox);
CountSelectedRB = [];
function displayRadiobox() {       
$("input:radio").change(function() {                 
selectedRB = [];        
notSelectedRB = [];                
CountSelectedRB.length = 0;        
$("input:radio").each(function() {            
if ($(this).is(":checked")) {                
CountSelectedRB.push($(this).attr("value"));            
}        
});                
$('input[name=existing]').val(CountSelectedRB).blur();     
});
}
$('#solutions, #existing').bind('keyup blur', function() {            
$('#summary').val('You are looking for solutions in ' +                               $('#solutions').val() +                               (' \n') +                              'Are you using an existing customer? ' +                               $('#existing').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> Looking for a solutions in:<br>
<input type="checkbox" value="Heating">Heating<br>
<input type="checkbox" value="Ac">AC<br>
<input type="checkbox" value="Cold Chain">Cold Chain<br>
<input type="checkbox" value="Others">Others<br>
</div>
<input name="specify" type="text" id="specify" style="display: none">
<input name="solutions" type="text" id="solutions">
<div><br>Are you an exisiting customer?<br>
<input type="radio" value="Yes" name="radio">Yes<br>
<input type="radio" value="No" name="radio">No
</div>
<input name="existing" type="text" id="existing">
<br><br> Summary:
<br>
<textarea type='text' id="summary"></textarea>
Updated JSFiddle Code

Using jQuery to validate checkboxes and input text values

I need your help,
Is there a way one can possible use the all so powerful jQuery to validate the following conditions before enabling button?
If the user inputs a value in the text box and then checks one of the checkboxes, then enable the button
If the user already has a value present in the text, and then checks one of the checkboxes, then enable the button
How can this be written in jQuery, from my perspective this would some lenghty form field checking no?
Here's the HTML markup:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date3">
</body>
</html>
This might get you started. You can make the field validation as complex or simple as you wish.
$('input[type=checkbox]').click(function(){
var tmp = $(this).next('input').val();
//validate tmp, for example:
if (tmp.length > 1){
//alert('Text field has a value');
$('#mybutt').prop('disabled',false);
}else{
//alert('Please provide a long value in text field');
$('#mybutt').prop('disabled', true);
$(this).prop('checked',false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="mybutt" type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date3">
Try this way..
$('input').on('change input', function() {
$input = $('input');
$button = $('input[type="button"]');
var arr = [];
$input.each(function() {
if ($(this).attr('type') !== 'button') {
arr.push(check($(this)));
arr.indexOf(false) == -1 ? $button.removeAttr('disabled') : $button.attr('disabled', 'disabled');
}
})
})
function check(elem) {
if ($(elem).attr('type') == 'checkbox' && $(elem).is(':checked')) return true;
if ($(elem).attr('type') == 'text' && $(elem).val().trim().length) return true;
return false;
}
$('input').on('change input', function() {
$input = $('input');
$button = $('input[type="button"]');
var arr = [];
$input.each(function() {
if ($(this).attr('type') !== 'button') {
arr.push(check($(this)));
arr.indexOf(false) == -1 ? $button.removeAttr('disabled') : $button.attr('disabled', 'disabled');
}
})
})
function check(elem) {
if ($(elem).attr('type') == 'checkbox' && $(elem).is(':checked')) return true;
if ($(elem).attr('type') == 'text' && $(elem).val().trim().length) return true;
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date3">

Disable submit button until all form inputs have data

I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">

Using Buttons in JavaScript

How can you create a button so that whenever you click on it a question changes to its uppercase form, then when you click the button again it changes to its lowercase form. I believe I should create a function of some sort, just not sure how. Below is what I have tried so far:
function upper_lower() {
if (windows.document.f1.value=="lower") {
windows.document.value = "UPPER"
windows.document.question = windows.document.question.toUpperCase();
windows.document.queston.size="40"
} else {
windows.document.value = "lower"
windows.document.question = windows.document.question.toLowerCase()
windows.document.queston.size="30"
}
}
Question
<input type="text" name="question" value="Favorite food?" size="25">
readonly /input
<input type="button" name="f1" value="UPPER" onClick = "upper_lower">
Try this
Html:
Question <input type="text" name="question" id="question1" value="Favorite food?" size="25" readonly></input>
<input type="button" name="f1" id="button1" value="UPPER" onClick="upper_lower()"></input>
js:
var toggle = true;
function upper_lower(){
var question = document.getElementById('question1'),
button = document.getElementById('button1');
if(toggle){
question.value = question.value.toUpperCase();
button.value = 'LOWER';
toggle = false;
} else{
question.value = question.value.toLowerCase();
button.value = 'UPPER';
toggle = true;
}
}
Snippet below (indented weird for some reason)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
Question <input type="text" name="question" id="question1" value="Favorite food?" size="25" readonly></input>
<input type="button" name="f1" id="button1" value="UPPER" onClick="upper_lower()"></input>
</body>
<script>
var toggle = true;
function upper_lower(){
var question = document.getElementById('question1'),
button = document.getElementById('button1');
if(toggle){
question.value = question.value.toUpperCase();
button.value = 'LOWER';
toggle = false;
} else{
question.value = question.value.toLowerCase();
button.value = 'UPPER';
toggle = true;
}
}
</script>
</html>
Try This Updated Code...
<script type="text/javascript">
var flag = 0;
function changecase() {
if (flag == 0) {
document.form1.instring.value = document.form1.instring.value.toUpperCase();
document.form1.Convert.value = 'To Lower'
flag = 1;
}
else
{
document.form1.instring.value = document.form1.instring.value.toLowerCase();
document.form1.Convert.value = 'To Upper'
flag = 0;
}
}
</script>
<form name="form1" method="post">
<input name="instring" type="text" value="this is the text string" size="30">
<input type="button" name="Convert" value="To Upper " onclick="changecase();">
</form>

How to show form fields on keyup

I've been working on this for weeks now and I can't seem to get the hang of this. I'm trying to show the hidden fields only when the previous fields are entered. Here's my example code:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1" />
<br/>
<label>Field 2:</label>
<input type="text" class="field2" />
<br/>
<label>Field 3:</label>
<input type="text" class="field3" />
<br/>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4" />
<br/>
<label>Field 5:</label>
<input type="text" class="field5" />
<br/>
<label>Field 6:</label>
<input type="text" class="field6" />
<br/>
</div>
<div id="group3">
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 9:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>
</form>
CSS
#group2 {
visibility: hidden;
}
#group3 {
visibility: hidden;
}
Script
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
CheckSubmit();
});
function CheckSubmit() {
var x = true;
$('#group1').find('input[type="text"]').keyup(function () {
if ($(this).val().length === 0) {
x = false;
return;
}
});
if (x) {
$('#group2').css('visibility', 'visible');
$('#group3').css('visibility', 'visible');
} else {
$('#group2').css('visibility', 'hidden');
$('#group3').css('visibility', 'hidden');
}
CheckSubmit();
});
I'm not sure what I'm doing wrong here. Can someone please assist?
I changed your code a bit. I stored the relevant selectors in variables, so you don't need to do a lot of re-querying every time something changes.
Here's the updated code:
JavaScript
var inputs = $('#group1').find('input[type="text"]');
var hidden = $('#group2, #group3');
inputs.keyup(function() {
var test = true;
inputs.each(function(key, value) {
if (!$(this).val().length) {
test = false;
return false;
}
});
hidden.css('visibility', ( test ? 'visible' : 'hidden' ) );
});
Demo
Try before buy
You can make this more dynamic by checking the inputs in the current div and if they all have a value, then show the next div (if there is one).
If they clear a value, then hide all the later divs.
$(document).ready(function() {
// you can restrict this to inputs in a specific div or just any input
$('#group1 input').on('keyup', function () {
var parentDiv = $(this).closest('div')
var hasValues = parentDiv.find('input').filter(function() {
return this.value == '';
}).length == 0;
if(hasValues) {
//parentDiv.next().css('visibility', 'visible'); // show just the next section
parentDiv.nextAll().css('visibility', 'visible'); // show all later sections
} else {
parentDiv.nextAll().css('visibility', 'hidden');
}
});
});
DEMO
I made a quick pen with a solution. It may not be the prettiest but it get's it done. Basically on every keyup event I check #group1's children for their value length and if they all have a length that's more than 0 I change a flag in an array. If all 3 flags are true I show #group2.
Here's the pen
$('#group2').hide();
$('#group3').hide();
$('#group1').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group1 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group2').show();
}
});
$('#group2').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group2 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group3').show();
}
});
Hope it helps :D
If I understand your question well, you want to show the fields in #group2/-3 if all the fields in the previous fields have a value. Using a few data-*-attributes (see MDN), you can create a handler like this (if you prefer: jsFiddle, containing a more complete example):
$('[data-nextgroup] [type=text]').on('keyup', function (e){
var fieldgroup = $(this.getAttribute('data-group'))
,fields = fieldgroup.find('[type=text]')
,canshow = fields.length ===
fields.filter( function (i,el) { return el.value.length; } ).length;
void( canshow && $(fieldgroup.attr('data-nextgroup')).fadeIn() );
});
[data-hidden] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="group1" data-nextgroup="#group2">
<label>Field 1:</label>
<input type="text" class="field1" data-group="#group1"/>
<br/>
<label>Field 2:</label>
<input type="text" class="field2" data-group="#group1"/>
<br/>
<label>Field 3:</label>
<input type="text" class="field3" data-group="#group1"/>
<br/>
</div>
<div id="group2" data-nextgroup="#group3" data-hidden>
<label>Field 4:</label>
<input type="text" class="field4" data-group="#group2"/>
<br/>
<label>Field 5:</label>
<input type="text" class="field5" data-group="#group2"/>
<br/>
<label>Field 6:</label>
<input type="text" class="field6" data-group="#group2"/>
<br/>
</div>
<div id="group3" data-groups data-hidden>
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 8:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>

Categories