Keeping Textboxes Hidden using Javascript - javascript

I have 5 text boxes pre-defined in a form.
Is it possible to use JQuery/JavaScript to:
1. Keep only one textbox visible when the page containing the form is loaded.
2. Can there be A more link/button to show the other 4 text boxes, one at a time.
3. Can we disable the link/button from adding another text box, because only 5 textboxes are predefined.
I am working with "securefiles" type in CouchCMS. And have to achieve this at the front end.
My current front definition of the text boxes are:
<cms:input type="bound" name="ibox1" /><br /><br />
<cms:input type="bound" name="ibox2" /><br /><br />
<cms:input type="bound" name="ibox3" /><br /><br />
<cms:input type="bound" name="ibox4" /><br /><br />
<cms:input type="bound" name="ibox5" />
And the bounded type is defined as:
for each textbox.

Of course it's possible. You can have a div container for all your predefined inputs, and when a new one is created, put it below the last one.
HTML:
<div id="where_boxes_go">
<input type="bound" name="ibox1">
<input type="bound" name="ibox2">
<input type="bound" name="ibox3">
<input type="bound" name="ibox4">
<input type="bound" name="ibox5">
</div>
<span class="more-inputs">Add</span>
CSS
.hidden {
display: { none; }
}
JQUERY
$(document).ready(function() {
$(".more-inputs").on("click", function() {
$(".form").each(function() {
if( $(this).hasClass("hidden") ) {
$(this).removeClass("hidden");
return false;
}
});
});
});
This will make that your text, or bounds, our whatever you want starts hidden except the first one. If you click the Add button, it will show the next one.
It won't matter if there is no more text boxes, the button won't do anything, you will have to check inside the each() function if a counter reached 5, and then add a class for changing it's CSS to one that make the user know that he can use the button.
Demo: http://jsfiddle.net/3sex8mqf/1/

You could do the following in jQuery.
Demo#fiddle
var $inputs = $("input[type='bound']"), count = 0;
$inputs.first().show();
$(".more").on("click", function(e) {
e.preventDefault();
count++;
$inputs.filter(":eq("+count+")").show();
if ($inputs.length === count + 1) {
$(this).hide();
}
});
HTML:
<input type="bound" name="ibox1" /><br /><br />
<input type="bound" name="ibox2" /><br /><br />
<input type="bound" name="ibox3" /><br /><br />
<input type="bound" name="ibox4" /><br /><br />
<input type="bound" name="ibox5" />
<button class="more" style="cursor: pointer">Show More</button>
CSS:
input[type="bound"] { display: none; }
/* OR
input { display: none; }
*/

Related

scrollIntoView() not activating

I am writing a page, where you click a button, a new div gets created and appended to the end of the page. After the div is drawn I want the page to scroll to it, but it's not working.
All the drawing etc. all works fine.
Inside the console, when I manually execute the scrollIntoView
function on any of the elements, it works just fine, i.e., the screen does indeed scroll to that div just fine.
Somehow this clicking thing is ruining the scroll? Maybe the browser doesn't allow you to scroll to something else right after you release the click?
Here's the codesandbox: https://codesandbox.io/s/wild-framework-uiz9t0?file=/src/index.js:0-232
Here's the code copied over from codesandbox.
html
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
scroll
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div
style="height: 100px; width: 100px; background-color: yellow;"
id="yellow_box"
>
yellow box
</div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<script src="src/index.js"></script>
</body>
</html>
javascript
function scrollYellowBox() {
const box = document.getElementById("yellow_box");
box.scrollIntoView();
}
const btn = document.getElementById("btn-scroll");
btn.addEventListener("click", scrollYellowBox);
Found a tutorial here where it seems to work on a click: https://www.javascripttutorial.net/javascript-dom/javascript-scrollintoview/. But don't see how what they're doing is different from what I'm doing...
Update: so seems like there's a behavior where if you click on a link / button, the browser automatically scrolls to that thing you just clicked. Which I guess makes sense but in this case I need to override it somehow?
Thanks!
Your button is not really a button: <button /> but a link <a />. By default the link will always try to navigate to the location defined by the href attribute. In your case this causes the browser to scroll to the yellow box and then back to the root of the document.
You can fix the issue by either making the button a real button
like so:
<button id="btn-scroll" class="btn">scroll</button>
You can also prevent the default behavior of the link or any other clickable element; by calling preventDefault() on the passed event at the beginning of the event handler callback, like so:
function scrollToYellowBox (e) {
e.preventDefault()
const box = document.getElementById("yellow_box");
box.scrollIntoView();
}
Your btn is a link pointing to #, which default behavior is scrolling the page to top. Change the link to a real button, or prevent the link default behavior:
function scrollYellowBox(e) {
// stop the default behavior
e.preventDefault();
// your other logics
// ...
}

set javascript variable using html attribute

I am trying to re-create the functionality of https://chriscoyier.net/ where you have a form with radio buttons, and as you click a radio button, the text changes.
What I started with was:
window.onload=function() {
document.getElementById("hidden_elements").style.display="none";
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick=radioClicked;
}
function radioClicked() {
if (this.value == "two") {
document.getElementById("hidden_elements").style.display="block";
} else {
document.getElementById("hidden_elements").style.display="none";
}
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<div id="hidden_elements">
Input 1: <input type="text" id="intext" />
Input 2: <input type="text" id="intext2" />
Input 3: <input type="text" id="intext3" /><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
This allows me hide or display the div with id="hidden_elements" if input number 2 is selected.
What I want to do is hide or display the individual elements of "hidden_elements" based on the input 1, 2 or 3.
I tried changing the "hidden_elements" attributes to:
<div id="hidden_elements">
Input 1: <input type="text" name="one" />
Input 2: <input type="text" name="two" />
Input 3: <input type="text" name="three" /><br /><br />
</div>
and JS to:
var hide = document.getElementById("hidden_elements");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
function radioClicked() {
document.getElementsByName(this.value).style.display = "block"
}
But that doesn't work either.
I've tried a less appealing approach using if/else statements, but that too doesn't work.
<div id="paragraphs">
<div id="hidden_element" name="one">Paragraph 1 </div>
<div id="hidden_element" name="two">Paragraph 2 </div>
<div id="hidden_element" name="three">Paragraph 3 </div>
</div>
function radioClicked() {
if (this.value == "one") {
document.getElementById("hidden_element_one").style.display="block";
} else if (this.value == "two") {
document.getElementById("hidden_element_two").style.display="block";
} else if (this.value == "three") {
document.getElementById("hidden_element_three").style.display="block";
}
}
I've tried a few more approaches but the behaviour isn't what I want. Any idea how I can change the display from "none" to "block" based on the selected radio-button? (I know you can do it with JQuery but I'm trying to learn Javascript)
A few notes:
getElementsByName returns a list of elements. That list doesn't have a style property (the entries on the list do).
ids must be unique, you can't put the same ID on multiple elements. Use a class to group elements together.
data-* attributes would probably be a better choice than name, since you can use them on any element type.
If you want to show/hide elements based on the radio button value, you'll need to select all of the elements you show/hide, not just the one matching the radio button's value. Then loop through that list, showing/hiding depending on whether they match the selected value.
The load event happens very late in the page load cycle (e.g., right at the end). Instead of using load, put your script tags at the very end of your document, just before the closing </body> tag, and do your event hook-up immediately.
I'd probably use a class to toggle visibility rather than style.display.
You can get the attribute from an element via getAttribute.
You can use querySelectorAll to get a list of elements matching any CSS selector. Use it on document to look globally, or on a specific element to only look within that element. For instance, to get a list of elements in the document with an attribute called data-val, you'd use the CSS selector [data-val], e.g. `document.querySelectorAll("[data-val]").
Here's a version of your snippet with some minimal updates; see comments:
// I'd use querySelectorAll rather than the old-style
// forms and elements collections (but those work too)
var radios = document.querySelectorAll("#picker input[type=radio]");
// Initial value is 0, not [0]
for (var i = 0; i < radios.length; i++) { // You were missing { on this line
// Recommend modern event handling, not onclick
radios[i].addEventListener("click", radioClicked);
}
function radioClicked() {
var hidden = document.getElementById("hidden_elements");
hidden.classList.remove("hidden");
// Get all elements within it that have a data-val attribute
var list = hidden.querySelectorAll("[data-val]");
for (var i = 0; i < list.length; ++i) {
var el = list[i];
// Add/remove the hidden class depending on whether it matches
el.classList.toggle("hidden", el.getAttribute("data-val") != this.value);
}
}
.hidden {
display: none;
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<!-- Hide this initially with markup rather than code -->
<div id="hidden_elements" class="hidden">
<!-- Use data-val to identify them -->
Input 1: <input type="text" data-val="one" />
Input 2: <input type="text" data-val="two" />
Input 3: <input type="text" data-val="three" /><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
Some further changes you might make:
Wrap all the code in an IIFE so nothing is global.
Wrap the inputs and their labels in label elements, and toggle the visibility of them rather than the inputs directly.
Wrap things in containers for line breaks rather than using br.
You could do something like this :
Add a common class on the elements you want to toggle (can wrap label and field in span)
Toggle their display, can use a css class for hiding and a class same as the value of the checkbox
function radioClicked(e) {
//hide previously shown
var elem = document.getElementById("hidden_elements").getElementsByClassName("shown")[0];
if (elem) {
elem.classList.remove("shown");
elem.classList.add("hide");
}
//show currently selected
elem = document.getElementById("hidden_elements").getElementsByClassName(e.value)[0];
elem.classList.remove("hide");
elem.classList.add("shown");
}
.hide {
display: none;
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" onclick="radioClicked(this)" />
Item 2: <input type="radio" name="group1" value="two" onclick="radioClicked(this)" />
Item 3: <input type="radio" name="group1" value="three" onclick="radioClicked(this)" /><br />
<br />
<div id="hidden_elements">
<span class="hide one elem">Input 1: <input type="text" id="intext" /></span>
<span class="hide two elem">Input 2: <input type="text" id="intext2" /></span>
<span class="hide three elem">Input 3: <input type="text" id="intext3" /></span>
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
My solution changes the values of the radio buttons to the numeric value rather than the the text value. This enabled it to be used to select the input element by id and appending the number.
Each time radioClicked() is run it hides all the inputs and only shows the selected one. To do this I've wrapped all the inputs and their labels in span elements.
window.onload=function() {
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick=radioClicked;
}
function radioClicked() {
var allRadio = document.querySelectorAll('#hidden_elements span');
Array.prototype.forEach.call(allRadio, function(el, i){
el.style.display="none";
});
var selectedRadio = this.value;
document.getElementById("intext" + selectedRadio).parentNode.style.display="block";
}
#hidden_elements span {
display: none;
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="1" />
Item 2: <input type="radio" name="group1" value="2" />
Item 3: <input type="radio" name="group1" value="3" /><br />
<br />
<div id="hidden_elements">
<span>Input 1: <input type="text" id="intext1" /></span>
<span>Input 2: <input type="text" id="intext2" /></span>
<span>Input 3: <input type="text" id="intext3" /></span><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
My solution add extra div for all inputs and id for this div
window.onload = function() {
var hide = document.getElementsByClassName("hidden");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick = radioClicked;
}
function radioClicked() {
var hide = document.getElementsByClassName("hidden");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
document.getElementById("hidden_" + this.value).style.display = "block"
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<div id="hidden_elements">
<div class="hidden" id="hidden_one">Input 1: <input type="text" /></div>
<div class="hidden" id="hidden_two">Input 2: <input type="text" /></div>
<div class="hidden" id="hidden_three">Input 3: <input type="text" /><br /><br /></div>
</div>
<input type="submit" id="submitbutton" value="Send form" />

How to make the submit button a href and image

I'm trying to make my submit button a image and also when clicked it links to another page.
This is the current submit button which works but isn't a href or image
<input type="submit" name="submit" alt="add" onclick="add()" >
These are the multiple methods I've tried but none of them seem to work. Can anyone see where I'm going wrong?
<input type="image" name="submit" src="img/add.png" class="addButton" id="addButton" />
2.
<img src="img/add.png" class="addButton" id="addButton" alt="add button" />
3.
<img src="img/addToBookmarks.png" class="addButton" id="addButton" alt="add button" />
Lastly the form itself on stadiumLargeSymbol.php:
<form class="form" action="stadiumLargeSymbol.php?submit=true" method="post">
<img id="enlargedSymbol" type="text" size="60" name="pathOfSymbol" src='' />
<br />
<input class="inputBox" type="hidden" name="pathOfSymbol" id="pathOfSymbol" />
<script>
var querySrc = URI(window.location.href).search(true).src;
$("#enlargedSymbol").prop("src", querySrc);
$('#pathOfSymbol').val(querySrc);
</script>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br/>
<input type="submit" name="submit" alt="add to bookmarks button" onclick="add()" >
</form>
Check this link:
https://jsfiddle.net/0e2rykap/
<html>
<body>
<h1>
<button type="submit" class="btn_submit">
<img src="http://www.smartwebby.com/imgs/tutorials/fireworks/website-design/submit-button.jpg" />
</button>
</h1>
</body>
</html>
you can use javascript to mimick the href redirection
Try giving id to div where your image is being rendered, Assuming id of your div is "divImage",You can write following is JS :
$("#divImage").click(function(){
//On Click Event
});
You can write your form submission code and redirecting code inside "on-click" event.Your problem will be solved.
Apply a background image to the submit button using css.
// html
<input type="submit" name="submit" alt="add" onclick="add()" >
// css
form input[type=submit]{
background-image: url('img/example.png');
}
And add other styling properties as necessary. Don't forget to remove the border and such from the button in the css.
Instead of input type submit
Use a div , inside div set a image tag like below
<div id="yoyo">
<img src="whateva" />
</div>
Now on click of img tag ID or Div ID , submit the form.
Like :
$( "#yoyo" ).click(function() {
$( "#FormID" ).submit();
//or if you want to redirect than
window.location.href = "http://stackoverflow.com";
});

Dynamically show dropdown select list to improve performance

I have a page where users edit a grid of data that contains up to 400 form fields. Think inline editing of a table.
The problem is where most of the form fields are select dropdowns, some of which can contain up to 1,000 options.
This is causing browsers to use a lot of memory, and to run far too slowly.
Is there some way to improve performance here, perhaps by dynamically filling the dropdown every time it's clicked, and clearing all but the selected option when leaving the dropdown?
I personally wouldn't advise clearing all other options from a select dropdown when a user selects one, in case they select the wrong one.
If you still would like to do this, use something similar to the following, to achieve it:
HTML Example
<select id="long_select">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
<option value="4">test4</option>
<option value="5">test5</option>
</select>
JavaScript Example
// ITERATE THROUGH ALL SLEECTS ON THE PAGE, ADDING A FUNCTION TO THEIR 'onchange' EVENT HANDLER, WHICH WILL EXECUTE WHEN THE USER CHANGES THE SELECTS OPTION
var selects = document.getElementsByTagName('select');
var len = selects.length;
while(len--)
{
selects[len].onchange = select_delete;
}
// THIS FUNCTION CAPTURES THE SELECTED OPTION, CLEARS ALL OPTIONS AND APPENDS THE SELECTED OPTION TO THE SELECT'S OPTIONS COLLECTION, LEAVING ONLY ONE OPTION
function select_delete()
{
var item = this[this.selectedIndex];
this.options.length = 0;
this.appendChild(item);
}
And here's a working JSFiddle: http://jsfiddle.net/93o0qphv/1/
EDIT:
To dynamically populate select elements, you can create new option element, set it's 'text' and 'value' properties, and add it to the desired select.
HTML
<select id="first_select"></select>
JAVASCRIPT
// POINTER TO DESIRED SELECT
var select = document.getElementById('first_select');
// ARRAY HOLDING ONE OBJECT PER OPTION
var options_array = [{"textvar":"Option 1","valuevar":1},{"textvar":"Second option","valuevar":2}];
// ITERATE THROUGH ARRAY, USING EACH OBJECTS 'textvar' AND 'valuevar' AS THE NEW OPTIONS 'text' AND 'value' PROPERITES, THEN ADD NEW OPTION TO THE SELECT
for(var c=0;c<options_array.length;c++)
{
var new_option = document.createElement('option');
new_option.text = options_array[c].textvar;
new_option.value = options_array[c].valuevar;
select.appendChild(new_option);
}
Here's an example: http://jsfiddle.net/ShadeSpeed/gxxugp6v/
I hope this helps!
Dan.
I've had to do something similar before.
One of your options is to AJAX load options for select boxes that are visible on the page at the current moment. So something like this: (Fiddle for if the code snippet doesn't work)
function checkScroll(el) {
var top_of_object = el.offset().top;
var top_of_window = $(window).scrollTop();
var bottom_of_object = el.offset().top + el.outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if ((top_of_object > top_of_window && bottom_of_object < bottom_of_window) && el.is(':empty')) { // If the element is in view and it's empty
el.load('ajax/MyURL?Select=thisSelect'); //Run ajax call to populate the element
} else if (top_of_object < top_of_window || bottom_of_object > bottom_of_window) {
el.empty(); // Empty elements not in view
}
}
function fireScroll() {
$('select').each( function() { //Loop through all selects
checkScroll($(this));
});
}
var timer;
$(window).scroll(function(){
timer && clearTimeout(timer);
timer = setTimeout(fireScroll, 100); // Make it only fire when you stop scrolling
});
fireScroll();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select><select></select>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<select></select><select></select>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<select></select><select></select>
You AJAX call would then just need to return a string that was something like <option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option><option>MyOption</option>

How to find all child elements with a class and check if any are empty?

I have a form and need to check to make sure any child inputs of a fieldset are empty. How can I accomplish this using jQuery?
if any fields with .required are empty
-> there are fields that have not been filled out
if all fields with .required have been filed out
-> they have all been filed out
Select your fields by form id and class name. Then use .filter() to reduce your set to include only the fields that have not been filled out:
var emptyFields = $("#myForm .required").filter(function()
{
return $(this).val() == "";
});
If you don't want to do anything with the fields, but just need a boolean:
var anyEmptyFields = !!emptyFields.length;
Try this:
var emptyRequiredFields = jQuery("#post-form .required:input").not("[value]");
Try this:
<fieldset id="myForm">
<input type="text" required="true" /><br />
<input type="check" required="true" /><br />
<input type="radio" required="true" /><br />
<input type="text" required="false" /><br />
<input type="check" required="" /><br />
<input type="radio" /><br />
<button onclick="$('#myForm').find('input[required=true]').after('<span>null</span>');">Check</button>
</fieldset>
Try this one:
$("form[name=form_name] .required").each(function(index,e){
if(e.value == ''){
alert(e.name+' field is required!');
}
});

Categories

Resources