Adding to a url to tick a checkbox - javascript

I have a URL www.example.com/index.html
It has an element with an id of DARK_MODE.
It is a checkbox.
I want to add to the URL so that when it loads it automatically gets ticked.
I tried www.example.com/index.html?DARK_MODE=checked
This is not my website that i'm loading.
Am i doing this right?
Thanks.

Here is the solution that I propose. In order to check the checkbox, use, ?DARK_MODE=checked.
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1) {
var query = document.location
.toString()
.replace(/^.*?\?/, '')
.replace(/#.*$/, '')
.split('&');
for(var i=0, l=query.length; i<l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
if($_GET['DARK_MODE'] === 'checked') document.getElementById('DARK_MODE').checked = true;
<input type="checkbox" id="DARK_MODE" />

Related

Javascript validation on select input

I am trying to make a javascript validating form, and am a bit stuck on validating drop down inputs (select)
I have been using this so far but am unsure on how to implement the validation to the select options, if anyone could give me some tips that would be great.
Edit: Also, how would I implement email validation, e.g containing #, thanks
Thanks
<input id="firstname" onblur="validate('firstname')"></input>
Please enter your first name
Thanks
http://jsfiddle.net/ww2grozz/13/
you need to handle select as follow
var validated = {};
function validate(field) {
// Get the value of the input field being submitted
value = document.getElementById(field).value;
// Set the error field tag in the html
errorField = field + 'Error';
// Set the success field
successField = field + 'Success';
if (value != '') {
document.getElementById(successField).style.display = 'block';
document.getElementById(errorField).style.display = 'none';
validated[field] = true;
} else {
document.getElementById(successField).style.display = 'none';
document.getElementById(errorField).style.display = 'block';
validated[field] = false;
}
}
function SimulateSubmit() {
// Query your elements
var inputs = document.getElementsByTagName('input');
// Loop your elements
for (i = 0, len = inputs.length; i < len; i++) {
var name = inputs[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
var all_select = document.getElementsByTagName("select"); // get al select box from the dom to validate
for (i = 0, len = all_select.length; i < len; i++) {
var name = all_select[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
}
here the Working fiddle
using jQuery function
$('input').on('keyup', function() {
var isValid = $.trim($(this).val()) ? true : false;
// show result field is Valid
});
You must use <form> tag and set your action to it I have done that check this link and I have added select tag and set it to -1 by default for checking purpose while validating

Insert keypress in input value

Hi i have a problem with insert value in input
You might ask why I did put keypress input field with JS?
I have the compiled program emscripten and it has driver input that intercepts all keypress, keydown, keyup and returns false for other element on page.
That blocks all input fields on page.
I have no way to fix this in the emscripten program, and I decided to fix it by jQuery on html side
jQuery(function() {
var $input = jQuery("#search-area228");
$input
.attr("tabindex", "0")
.mousedown(function(e){ jQuery(this).focus(); return false; })
.keypress(function(e){
var data = jQuery(this).val
var text = String.fromCharCode(e.keyCode || e.charCode)
for(var i = 0; i < text.length; i++)
jQuery(this).val(text[i])
return false; });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="search-area228">
This will unlock the input field, but the problem is that allows you to write only one character and when you click on the following replaces it!
Please, help !
Just add the new text to the pre-existing text in that field which you already defined (in a wrong way) as data and didn't use it
when you call the method val of an input you should use it with braces jQuery(this).val() NOT jQuery(this).val because this is a function method of jQuery not a variable.
jQuery(function() {
var $input = jQuery("#search-area228");
$input
.attr("tabindex", "0")
.mousedown(function(e){ jQuery(this).focus(); return false; })
.keypress(function(e){
var data = jQuery(this).val();
var text = String.fromCharCode(e.keyCode || e.charCode)
for(var i = 0; i < text.length; i++)
jQuery(this).val(data + text[i])//<<< here
return false; });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="search-area228">
Your code had little mistake.You were setting the value of the input to the current key instead of appending it to the current value of the input.
jQuery(this).val(jQuery(this).val() + text[i]);
This is the fixed version:
jQuery(function () {
var $input = jQuery("#search-area228");
$input.attr("tabindex", "0")
.mousedown(function (e) {
jQuery(this).focus();
return false;
})
.keypress(function (e) {
var data = jQuery(this).val
var text = String.fromCharCode(e.keyCode || e.charCode)
for (var i = 0; i < text.length; i++)
jQuery(this).val(jQuery(this).val() + text[i]);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search-area228">

Trying to pre-populate form fields with specific URLS

One of our affiliates wants us to be able to pre-populate fields on our form, based on the URL. Using something such as an "s5 parameter". For example:
Here is the example link:
www.smartreliefrx.com/qualify/new/diabetes/?a=1476&oc=172&c=1205&m=2&s1=#affid#&s2=#s2#&s3=#s1#&#s5#
How would I go about doing that? I am only using JavaScript.
Thanks!
Get rid of the #'s around the parameters in the url or you'll need to change the function below. Also change the var url to the window.location, I think its right but double check, try this:
See it in action: http://jsfiddle.net/wp4Ls24n/2/
function populateForm() {
var formVal = '';
var url = 'http://www.smartreliefrx.com/qualify/new/diabetes/?a=1476&oc=172&c=1205&m=2&s1=#affid&s2=#s2&s3=s1#&s5=someValue';
//var url = window.location.search.substring(1);
url = url.split('&');
for(var i=0; i<url.length; i++) {
var pair = url[i].split('=');
if(pair[0] == 's5') {
formVal = pair[1];
}
}
document.getElementById('someInput').value = formVal;
}
populateForm();
<form>
<label>Some Input:</label>
<input id="someInput" />
</form>

form loop all and check radio + options

I have a long form and trying to get the loop done. but i am not sure how to
check for options (dropdown) and radio type's, if exist, select the checked or selected and put it in the array.
Is there a better way to construct it?
and when the loop is done, to pass the var for sending it in ajax?
var parameters = "";
var form = document.getElementById("someForm");
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].value) {
if(form.elements[i].type == "text" || form.elements[i].type == "select-one" || form.elements[i].type == "hidden")
parameters = parameters + '&' + form.elements[i].name+'='+escape(form.elements[i].value);
if((form.elements[i].type == "radio" || form.elements[i].type == "checkbox") && form.elements[i].checked)
parameters = parameters + '&' + form.elements[i].name+'='+form.elements[i].value;
}
}
I generally use something like this, if I need to ajax a form.
Simply append parameters to the end of your ajax request.
I would take a look at the way jQuery does it. Specifically you will want to look at the serialize (line 6260), serializeArray (line 6264) and param (line 6784) methods.
According to this comparison of form serialization in different JavaScript libraries, jQuery's implementation adheres to the W3C specification better than the competition.
I agree in looking at jQuery, but maybe try implementing something yourself. You could get all inputs / textareas / selects within the form quite easily using jQuery:
// get all input fields, except buttons
var inputs = $("form input:not(:button)");
// get all dropdowns
var dropdowns = $("form select");
// get all text areas (i.e. "big" textboxes)
var textareas = $("form textarea");
I used something like this (I edited line 2 of Sheldon's solution):
var parameters = "";
var form = document.someForm;
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].value) {
if(form.elements[i].type == "text" || form.elements[i].type == "select-one" || form.elements[i].type == "hidden")
parameters = parameters + '&' + form.elements[i].name+'='+escape(form.elements[i].value);
if((form.elements[i].type == "radio" || form.elements[i].type == "checkbox") && form.elements[i].checked)
parameters = parameters + '&' + form.elements[i].name+'='+form.elements[i].value;
}
}

Generic way to detect if html form is edited

I have a tabbed html form. Upon navigating from one tab to the other, the current tab's data is persisted (on the DB) even if there is no change to the data.
I would like to make the persistence call only if the form is edited. The form can contain any kind of control. Dirtying the form need not be by typing some text but choosing a date in a calendar control would also qualify.
One way to achieve this would be to display the form in read-only mode by default and have an 'Edit' button and if the user clicks the edit button then the call to DB is made (once again, irrespective of whether data is modified. This is a better improvement to what is currently existing).
I would like to know how to write a generic javascript function that would check if any of the controls value has been modified ?
In pure javascript, this would not be an easy task, but jQuery makes it very easy to do:
$("#myform :input").change(function() {
$("#myform").data("changed",true);
});
Then before saving, you can check if it was changed:
if ($("#myform").data("changed")) {
// submit the form
}
In the example above, the form has an id equal to "myform".
If you need this in many forms, you can easily turn it into a plugin:
$.fn.extend({
trackChanges: function() {
$(":input",this).change(function() {
$(this.form).data("changed", true);
});
}
,
isChanged: function() {
return this.data("changed");
}
});
Then you can simply say:
$("#myform").trackChanges();
and check if a form has changed:
if ($("#myform").isChanged()) {
// ...
}
I am not sure if I get your question right, but what about addEventListener? If you don't care too much about IE8 support this should be fine. The following code is working for me:
var form = document.getElementById("myForm");
form.addEventListener("input", function () {
console.log("Form has changed!");
});
In case JQuery is out of the question. A quick search on Google found Javascript implementations of MD5 and SHA1 hash algorithms. If you wanted, you could concatenate all form inputs and hash them, then store that value in memory. When the user is done. Concatenate all the values and hash again. Compare the 2 hashes. If they are the same, the user did not change any form fields. If they are different, something has been edited, and you need to call your persistence code.
Another way to achieve this is serialize the form:
$(function() {
var $form = $('form');
var initialState = $form.serialize();
$form.submit(function (e) {
if (initialState === $form.serialize()) {
console.log('Form is unchanged!');
} else {
console.log('Form has changed!');
}
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Field 1: <input type="text" name="field_1" value="My value 1"> <br>
Field 2: <input type="text" name="field_2" value="My value 2"> <br>
Check: <input type="checkbox" name="field_3" value="1"><br>
<input type="submit">
</form>
Form changes can easily be detected in native JavaScript without jQuery:
function initChangeDetection(form) {
Array.from(form).forEach(el => el.dataset.origValue = el.value);
}
function formHasChanges(form) {
return Array.from(form).some(el => 'origValue' in el.dataset && el.dataset.origValue !== el.value);
}
initChangeDetection() can safely be called multiple times throughout your page's lifecycle: See Test on JSBin
For older browsers that don't support newer arrow/array functions:
function initChangeDetection(form) {
for (var i=0; i<form.length; i++) {
var el = form[i];
el.dataset.origValue = el.value;
}
}
function formHasChanges(form) {
for (var i=0; i<form.length; i++) {
var el = form[i];
if ('origValue' in el.dataset && el.dataset.origValue !== el.value) {
return true;
}
}
return false;
}
Here's how I did it (without using jQuery).
In my case, I wanted one particular form element not to be counted, because it was the element that triggered the check and so will always have changed. The exceptional element is named 'reporting_period' and is hard-coded in the function 'hasFormChanged()'.
To test, make an element call the function "changeReportingPeriod()", which you'll probably want to name something else.
IMPORTANT: You must call setInitialValues() when the values have been set to their original values (typically at page load, but not in my case).
NOTE: I do not claim that this is an elegant solution, in fact I don't believe in elegant JavaScript solutions. My personal emphasis in JavaScript is on readability, not structural elegance (as if that were possible in JavaScript). I do not concern myself with file size at all when writing JavaScript because that's what gzip is for, and trying to write more compact JavaScript code invariably leads to intolerable problems with maintenance. I offer no apologies, express no remorse and refuse to debate it. It's JavaScript. Sorry, I had to make this clear in order to convince myself that I should bother posting. Be happy! :)
var initial_values = new Array();
// Gets all form elements from the entire document.
function getAllFormElements() {
// Return variable.
var all_form_elements = Array();
// The form.
var form_activity_report = document.getElementById('form_activity_report');
// Different types of form elements.
var inputs = form_activity_report.getElementsByTagName('input');
var textareas = form_activity_report.getElementsByTagName('textarea');
var selects = form_activity_report.getElementsByTagName('select');
// We do it this way because we want to return an Array, not a NodeList.
var i;
for (i = 0; i < inputs.length; i++) {
all_form_elements.push(inputs[i]);
}
for (i = 0; i < textareas.length; i++) {
all_form_elements.push(textareas[i]);
}
for (i = 0; i < selects.length; i++) {
all_form_elements.push(selects[i]);
}
return all_form_elements;
}
// Sets the initial values of every form element.
function setInitialFormValues() {
var inputs = getAllFormElements();
for (var i = 0; i < inputs.length; i++) {
initial_values.push(inputs[i].value);
}
}
function hasFormChanged() {
var has_changed = false;
var elements = getAllFormElements();
for (var i = 0; i < elements.length; i++) {
if (elements[i].id != 'reporting_period' && elements[i].value != initial_values[i]) {
has_changed = true;
break;
}
}
return has_changed;
}
function changeReportingPeriod() {
alert(hasFormChanged());
}
Here's a polyfill method demo in native JavaScript that uses the FormData() API to detect created, updated, and deleted form entries. You can check if anything was changed using HTMLFormElement#isChanged and get an object containing the differences from a reset form using HTMLFormElement#changes (assuming they're not masked by an input name):
Object.defineProperties(HTMLFormElement.prototype, {
isChanged: {
configurable: true,
get: function isChanged () {
'use strict'
var thisData = new FormData(this)
var that = this.cloneNode(true)
// avoid masking: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
HTMLFormElement.prototype.reset.call(that)
var thatData = new FormData(that)
const theseKeys = Array.from(thisData.keys())
const thoseKeys = Array.from(thatData.keys())
if (theseKeys.length !== thoseKeys.length) {
return true
}
const allKeys = new Set(theseKeys.concat(thoseKeys))
function unequal (value, index) {
return value !== this[index]
}
for (const key of theseKeys) {
const theseValues = thisData.getAll(key)
const thoseValues = thatData.getAll(key)
if (theseValues.length !== thoseValues.length) {
return true
}
if (theseValues.some(unequal, thoseValues)) {
return true
}
}
return false
}
},
changes: {
configurable: true,
get: function changes () {
'use strict'
var thisData = new FormData(this)
var that = this.cloneNode(true)
// avoid masking: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
HTMLFormElement.prototype.reset.call(that)
var thatData = new FormData(that)
const theseKeys = Array.from(thisData.keys())
const thoseKeys = Array.from(thatData.keys())
const created = new FormData()
const deleted = new FormData()
const updated = new FormData()
const allKeys = new Set(theseKeys.concat(thoseKeys))
function unequal (value, index) {
return value !== this[index]
}
for (const key of allKeys) {
const theseValues = thisData.getAll(key)
const thoseValues = thatData.getAll(key)
const createdValues = theseValues.slice(thoseValues.length)
const deletedValues = thoseValues.slice(theseValues.length)
const minLength = Math.min(theseValues.length, thoseValues.length)
const updatedValues = theseValues.slice(0, minLength).filter(unequal, thoseValues)
function append (value) {
this.append(key, value)
}
createdValues.forEach(append, created)
deletedValues.forEach(append, deleted)
updatedValues.forEach(append, updated)
}
return {
created: Array.from(created),
deleted: Array.from(deleted),
updated: Array.from(updated)
}
}
}
})
document.querySelector('[value="Check"]').addEventListener('click', function () {
if (this.form.isChanged) {
console.log(this.form.changes)
} else {
console.log('unchanged')
}
})
<form>
<div>
<label for="name">Text Input:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
</div>
<div>
<h4>Radio Button Choice</h4>
<label for="radio-choice-1">Choice 1</label>
<input type="radio" name="radio-choice-1" id="radio-choice-1" tabindex="2" value="choice-1" />
<label for="radio-choice-2">Choice 2</label>
<input type="radio" name="radio-choice-2" id="radio-choice-2" tabindex="3" value="choice-2" />
</div>
<div>
<label for="select-choice">Select Dropdown Choice:</label>
<select name="select-choice" id="select-choice">
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
</select>
</div>
<div>
<label for="textarea">Textarea:</label>
<textarea cols="40" rows="8" name="textarea" id="textarea"></textarea>
</div>
<div>
<label for="checkbox">Checkbox:</label>
<input type="checkbox" name="checkbox" id="checkbox" />
</div>
<div>
<input type="button" value="Check" />
</div>
</form>
I really like the contribution from Teekin above, and have implemented it.
However, I have expanded it to allow for checkboxes too using code like this:
// Gets all form elements from the entire document.
function getAllFormElements() {
// Return variable.
var all_form_elements = Array();
// The form.
var Form = document.getElementById('frmCompDetls');
// Different types of form elements.
var inputs = Form.getElementsByTagName('input');
var textareas = Form.getElementsByTagName('textarea');
var selects = Form.getElementsByTagName('select');
var checkboxes = Form.getElementsByTagName('CheckBox');
// We do it this way because we want to return an Array, not a NodeList.
var i;
for (i = 0; i < inputs.length; i++) {
all_form_elements.push(inputs[i]);
}
for (i = 0; i < textareas.length; i++) {
all_form_elements.push(textareas[i]);
}
for (i = 0; i < selects.length; i++) {
all_form_elements.push(selects[i]);
}
for (i = 0; i < checkboxes.length; i++) {
all_form_elements.push(checkboxes[i]);
}
return all_form_elements;
}
// Sets the initial values of every form element.
function setInitialFormValues() {
var inputs = getAllFormElements();
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].type != "checkbox"){
initial_values.push(inputs[i].value);
}
else
{
initial_values.push(inputs[i].checked);
}
}
}
function hasFormChanged() {
var has_changed = false;
var elements = getAllFormElements();
var diffstring = ""
for (var i = 0; i < elements.length; i++) {
if (elements[i].type != "checkbox"){
if (elements[i].value != initial_values[i]) {
has_changed = true;
//diffstring = diffstring + elements[i].value+" Was "+initial_values[i]+"\n";
break;
}
}
else
{
if (elements[i].checked != initial_values[i]) {
has_changed = true;
//diffstring = diffstring + elements[i].value+" Was "+initial_values[i]+"\n";
break;
}
}
}
//alert(diffstring);
return has_changed;
}
The diffstring is just a debugging tool

Categories