Save and load checkboxes state to file - javascript

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>

Related

How to use global variable so i can use it on my javascript module

i want to get all of this input values to my budget app
but i have problem to get values of the radio button because it says its undefined. i create global function to get by radio button value. but the others is in javascript module.
https://jsfiddle.net/8k3gw7ty/
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
Actually there was no default value for your val variable. Since val will only get value when you click on the checkbox (according to your code).
Also you were returning val which isn't necessary. I've also removed the budgetController.
Hope this'll help.
let val = 'inc'; // default value
function getButtonValue() {
var type = document.getElementsByName("type");
if (type[0].checked) {
val = type[0].value
} else if (type[1].checked) {
val = type[1].value
}
}
const domController = (function() {
return {
getInput: function() {
return {
type: val,
description: document.querySelector(".input_description").value || 0,
value: parseFloat(document.querySelector(".input_value").value) || 0
}
}
}
})();
const controller = (function( UI) {
var ctrlAddItem = function() {
var input = UI.getInput();
console.log(input);
}
document.querySelector(".addbtn").addEventListener("click", ctrlAddItem)
document.addEventListener("keypress", function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
})( domController);
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
<button><i class="fas fa-check addbtn">Save</i></button>

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">

How to use a checkbox to show more options of a form and change the action attribute of the form?

Hi I am creating a website that has a form to search rooms. I wanted to make it so a checkbox, when clicked, show new options AND change the action ="" attribute of the form.
<form class="form-horizontal" action="reservation?action=listRooms" method="POST">
<label for="">Date </label>
<div class="datepicker ll-skin-nigran hasDatepicker">
<input class="form-control" type="text" placeholder="14/03/2016" name="dateReservation" id="date" required="required"/>
</div>
<br />
<div>
<input type="checkbox" name="choice-for" id="choice-form">
<label for="choice-for">Show More Options.</label>
<div class="reveal-if-active">
<label for="">Slots</label>
<select name="slot" name ="slot" id="slot" >
<option value="">Choose a slot </option>
<option value="8h-9h30">8h00-9h30</option>
<option value="9h30-11h">9h30-11h00</option>
<option value="11h-12h30h">11h00-12h30h</option>
<option value="12h30-14h">12h30-14h00</option>
<option value="14h-15h30">14h00-15h30</option>
<option value="15h30-17h">15h30-17h00</option>
<option value="17h-18h30">17h00-18h30</option>
</select>
<br />
<label for="">Display Screens</label>
<input class="form-control" type="text" placeholder=" 26 pouces" name="screen" id="screen" />
<br />
<label for="">CPU</label>
<input class="form-control" type="text" placeholder="Intel Core i5 " name="processor" id="processor" />
<br />
<label for="">RAM</label>
<input class="form-control" type="text" placeholder=" 2Go de RAM ?" name="ram" id="ram" />
<br />
<input type="submit" value="Réserver" class="btn btn-primary" />
</div>
I tried then to use a javascript(JQuery) script to satisfy my expectations:
<script>
$(function() {
$( "#date" ).datepicker({ dateFormat: 'dd/mm/yy' });
});
$("#choice-form").change(function() {
//there i need to know when the checkbox is changed dynamically so the attribute can change too.
$("#form-horizontal).attr("reservation?action=listRooms");
});
var FormStuff = {
init: function() {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function() {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function() {
$(".require-if-active").each(function() {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
} else {
el.prop("required", false);
}
});
}
};
FormStuff.init();
</script>
Try this:
$("#choice-form").change(function() {
// If checkbox checked
if ( $('#choice-form').is(':checked') ) {
// Set new form action
$('#form-horizontal').attr('action', 'reservation?action=listRooms');
// Reveal additional options
$('.reveal-if-active').show(); // or call .css() with appropriate options
}
});
Ok, let's say you want to add the id(you can use name as well) and value to the action parameter from the form...
$(document).on('click','.checkboxClass',function(){
var id = $(this).attr('id');
var val = $(this).val();
var selectedVal = '&'+id+'='+val;
var methodUrl = $('form.form-horizontal').attr('action');
if($(this).is(':checked')){
methodUrl+= selectedVal;
}
else{
methodUrl = methodUrl.replace(selectedVal,'');
}
$('form.form-horizontal').attr({'action':methodUrl});
});
Now let's say you have a checkbox with the id="myId" and value="myValue", if you check it, the action parameter will become action="reservation?action=listRooms&myId=myValue"
Is this what you asked for?

Adding Span with Class to a input tag with Jquery

I am trying to add a Span after my Input that will have the class "error" and the text "test".
I've tried the append, and insertAfter methods. I can get the code to work on jsfiddle but I cannot get the code to work on my application.
I have put the HTML and JS/Jquery below. My end result would have a Span (with the class error) next to each input with the type text. I would then set a value for this span based on a validation loop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Zito - Lab 7</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="reservation.js" type="text/javascript"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<fieldset>
<legend>General Information</legend>
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" autofocus><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights"><br>
<label>Adults:</label>
<select name="adults" id="adults">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<label>Children:</label>
<select name="children" id="children">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label>Room type:</label>
<input type="radio" name="room" id="standard" class="left" checked>Standard
<input type="radio" name="room" id="business" class="left">Business
<input type="radio" name="room" id="suite" class="left last">Suite<br>
<label>Bed type:</label>
<input type="radio" name="bed" id="king" class="left" checked>King
<input type="radio" name="bed" id="double" class="left last">Double Double<br>
<input type="checkbox" name="smoking" id="smoking">Smoking<br>
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email"><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
</fieldset>
<input type="submit" id="submit" value="Submit Request"><br>
</form>
</body>
</html>
JS/JQuery
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
var phonePattern = /\b(\d{3})([-])(\d{3})([-])(\d{4})\b/;
var datePattern = /\b(0[1-9]|1[012])([/])(0[1-9]|1[0-9]|2[0-9]|3[01])([/])((20)\d\d)\b/;
$(":text").after("<span class='error'>*</span>");
$("#arrival_date").focus();
$("#reservation_form").submit(
function(event) {
var isValid = true;
// validate arrival date
var arrivalDate = $("#arrival_date").val();
if (arrivalDate == "") {
$("#arrival_date").next().text("This field is required");
isValid = false;
} else if (!datePattern.test(arrivalDate)) {
$("#arrival_date").next().text("Must be in the format 12/12/2012");
isValid = false;
} else {
$("#arrival_date").next().text("");
}
// validate nights
var nights = $("#nights").val();
if (nights == "") {
$("#nights").next().text("This field is required");
isValid = false;
} else if ((isNaN(parseInt(nights))) || (parseInt(nights) <=0)) {
$("#nights").next().text("This field must be a number and not zero");
isValid = false;
} else {
$("#nights").next().text("");
}
// validate name
var name = $("#name").val();
if (name == "") {
$("#name").next().text("This field is required");
isValid = false;
} else {
$("#name").next().text("");
}
// validate email
var email = $("#email").val();
if (email == "") {
$("#email").next().text("This field is required");
isValid = false;
} else if (!emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
// validate phone
var phone = $("#phone").val();
if (phone == "") {
$("#phone").next().text("This field is required");
isValid = false;
} else if (!phonePattern.test(phone) ) {
$("#phone").next().text("Must be in the format 999-999-9999");
isValid = false;
} else {
$("#phone").next().text("");
}
if (isValid == false) {
event.preventDefault();
$("#arrival_date").focus();
}
}
);
}); // end ready
Most easy way is to add a Div container around the form and just append the warning to that. To effectively append after an element you need to give it a class or id.
var email = $("#email"); //using class instead of input:text
var html = "<span class='error'>TEST!</span>"
email.after( html );
But I personally would like something like this better:
var generateError = function(){
var html = "<div id='error' style='top: 0; left:0; width:100%; height: 50px; background-color: red; text-allign: center; display:none; z-index: 100;'> ERROR!!</div>"
$(body).append( html );
}
var showError = function( text ){
var err = $("#error");
err.html( text );
err.show(500).delay(2000).hide(500);
}
Code is fairly self-explaining, but this will make two functions: generateError and showError.
generateError you need to call before you want to show the error, possibly when the page loads it will add a small header on top of all you other elements and will appear hidden.
showError uses a text argument with the error you want to show. Then it will set the text to the div and show it for two seconds.
This then is more what you are looking for?
$(document).ready(function () {
var input = $("input");
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
input.keypress(function (ele) {
// if regex.test( input ) === false
createErrors(ele.target);
})
});
var createErrors = function (ele) {
$('<span>TEST!</span>').insertAfter(ele);
$("#arrival_date").focus();
};
This works on keypress, that means the regex gets checked every time a key is pressed. It also passes the element where the user is typing as parameter, this means that you wont get errors for all input:text, but only for the ones where there is an error.
Updated Fiddle (still not perfect, but if its an school exercise this will help you to finish it :)

Unable to get Status of Checkbox from a Form

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);
});

Categories