I am trying to run the following function:
var getFavorite = function(){
var favCheck = document.querySelector("#fav");
var status;
if(favCheck.checked){
status = "Yes!";
}else{
status = "No";
}
return status;
};
The html form contains the following:
<form action="#" id="flavorForm">
<ul id="errors"></ul>
<div data-role="fieldcontain">
<label for="drug">Flavor: </label>
<input type="text" name="flavor" id="flavor" class="required" />
</div>
<div data-role="fieldcontain">
<label for="favorite">Favorite?</label>
<input type="checkbox" id="favorite" value="Yes" class="checkbox" />
</div>
<div data-role="fieldcontain">
<label for="notes">Notes: </label>
<textarea name="notes" id="notes"></textarea>
</div>
<input type="submit" value="Save Flavor" id="submitFlavor" data-theme="b" />
</form>
And the values for favCheck should come from the second ... block of the form. But I'm getting a 'TypeError: favCheck is null' whenever I input a value on the form, whether I check the checkbox or not. I am using jQuery to retrieve the values. Any suggestions are appreciated. Thanks.
You misspelled the id name. Please use #favorite instead of #fav
Try this,
var getFavorite = function(){
var favCheck = document.querySelector("#favorite");
var status;
if(favCheck.checked){
status = "Yes!";
}else{
status = "No";
}
return status;
};
DEMO
HTML
<input type="checkbox" id="checkme" checked="checked" />
jQuery
$('#checkme').change(function () {
var checkbox = $('#checkme').prop('checked');
if (checkbox) {
alert('checkbox is checked');
} else {
alert('checkbox is not checked');
}
});
http://jsfiddle.net/rjE8P/
Since you're using an ID rather than a class
favcheck = document.getElementById('fav');
Also, you need to actually use that ID fav rather than favorite as it is now.
$('#favorite').change(function(){
var status;
if($(this).is(':checked')) {
status = 'Yes';
}
else{
status = "No";
}
alert(status);
});
Related
I want to save state of selected checkbox to a file (whether as a text file or something else) that contains information on what was checked.
I can't use localstorage or cookies, I need it saved as external file so I can save (and load) several files with different checkmarks selected.
It's pretty straightforward, but I can't find any solution that does exactly this, so any help is appreciated.
Simple snippet for reference:
div {
display: table;
}
span {
display: block;
}
input,
label {
display: inline-block;
}
<div>
<span>
<input id="box1" type="checkbox" />
<label for="box1">Checkbox 1</label>
</span>
<span>
<input id="box2" type="checkbox" checked/>
<label for="box2">Checkbox 2</label>
</span>
<span>
<input id="box3" type="checkbox" />
<label for="box3">Checkbox 3</label>
</span>
</div>
<button id="_save">Save</button>
<button id="_load">Load</button>
Ok, I have a solution that does what I needed.
So when you check everything you want from your form, you can save it into localstorage and THEN you can export localstorage as JSON. I found this google extension that handles import and export for the localstorage (in a textual file), but you can always go extra mile and write your own script for that.
Here is JSFiddle for the localstorage so can save whatever input you want and here is chrome extension that handles import and export LocalStorage Manager.
Javascript:
;(function($) {
$.fn.toJSON = function() {
var $elements = {};
var $form = $(this);
$form.find('input, select, textarea').each(function(){
var name = $(this).attr('name')
var type = $(this).attr('type')
if(name){
var $value;
if(type == 'radio'){
$value = $('input[name='+name+']:checked', $form).val()
} else if(type == 'checkbox'){
$value = $(this).is(':checked')
} else {
$value = $(this).val()
}
$elements[$(this).attr('name')] = $value
}
});
return JSON.stringify( $elements )
};
$.fn.fromJSON = function(json_string) {
var $form = $(this)
var data = JSON.parse(json_string)
$.each(data, function(key, value) {
var $elem = $('[name="'+key+'"]', $form)
var type = $elem.first().attr('type')
if(type == 'radio'){
$('[name="'+key+'"][value="'+value+'"]').prop('checked', true)
} else if(type == 'checkbox' && (value == true || value == 'true')){
$('[name="'+key+'"]').prop('checked', true)
} else {
$elem.val(value)
}
})
};
}( jQuery ));
//
// DEMO CODE
//
$(document).ready(function(){
$("#_save").on('click', function(){
console.log("Saving form data...")
var data = $("form#myForm").toJSON()
console.log(data);
localStorage['form_data'] = data;
return false;
})
$("#_load").on('click', function(){
if(localStorage['form_data']){
console.log("Loading form data...")
console.log(JSON.parse(localStorage['form_data']))
$("form#myForm").fromJSON(localStorage['form_data'])
} else {
console.log("Error: Save some data first")
}
return false;
})
});
HTML:
<form action="#" method="get" id="myForm">
<input type="text" name="textfield">
Textfield
<br/>
<input type="number" name="numberfield" />
Numberfield
<br/>
<input type="radio" name="radiofield" value="1" />
<input type="radio" name="radiofield" value="2" />
<input type="radio" name="radiofield" value="3" />
Radiofields
<br/>
<input type="checkbox" name="checkfield">
<input type="checkbox" name="checkfield2">
<input type="checkbox" name="checkfield3">
Checkboxes
<br/>
<select name="selectbox">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Selectbox
<br/>
<textarea name="textarea"></textarea>
Textarea
<br/>
<hr/>
<button id="_save">Save</button>
<button id="_load">Load</button>
<input type="reset">
</form>
I have a html form with such structure:
...
<select name="Employee">
<option>a</option>
<option>b</option>
</select>
<input type="checkbox" name="email" value="Yes" unchecked>Include Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show()" id="refresh">
...
And a div:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:</div>
<div class="ft_tbl_data"></div>
</div>
How can I show my values in div section by pressing the button without reloading the entire page?
I know Javascript a bit, but unfortunately, didn't find the answer yet.
Thank you in advance!
Here is one solution, using unobtrusive vanilla javascript.
The function showData() runs when the button is clicked.
Then, the function showData():
gets the Boolean value of each checkbox (either true if checked or false if unchecked)
rewrites the Boolean value as a string (a value of true becomes 'Yes' and a value of false becomes 'No')
rewrites the relevant data field, including the string.
function showData() {
var emailValue = document.querySelector('input[value="email"]').checked;
var phoneValue = document.querySelector('input[value="phone"]').checked;
var data = document.getElementsByClassName('data')[0];
var dataFields = data.getElementsByTagName('div');
if (emailValue === true) {emailValue = 'Yes';} else {emailValue = 'No';}
if (phoneValue === true) {phoneValue = 'Yes';} else {phoneValue = 'No';}
for (var i = 0; i < dataFields.length; i++) {
switch (i) {
case (0) : dataFields[i].textContent = 'E-Mail: ' + emailValue; break;
case (1) : dataFields[i].textContent = 'Phone: ' + phoneValue; break;
}
}
}
var button = document.querySelector('input[type="button"]');
button.addEventListener('click',showData,false);
form, .data, label, input[type="button"] {
display: block;
}
form, .data {
float: left;
width: 200px;
}
input[type="button"] {
margin-top: 24px;
}
<form>
<label><input type="checkbox" name="contact" value="email" unchecked>Include Email Contact</label>
<label><input type="checkbox" name="contact" value="phone" unchecked>Include Phone Contact</label>
<input type="Button" value="Generate">
</form>
<div class="data">
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_meta">Phone:</div>
</div>
set some IDs for your divs you wish to take/assign values from/to and put this code
IncludeEmailCheckBox is for your "include Email" checkbox
EmailToDiv is for your div to get the email
EmailFromDiv is for your input for Email
IncludePhoneCheckBox is for your "include Phone" checkbox
PhoneToDiv is for your div to get the Phone
PhoneFromDiv is for your input for Phone
function show(){
if (document.getElementById("IncludeEmailCheckBox").checked){
document.getElementById("EmailToDiv").innerHTML = document.getElementById("EmailFromDiv").innerHTML ;}
if (document.getElementById("IncludePhoneCheckBox").checked){
document.getElementById("PhoneToDiv").innerHTML = document.getElementById("PhoneFromDiv").innerHTML ;}
return false;
}
Remember to change IDs as nessesary
Get elements of class by calling document.getElementsByClassName(class_name)
Example javascript code below
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var x = document.getElementsByClassName("ft_name");
x[0].innerHTML = form.name.value;
x = document.getElementsByClassName("ft_tbl_meta");
x[0].innerHTML = form.email.value; // name email is one provided in form
// Do same for all other classes
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<input type="checkbox" name="email" value="Yes" unchecked>Include
Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show(this.form)" id="refresh">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
here is your view (I updated) using Jquery:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:<span id="email_here"></span></div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:<span id="phone_here"></span></div>
<div class="ft_tbl_data"></div>
</div>
Now fetching and printing values:
var Employee = $( "select[name=Employee]" ).val();
$('.ft_name').html(Employee);
var email = $( "input[name=email]" ).val();
$('#email_here').html(email);
var phone = $( "input[name=phone]" ).val();
$('#phone_here').html(phone);
var jobTitle = $( "input[name=jobTitle]" ).val();
$('.ft_pos').html(jobTitle);
I'm trying to hide part of the form with the button disabled and have the user click on the button to show rest of form when previous fields are filled in. Can anyone help? Here's my code as an example:
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 align="center">
<button id="show_form" onClick = "this.style.display= 'none'" disabled="disabled">
Enter Billing Info</button>
</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>
</form>
JQUERY
<script>
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
$("#show_form").prop("disabled", true);
$("#group2").hide();
$("#show_form").show();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
</script>
Try this jQuery:
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
/* This will hide the bottom form and disable the button again if
* any of the field above will be emptied.
* NOTE: This will just hide the form; it will not clear the fields.
*/
$("#show_form").prop("disabled", true);
$("#group2").hide();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
This will enable the button when all the fields in the initial form are filled. Then the user will be able to click on the button to see the rest of the form.
You just need to loop through each input and check if a value is set when the button is clicked like this:
$('#show_form').click(function () {
var fields = $('.js-field');
var pass = true;
for (var i = 0; i < fields.length; i++) {
if (!$(fields[i]).val()) {
pass = false;
}
}
if (pass === true) {
$('#group2').show();
}
});
I also needed to add some classes to your html:
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1 js-field"/><br/>
<label>Field 2:</label>
<input type="text" class="field2 js-field"/><br/>
<label>Field 3:</label>
<input type="text" class="field3 js-field"/><br/>
</div>
<button type="button" id="show_form" value="Show_Form">Enter Billing
Info</button>
<div id="group2" style="display: none;">
<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>
</form>
To see it in action visit this fiddle.
You can add some logic to the click event and check all the input fields to have a value like this
$("#show_form").click(function(){
var allFilled = true;
$('#group1').find('input').each(function(){
//if someone is empty allFilled will keep false
if(this.value === ''){
allFilled = false;
//this breaks the each
return false;
}
});
if(allFilled){
$("#group2").show();
}
});
Keep in mind the previous code only work with input fields.
I have a login form.
Field: Username textbox, password text box, 2 check boxes, submit button--- everything inside a form.
submit button initially disabled. It is enabled only when username, password or AT LEAST any one checkbox is checked. button gets enabled when username & password fields are entered. no change happens even if checkbox is checked or unchecked.
<form class="form-horizontal" role="form" action="page2.html">
<div class="form-group">
<label for="txtusername" class="col-sm-4 control-label ">Username</label>
<div class="col-sm-8">
<input type="text" class="form-control textboxprop" id="txtusername" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="txtpassword" class="col-sm-4 control-label ">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control textboxprop" id="txtpassword" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<div class="checkbox">
<input id="chk" type="checkbox" >chk1
<input id="chk" type="checkbox" >chk2
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" id="signin" class="btn btn-default" disabled>Sign in</button>
</div>
</div>
</form>
This is the form. Below given is the javascript function I use.
var $input = $('input'),
$register = $('#signin');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
You need to listen checkboxes change event too. Try this code:
var $input = $('input'),
$check = $input.filter(':checkbox'),
$register = $('#signin');
$register.attr('disabled', true);
$input.on('keyup change', function() {
var trigger = false;
$input.each(function() {
if (this.type != 'checkbox' && !$(this).val()) {
trigger = true;
}
});
$register.prop('disabled', trigger || !$check.filter(':checked').length);
});
Demo: http://jsfiddle.net/jy3UR/1/
Your HTML is invalid. A <label> is closed which wasn't started and you have a duplicate ID 'chk'...
You need to put it in the onload event of the document and indeed as #dfsq already stated, you need to add a check for the checkboxes too, like so:
$(document).ready(function() {
var $input = $('input'),
$register = $('#signin');
$chk = $('input[type=checkbox]');
$register.attr('disabled', true);
$input.on('keyup change', function() {
var trigger = false;
$input.each(function() {
if (this.type != 'checkbox' && !$(this).val()) {
trigger = true;
}
});
$register.prop('disabled', trigger || !$chk.filter(':checked').length);
});
})
otherwise it will get executed when the DOM has not fully loaded yet and your fields will not be available...
DEMO
First of all you have used same id for both the check box.
rename it like below
<input id="chk1" type="checkbox" >chk1</label>
<input id="chk2" type="checkbox" >chk2</label>
and modify your code like below :
<script>
$(document).ready(function() {
var $input = $('input'),
$register = $('#signin');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
var checked = $("input[type='checkbox']:checked");
if(checked.length >0) // check if atleast one checkbox checked
trigger = true;
if(!trigger){
if(!$(this).val()) {
trigger = true;
}
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
</script>
You should try this simple solution :
jQuery(function($) {
$('form input').on('change',function() {
isDisabled = !(($('#txtusername').val().length > 0 && $('#txtpassword').val().length > 0) || $('input[type="checkbox"]:checked').length > 0);
$('#signin').attr('disabled', isDisabled);
});
});
It does its job.
So my form throws up the correct error when no email is given. But when a correct email is put into the field, it wont submit. Where am I going wrong here? Thanks for any advice and help!
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$(document).ready(function(){
$("#submitbutton").click(function(e){
var none_answered = true;
var eMailToTest = $('#email').val();
if(!myEmailRegEx.test(eMailToTest)) {
e.preventDefault();
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
}
else {
$('#email').removeClass('error');
return true;
}
});
});
<style type="text/css">
.error
{
color:red;
}
#texthere
{
color:red;
}
</style>
<body>
<form>
<label id="email" class="req"><span>*</span>Email:</label>
<input id="email" class="req" name="email" value="" type="email"></br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" formaction="http://www.utah.edu/">
</form>
</body>
You have duplicate IDs, for the label and input field. Because of that the value of eMailToTest was always blank.
<label for="email" class="req"><span>*</span>Email:</label>
Demo: Fiddle
Try to do like this:
$("#submitbutton").click(function (e) {
e.preventDefault();
var none_answered = true;
var eMailToTest = $('#email').val();
if (!myEmailRegEx.test(eMailToTest)) {
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
} else {
$('#email').removeClass('error');
$('form').submit();
}
});
Also, seem like your none_answered variable is redundant here.
Try this change id of label
<form action="http://www.utah.edu/">
<label class="req"><span>*</span>Email:</label> // Here duplicate id removed
<input id="email" class="req" name="email" value="" type="email">
</br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" />
</form>
Script
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#submitbutton").click(function(e){
e.preventDefault();
var none_answered = true;
var eMailToTest = $('#email').val();
if(!eMailToTest.match(myEmailRegEx)) {
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
console.log('if')
}
else {
console.log('else')
$('#email').removeClass('error');
$(this).closest('form').submit();
}
});
DEMO
You did a few mistakes.
Use event submit on forms (not click event)
You used id attribute on label and email. ID can be used only once on page.
var eMailToTest = $('#email').val();
It returned value of first element with ID email. So it's label (which has no value). You want input element instead.
Here is the working code.
HTML:
<form>
<label for="email" class="req"><span>*</span>Email:</label>
<input id="email" class="req" name="email" value="" type="text"><br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" formaction="http://www.utah.edu/">
</form>
Javascript:
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
(function(){
$("form").on('submit', function(e){
var eMailToTest = $('#email').val();
if(!myEmailRegEx.test(eMailToTest)) {
e.preventDefault();
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
} else {
$('#email').removeClass('error');
}
});
})();
Also none_answered variable is redundant here.
Working example.
Hope this helps :)