Selectively adding and removing values of same CSS property - javascript

I’m creating an Open Type features tester using jquery and want to give the user the possibility of seeing several open type features applied at the same time.
The first dropdown sets the property to font-feature-settings: ‘frac’ 1;, he second dropdown sets the property to font-feature-settings: ‘smcp’ 1;
Currently if both of the dropdowns are active one overrides the instructions of the other one. What I need is that if both of them are active at the same time the property is set to font-feature-settings: ‘frac’ 1, ‘smcp’ 1; and consequently if only one of them is deactivated only the corresponding value is removed from the property.
Note: I'm aware that the Open Type features don't work when I link the font from the Google fonts site, so I've been testing it with it installed.
Thanks in advance.
.font-tester{
color: #000;
line-height: normal;
width: 100%;
word-wrap: break-word;
padding-top: 30px;
}
<style> #import url('https://fonts.googleapis.com/css2?family=EB+Garamond&display=swap'); </style>
<div class="tester-container">
<select id="tester-figures">
<option value="none" selected>Default</option>
<option value="'frac' 1">Fractions</option>
</select>
<select id="tester-smcp">
<option value="none" selected>Default</option>
<option value="'smcp' 1">Small caps</option>
</select>
<div class="font-tester" contenteditable="true" spellcheck="false" style="font-family: 'EB Garamond', serif; font-size:65pt;">
abc 123
</div>
</div>
<script>
$("#tester-figures").change(function() {
$('.font-tester').css("font-feature-settings", $(this).val());
});
$("#tester-smcp").change(function() {
$('.font-tester').css("font-feature-settings", $(this).val());
});
</script>

There are many ways to solve a task. Additional here is an alternative solution which has less and more simplyfied and code.
It works with only one function which add the change event to both selects. On change it reads out the actual values from both selects and builds a simple css string based on the actual values of both selects.
$('#tester-figures').add('#tester-smcp').each( function(){
const $this = $(this);
$this.change(function(){
let actualVals = {};
actualVals.TesterFigures = $('#tester-figures').val();
actualVals.TesterSmcp = $('#tester-smcp').val();
let myVal = '';
if('none' == actualVals.TesterFigures){
myVal = 'none' == actualVals.TesterSmcp ? '' : actualVals.TesterSmcp;
}else {
myVal = 'none' == actualVals.TesterSmcp ? actualVals.TesterFigures : actualVals.TesterFigures + ', ' + actualVals.TesterSmcp;
}
$('.font-tester').css("font-feature-settings", myVal);
});
});
NOTE: I don't have worked with css attribute font-feature-settings yet. So I don't have any experience with this special item. What I notice is, that the strings in the selects (i.e. 'frac' 1) changes. The inner quotes and the number get lost when the css is added to the html element. But the style still works without them. Maybe you like to check if it works if you only use frac and smcp in your selects. In actual FF it works ;-)

What you need to do is basically concatenate the values into a comma-separated string as you update them, instead of just whatever the input value is. You could write your own function to do this if you wanted to. It would have to include logic for whether there is only one value or multiple values in order to make sure you don't end up with a trailing comma for no reason. However, there's an easier way: if we store the values in an array, we can use Array.join(), which will automagically handle that logic for us.
Array.join() joins all the elements in an array into one big string, and it takes an optional parameter that specifies how to join them. So we can do like so:
['one', 'two', 'three'].join(', '); // => 'one, two, three'
Note how there's not an extra comma and space at the end.
So now that we know how to get the end result, we just need to work on getting the values. You will need to either add elements to the array or remove them based on how you interact with the dropdowns. Since you only have two items in each dropdown right now, that logic can be pretty simple. If you are going to have multiple items in any dropdowns, the overall approach is the same, but you'll have to tweak the if…else part in the snippet below.
Keep in mind that, if you want to remove an item from the array, you need to know what to remove. But that's the old value. If you run $(myInput).val() inside your .change() function, you're going to get the current value. So you need to keep track of the old values separately.
Once you have the new array set up, you just have to apply the Array.join() magic and then you have your string that you can use in the jQuery .css() function.
It will be much easier to maintain this if you cut out as much repeated logic as possible and just have one single function that the inputs can each call. So I've done that for you below. You can add more inputs to the .each() function by chaining on more .add()s before it, if you need to.
let oldValues = ['none', 'none']; // whatever the default values are for each select
let currentValue = [];
const getNewValue = input => {
const val = $(input).val();
const index = input.index();
const oldValue = oldValues[index];
if (val !== 'none') {
currentValue.push(val);
} else {
const indexOfValue = currentValue.indexOf(oldValue);
currentValue.splice(indexOfValue, 1);
}
oldValues[index] = val;
const newCssValue = currentValue.join(', ');
console.clear();
console.log(`new value is "${newCssValue}"`);
return newCssValue;
};
$(function() {
const $fontTester = $('.font-tester');
$('#tester-figures').add('#tester-smcp').each(function() {
const $this = $(this);
$this.change(function() {
const newCssValue = getNewValue($this);
$fontTester.css('font-feature-settings', newCssValue);
});
});
});
.font-tester {
color: #000;
line-height: normal;
width: 100%;
word-wrap: break-word;
padding-top: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tester-container">
<select id="tester-figures">
<option value="none" selected>Default</option>
<option value="'frac' 1">Fractions</option>
</select>
<select id="tester-smcp">
<option value="none" selected>Default</option>
<option value="'smcp' 1">Small caps</option>
</select>
<div class="font-tester" contenteditable="true" spellcheck="false" style="font-family: 'EB Garamond', serif; font-size:65pt;">
abc 123
</div>
</div>

Related

Why does my JS function only affect the first element addressed in the HTML structure? (changing display property of class)

my basic structure of the JS function works. However, it only affects the first DIV in the HTML structure that is to be shown and hidden.
The CSS class "map-content" has none as display property. Several containers will receive this class and will therefore initially be hidden. All DIV containers get their own value, which is necessary in my code when changing the display property.
This is my function, which basically works, but only shows and hides the first container (in the HTML structure) with the "map-content" class.
function validate_3() {
var x = document.getElementById("location_select");
var y = x.options[x.selectedIndex].value;
var a = document.querySelector(".map-content");
var b = a.getAttribute('value');
{
if (y == b) {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
}
.map-content {
display: none;
}
<select id="location_select" onchange="validate_3">
<option disabled selected>Select location...</option>
<option value="de_germany">Berlin: Germany</option>
<option value="fr_france">Paris: France</option>
<option value="it_italy">Rome: Italy</option>
</select>
<div class="map-content" value="de_germany">
<h3>This is Berlin</h3>
<p>Berlin is in Germany</p>
</div>
<div class="map-content" value="fr_france">
<h3>This is Paris</h3>
<p>Paris is in France</p>
</div>
<div class="map-content" value="it_italy">
<h3>This is Rome</h3>
<p>Rome is in Italy</p>
</div>
Note on the code snippet: I don't know why, but unlike my test interface, none of the selections work here. Not even the first in the structure as described in the text.
I am happy to get general suggestions for a better structure if there are any.
you are missing a set of parentheses here onchange="validate_3"> , add a set of parentheses like this onchange="validate_3()">, and your first selection should work
To get what you want, make sure you've added the parentheses as shown above.
javascript,
// take this line out of your funtion and change `querySelector` to
//`querySelectorAll`
var a = document.querySelectorAll(".map-content");
function validate_3() {
var x = document.getElementById("location_select");
var y = x.options[x.selectedIndex].value;
//use The forEach() method to executes a provided function once for each
//element.
a.forEach((element) => {
if (y != element.getAttribute("value")) {
(element.classList.add("map-content"))
} else {
element.classList.remove("map-content")
};
});
};
But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

Want to make something like conditional select options in a HTML Form

I want to make a form in which the next field appears based on input done in the previous field by the user.
eg: If The user selects Beverages then below it show a fieldset with different beverages with checkbox, and if user select snacks then below it show fieldset with snacks items
I was trying it to do like this:
<select id="first-choice">
<option selected value="base">Please Select</option>
<option value="beverages">Beverages</option>
<option value="snacks">Snacks</option>
</select>
<br>
<select id="second-choice">
<option>Please choose from above</option>
</select>
JSON Data
{
"beverages": "Coffee,Coke",
"snacks": "Chips,Cookies"
}
Jquery
$("#first-choice").change(function() {
var $dropdown = $(this);
$.getJSON("jsondata/data.json", function(data) {
var key = $dropdown.val();
var vals = [];
switch(key) {
case 'beverages':
vals = data.beverages.split(",");
break;
case 'snacks':
vals = data.snacks.split(",");
break;
case 'base':
vals = ['Please choose from above'];
}
var $secondChoice = $("#second-choice");
$secondChoice.empty();
$.each(vals, function(index, value) {
$secondChoice.append("<option>" + value + "</option>");
});
});
});
I not only want append select option, I actually want to make a new division with text fields and file uploads etc
just guide me how to do it in a compact/dynamic way
By all means keep the JS that fills the selector elements (but make your options map a thing that's known before the user even gets to pick anything: don't rely on a network transfer for that!), but don't try to get the whole "conditional showing" to work in JS: CSS can already do that, and it'll do it better. You just need to remember to use the correct HTML markup:
// Load this script via src="..." with `async` and `defer` attributes
// so that it'll run before the user gets to interact with the page,
// after the DOM has been constructed. A feature that's been available
// since IE11, so there's no reason to still put scripts at the end of
// the page, or listening for DOMContentLoaded/ready events.
const first = document.getElementsByName('first-value')[0];
const second = document.getElementsByName('second-value')[0];
const initial = second.innerHTML;
// Either hard code this, or get it on page load, just make sure
// it's already available before users start picking values!
const optionMap = {
a: ['i', 'j', 'k'],
b: ['u', 'v', 'w'],
c: ['x', 'y', 'z'],
};
function addOption(selectElement, text) {
let option = document.createElement('option');
option.value = text;
option.textContent = text;
selectElement.append(option);
}
// Fill the first selector
Object.keys(optionMap).forEach(text => addOption(first, text));
// And only fill the second selector when we know the first value
first.addEventListener('change', evt => {
second.innerHTML = initial;
optionMap[evt.target.value].forEach(text => addOption(second, text));
});
select:not(:valid) {
border: 1px solid red;
}
select:not(:valid) + .followup {
display: none;
}
<select required name="first-value">
<option disabled selected>please select one</option>
</select>
<select required class="followup" name="second-value">
<option disabled selected>please select one more</option>
</select>
The trick here is to make sure you have an option that is both disabled and selected. The latter because <select> elements always have an option selected, but any option marked as disabled does not count as a valid choice (this lets you for instance put labels in a selector element).
So, we make a first <option> that is simply a label, but also make sure the selector always starts with that option selected. As it's disabled, that makes the selector invalid as far as form posting is concerned, so we can use the CSS :valid pseudo class to do all kinds of useful things, like hiding any adjacent element until the main select element is valid.
And of course you can still "fill" the second selector using JS, with an event listener on the first selector so that its change triggers some JS that appends a bunch of option elements to the second one, but this is really something you want to do without a network request: have your code already know which primary values map to which arrays of secondary values by doing a fetch for the full mapping on pageload, or even hardcoded it (e.g. during your site building step, or even manually)

How to create a search that filters by class name

I currently have a website that has multiple items. They are all individual div items. They all have one class name in common with several other class names as tags to help separate them (some tags are common among multiple div items)
I already have buttons set up that use data-filter=".exampleclass" and data-filter=".exampleclass2" etc. which work perfectly for sorting based on the class names. I am now trying to make a search bar where a user could type in the class name so I don't have to make buttons for them all.
document.getElementById("boxsearch").oninput = function() {
var matcher = new RegExp(document.getElementById("boxsearch").value, "gi");
for (var i = 0; i < document.getElementsByClassName("portfolio-item").length; i++) {
if (matcher.test(document.getElementsByClassName("category")[i])) {
document.getElementsByClassName("portfolio-item")[i].style.display = "inline-block";
} else {
document.getElementsByClassName("portfolio-item")[i].style.display = "none";
}
}
}
http://jsfiddle.net/kc2ot8ua/
I dont have the jquery file included so the buttons dont work (they work on my end) I just dont know how to use the search bar to search the class names.
This is the closest I could find to what I am trying to achieve: http://jsfiddle.net/mttgj1tt/5/
Filtering elements based on regular expression matches with one of their class names is an inefficient way to filter elements. Typically you'd build an index and use that with a more optimised search algorithm.
You might use one class to select the target set of elements, then loop over them and get their classList, then loop over those looking for matches, there's an example below. But this will also test other class names that have nothing to do with filtering or sorting (e.g. in the example below, "box" is used for display only, but elements are filtered by it anyway).
A better idea might be to add the filter and sorting values as a data- attribute, then they can be isolated from other side effects. I'd also suggest building an index of subject elements so you can find the ones you want first, then hide them.
Multiple getElementByClassName calls are expensive and unnecessary (particularly in a for loop). The example does one call per keyup.
function filterOnClass(baseClass, s) {
let re = new RegExp(s.trim(), 'i');
document.querySelectorAll('.' + baseClass).forEach(node => {
let cNames = Array.from(node.classList);
// Show all if search string is blank
if (s.trim() == '') {
node.classList.remove('hide');
// Otherwise, filter
} else if (cNames.some(cName => re.test(cName))) {
node.classList.add('hide');
} else {
node.classList.remove('hide');
}
});
}
.box {
height: 50px;
width: 100px;
border: 1px solid blue;
}
.hide {
display: none;
}
<input id="searchInput" onkeyup="filterOnClass('box', this.value)"><br>
<div class="box foo">foo</div>
<div class="box foo bar">foo bar</div>
<div class="box fum bar">fum bar</div>
<div class="box fum">fum</div>

Using checkboxes to update UI in realtime

I'm currently in the process of trying to develop a smarter UI for one of my clients. However the only code I can use to develop this 'feature', is pure JS. I have no access to the source HTML or CSS files the only access I have is the ability to inject JavaScript through an external .js file.
I'm not too familiar with JS, but I can work my way around a basic script or two.
Scenario
What we're doing is allowing users to edit PDF Templates online using a software called Core Create. The UI accessed through the browser is quite cluttered and I would like to provide an option to hide and show UI elements <textareas>/<inputs> through the use of checkboxes.
Here is a very basic JS Fiddle that I have built with the
intention of hiding and displaying UI.
The page in question
Above is a screen grab of the page I am working with, on the left you can see the UI and its composition on the right within the 'Inspect Element' tool.
I have come to the conclusion that I need to iterate through the highlighted selection and link them accordingly with seven checkboxes. The result would then be a selection of checkboxes that would hide / display the correct UI element.
The Caveat
In realizing I cannot edit or introduce new HTML I noticed the lack of on-click attributes. So I'm a bit lost on how to invoke the JavaScript I will eventually build.
My Question
With my limited knowledge of JS I don't know how I would iterate though div elements editoraccvar - editoraccvar6 picking out the ones I need to manipulate.
Due to the lack of ID's / Names (I assume it would have to be done using Parent/Child rules somehow, as the classes are widley used by the rest of the UI. I would appreciate a small example demonstrating how I could achieve this, so I can learn from it.
I should clarify, I have already added the checkboxes to the page, I just need to build the JS link between the Checkbox and the UI element I'm attempting to target. You can find all attributes linking to these checkboxes included in the JS Fiddle.
EDIT // A Working Simplified Example;
Due to some confusion I have 'frankensteined' some code together to show the final result I am after. A working example of sorts. The actual result needs to target 7 Checkboxes and 7 Divisions. I'll list thier common properties below.
// This script is already in place and constructed by the system.
// Written inside script tags and located straight after 'editopt1'.
// $(document).ready(function() {
// $('#checkboxopt1').click(function() {
// if ($('#checkboxopt1').val() == 'true') {
// $('#opt1').val('false');
// $('#checkboxopt1').val('false');
// $('#checkboxopt1').prop('checked', false);
// $('#previewrefresh').trigger('click');
// } else {
// $('#opt1').val('true');
// $('#checkboxopt1').val('true');
// $('#checkboxopt1').prop('checked', true);
// $('#previewrefresh').trigger('click');
// };
// });
// });
function exFunction() {
// Check the function is called
console.log("200 : OK");
// grab all elements with the class, .field-summernote
var uiblocks = document.querySelectorAll('.field-summernote');
for (var i = 0; i < uiblocks.length; i++) {
var current = uiblocks[i];
if (current.className.indexOf('editoraccvar') < 0) //not found: -1
return;
// check elements in the array
console.log(current);
// control the elemets in the array.
if (document.getElementById('checkboxopt1').checked) {
uiblocks[0].style.display = 'block'; // display the element
} else {
uiblocks[0].style.display = 'none'; // hide the element
}
}
};
// Trigger the collection the check, and the control.
var x = document.getElementById("checkboxopt1");
x.addEventListener("click", function() {
console.log("Opt");
exFunction();
});
.editoraccvar1 {
width: 300px;
background: #0ff;
padding: .5em;
}
.editoropt1 {
width: 300px;
background: #ff0;
padding: .5em;
}
textarea {
display: block;
width: 95%;
resize: none;
padding: .5em;
}
<!-- I'm trying to hide & show this entire division... -->
<div class="seq-box-form-field field-summernote editoraccvar1 ">
<label for="accvar1">Ground Floor Info</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Using only what the system has supplied. -->
<div class="seq-box-form-field editoropt1 ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span>
<input type="checkbox" name="checkboxopt1" id="checkboxopt1" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
Divisions <div class=""></div>
* editoraccvar,
editoraccvar1,
editoraccvar2,
editoraccvar3,
editoraccvar4,
editoraccvar5,
editoraccvar6*
Checkboxes <input id=""></input>
* checkboxopt,
checkboxopt1,
checkboxopt2,
checkboxopt3,
checkboxopt4,
checkboxopt5,
checkboxopt6,*
As far as I can see, your problem boils down to link checkboxes (that seem to have been generated in some way) to "division" parts of your html that you want to hide. Plus, you have to inject javascript code in the page (so I guess the less code the better).
One approach could be as follows:
// Wrap the code in an anonymus function, to avoid clustering the global space.
(function (domElements) {
// This is the callback that will fire when a checkbox is clicked.
function clickCallback() {
// the context of this callback is the DOM element thus we can access its attributes through this.
// extract the checkNumber of the class of the element. This number is the link to the division that we want to hide/show.
var checkNumber = ((/ editoropt(\d*) /).exec(this.className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0];
// Hide/show division, update checkBox state.
toggleElements(division, checkBox, window.getComputedStyle(division).display === 'none');
}
function toggleElements(division, checkBox, isShown) {
// Toggle the division (show/hide) accordingly.
division.style.display = isShown ? 'block' : 'none';
// Due to the fact that the event listener is attached to the parent of the checkBox, we need to maintain consistency manually.
checkBox.checked = isShown;
}
// Remove from the array of DOMElements those that aren't checkboxes and add a click event listener to each of them.
domElements
.filter(function (el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function (el) {
el.addEventListener('click', clickCallback, false);
});
// Call the function passing the dom elements with class '.seq-box-form-field' as argument. Checkboxes are contained within them. Also, transform the nodelist
// into a proper array so that methods defined in Array.prototype can be used.
})([].slice.call(document.querySelectorAll('.seq-box-form-field')));
The code is commented and (I think) quite self-explanatory. However, if you have any doubt or want me to elaborate any point further, please, let me know.
Finally, here's the working fiddle.
UPDATE
Same function (more or less) but now it accepts an array of values that will correspond to the initial state of the checkboxes:
(function (domElements, cbState) {
function clickCallback() {
toggleElements(this.className);
}
function toggleElements(className, initialShow) {
var checkNumber = ((/ editoropt(\d*) /).exec(className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0],
isShown = initialShow === undefined ? window.getComputedStyle(division).display === 'none' : initialShow;
division.style.display = isShown ? 'block' : 'none';
checkBox.checked = isShown;
}
domElements
.filter(function (el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function (el, index) {
el.addEventListener('click', clickCallback, false);
toggleElements(el.className, cbState[index]);
});
// Initial state of the checkboxes goes in the second parameter. The index in the array correspond to the checkbox position in the page.
})([].slice.call(document.querySelectorAll('.seq-box-form-field')), [false, false]);
Here's the Fiddle to play with. Hope it helps.
The other half of your problem, not addressed in the other answer has to do with events. Generally, adding an "onclick" attribute to the actual HTML is considered bad practice. You can attach event handlers with Javascript.
var a = document.getElementById("checkboxopt1");
a.addEventListener("click", exFunction, false);
See the manual for more info about how to use this.
Looks like that you need the elements that have the class "field-summernote", but not the class "editorbdyvar".
You can use a query selector to get elements by class name using the default tools from Javascript:
var items = document.querySelectorAll('.field-summernote');
for(var i = 0; i<items.length; i++){
var current = items[i];
if( current.className.indexOf('editoraccvar') < 0) //not found: -1
return;
//now you can manipulate the current element
console.log(current);
}
well ... you should either learn javascript, DOM, HTML and CSS or hire an somebody that can do it.
in my opinion the latter would come cheaper.
if not,
here goes something to put in your script.js file.
the checkboxes must have the id="toggleTextareas" respectively id="toggleInputs".
(function isolateScope() {
tryInit();
function tryInit() {
if(document.readyState!="complete"){
setTimeout(tryInit, 100);
}else{
createUI();
init();
}
}
function createUI(){
var div=document.createElement("div");
div.className="addon-floating-toolbar"
div.style.position="fixed";
div.style.zIndex="999999";
div.style.background="#EEE";
div.style.padding="5px";
div.innerHTML='<input type="checkbox" id="toggleTextareas">toggle Textareas<br>'
+'<input type="checkbox" id="toggleInputs">toggle Inputs';
document.body.appendChild(div);
}
function init() {
var tta=document.getElementById("toggleTextareas");
var ti=document.getElementById("toggleInputs");
var textareaVisible=true;
var inputVisible=true;
tta.onclick=toggleTextareas;
ti.onclick=toggleInputs;
function toggleTextareas() {
var elms=document.querySelectorAll("textarea");
textareaVisible=!textareaVisible;
if (textareaVisible) {
show(elms);
}else{
hide(elms);
}
}
function toggleInputs() {
var elms=document.querySelectorAll("input");
inputVisible=!inputVisible;
if (inputVisible) {
show(elms);
}else{
hide(elms);
}
}
function show(collection) {
for (var i = 0; i < collection.length; i++) {
collection[i].style.display="";
}
}
function hide(collection) {
for (var i = 0; i < collection.length; i++) {
collection[i].style.display="none";
}
}
}
})();
let me know if it works,
cheers.
You can traverse all your fields and generate a checkbox that will toggle it open/close for each of your fields. Also set the checkbox label as innerText of the corresponding field.
// Block to be run
generateCheckboxes = function() {
var button = document.getElementById("generateButton");
button.parentNode.removeChild(button);
// grab all elements with the class, .field-summernote
var uiblocks = [].slice.call(document.querySelectorAll('.field-summernote')).filter(function(x) {
return x.className.indexOf('editoraccvar') >= 0
});
if (!uiblocks.length) return;
var chcontainer = document.createElement('div');
chcontainer.style.display = "inline-block";
document.body.insertBefore(chcontainer, document.body.children[0]);
uiblocks.forEach(function(x) {
var cdiv = document.createElement('div');
var clabel = document.createElement('label');
clabel.innerHTML = x.innerText.trim();
var cinput = document.createElement('input');
cinput.type = 'checkbox';
cinput.checked = true;
cinput.onchange = function(ev) {
var checked = this.checked;
x.style.display = checked ? "" : "none";
}
cdiv.appendChild(clabel);
cdiv.appendChild(cinput);
cdiv.appendChild(document.createElement('br'));
chcontainer.appendChild(cdiv);
})
};
#container {
width: 150px;
}
input {
float: left;
}
label {
width: 120px;
display: block;
float: right;
text-align: left;
}
<button onclick="generateCheckboxes()" id="generateButton">Generate Checkboxes</button>
<div id="example" class="field-summernote editoraccvar">
<br/>
<br/>
<span>Zero</span>
<br/>
<textarea></textarea>
</div>
<div id="example1" class="field-summernote editoraccvar1">
<br/>
<br/>
<span>One</span>
<br/>
<textarea></textarea>
</div>
<div id="example2" class="field-summernote">
<br/>
<br/>
<span>Two</span>
<br/>
<textarea></textarea>
</div>
Fiddle

Boolean test HTML textbox input compared to array values

I am trying to create a single textbox form on a webpage to boolean test the input submitted by the user. The input will be the website user's zip code. I want to make a predetermined array of zip codes that will test true.
If it is true (the zip code entered is included in the predetermined array), I want to display one bit of HTML, and if it tests false, I want to display another bit.
I've searched around and looked in some of my JavaScript books (I've just started learning) and haven't found an answer; could someone help me out with this? Thanks!
HTML:
<label id="input-label" class="invalid">
ZIP code: <input id="zipcode" />
<div class="valid-message">
Valid
</div>
<div class="invalid-message">
Invalid
</div>
</label>
CSS:
#input-label.valid .valid-message { display: block; }
#input-label.valid .invalid-message { display: none; }
#input-label.invalid .valid-message { display: none; }
#input-label.invalid .invalid-message { display: block; }
Javascript
function isValidZip(z) {
return ['12345','67890'].indexOf(z) != -1;
}
var label = document.getElementById('input-label');
var input = document.getElementById('zipcode');
input.onkeydown = function() {
label.className = isValidZip(input.value) ? "valid" : "invalid";
}
You could try something like this(might be a little off I'll double check then get back to you :) ):
var zipArr = ['98671','97006'];//insert the zip/post codes here
var userInputEl = document.getElementById('userInput');//Get the element could use tag names or it would be better actually if you used jQuery but yeah
var elToShow = document.getElementById('elementToShowIfNotFound');
var otherElToShow = document.getElementById('idOfOtherelementToShow');
var userInput = userInputEl.value();//might be .text()
if(zipArr.indexOf(userInput) === -1){//-1 means it isn't found in the array
zipArr.push(userInput);//pushes the new one onto the array
elToShow.style.display = 'block';//this changes the css display to block instead of it being hidden.
}else{
otherElToShow.style.display= 'block';
}
Might not be the best way to do this, but I'd suggest using jQuery it makes this process a lot easier.

Categories

Resources