Display required fields on click with Javascript - javascript

I'm trying to display required fields on click with javascript. I have large form and inside of that form I have some required fields. Idea is to have button so that user can click (like toggle) and see only required fields?
So far my approach is something like this:
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {} else document.getElementById('ifYes').remove();
}
<button onclick="javascript:yesnoCheck();" id="yesCheck">Click</button>
<div id="ifYes">
<input type="text" name="usrname" required>
</div>
<div>
<input type="text" name="company" required>
</div>
What is the best way to this?

In case you really want to toggle the optional fields, you could just hide all optional elements in form (like in this example).
Keep in mind that yu may want to change the css selector to have more control what elements you want to hide.
eg:
form input:not([required]),
form select:not([required]),
form textarea:not([required]), ....
You may also want to not just hiden those fields but style them differently (opacity or something like that).
function toggleOptionalFields() {
document.querySelectorAll('form > :not([required])').forEach(field => field.hidden = !field.hidden);
}
<form>
<input required value="i am required" />
<input />
<select required>
<option value="1">required! :)</option>
</select>
<input />
<input />
<input required value="i am required too" />
</form>
<button onclick="toggleOptionalFields()">Toggle optional fields</button>
Also this function will not in IE because querySelectorAll().forEach and the arrow function are not supportet.
You could easily change that by using a regular function instead of the arrow-function and iterate differenttly thru the elementlist (eg, for(;;) or [].forEach.call(document.querySelectorAll(), function(element) {...});, ...).

Show and hide optional fields using button click
function toggleOptional(event){
var button = event.currentTarget;
var action = button.getAttribute('data-action');
//var optionalFields = document.querySelectorAll("form input:not([required])");
var optionalFields = document.querySelectorAll("form :not([required])");
if(action == "hide"){
optionalFields.forEach(function(value){
value.style.display = "none";
});
button.setAttribute('data-action','show');
button.innerText = "Show Optional ";
} else {
optionalFields.forEach(function(value){
value.style.display = "inline-block";
});
button.setAttribute('data-action','hide');
button.innerText = "Hide Optional";
}
}
input,textarea,select {
width : 70vw;
}
<button onclick="toggleOptional(event)" data-action="hide" >Hide Optional</button>
<form>
<input type="text" name="usrname" placeholder="usrname" required>
<input type="text" name="phone" placeholder="phone" required >
<input type="text" name="company" placeholder="company" >
<select name="birthyear" required >
<option value="">Select Year of Birth</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
</select>
<textarea required name="description" placeholder="description" ></textarea>
</form>

If you want to do it in javascript then here is a simple solution
Javascript
function yesnoCheck() {
var x = document.getElementById("ifYes");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
CSS
#ifYes{
display: block;
}

You can take a boolean variable and toggle its value and show or hide your elements based on it.
var toggleIfYes=false;
function yesnoCheck() {
toggleIfYes=!toggleIfYes
if (toggleIfYes) {
//show the elements
} else{
//hide the elements
}
}
<button onclick="javascript:yesnoCheck();" id="yesCheck">Click</button>
<div id="ifYes">
<input type="text" name="usrname" required>
</div>
<div>
<input type="text" name="company" required>
</div>

You could wrap all fields in the container like <div> or <form>
HTML
<div class="container">
<input required />
<input />
<input required />
</div>
then your toggle button function should toggle a class in the container
Javascript
function yesnoCheck() {
let container = document.querySelector('.container')
container.classList.toggle('only-required')
}
now you can use CSS to hide the non-required field if the container has a class only-required
CSS
.container.only-required input:not([required]) {
display: none;
}

You're using document.getElementById('ifYes').remove() which removes the element from the DOM. This way you won't be able to recover your element when you click the toggle button again. Also, you're verifying a <button/> element as if it were an <input type="checkbox" /> so you might want to use a checkbox instead.
You'd be better off using document.getElementById('ifYes').style.display = 'none' as it fits best in this situation:
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'none';
}
else {
document.getElementById('ifYes').style.display = '';
}
}
<input type="checkbox" onclick="javascript:yesnoCheck();" id="yesCheck">Click</input>
<div id="ifYes">
<input type="text" name="usrname" required>
</div>
<div>
<input type="text" name="company" required>
</div>

Related

When button is clicked, display the value on my textbox

newbie here. My target is when is when I click the button, my 2nd textbox will do the copy without comma. How can I make this work? I provided my JS fiddle and codes below. Any help will be appreciated. Thank you
JS Fiddle: https://jsfiddle.net/rain0221/auk4rfdg/6/ // I provided more explanation here
html:
<input type="text" value="" class="form-control" id="box"/>
<input type="text" value="" id="textbox2" required name="amount1" min="100" autocomplete="off"/>
<input id="bet4" class="amount btn btn-success" type="button" onclick="showme('5,000')" value="5000">
script:
//this function copies the textbox1 values with autocomma and produces same value but without comma on textbox2
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#box').on('keyup',function(){
updateTextView($(this));
});
});
//this function shows the value of my button to the textbox
$(document).ready(function(){
$("#bet4").on("click", function(e)
{
e.preventDefault();
let box = $("#box").val();
$("#betAmountResult").html(box);
})
})
function showme(count){
document.getElementById("box").value=count;
}
When 5000 clicked, change textbox2 value!
Code snippet:
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#box').on('keyup',function(){
updateTextView($(this));
});
});
$(document).ready(function(){
$("#bet4").on("click", function(e)
{
e.preventDefault();
let box = $("#box").val();
$("#betAmountResult").html(box);
})
})
function showme(count){
document.getElementById("box").value=count;
document.getElementById("textbox2").value=count.replace(',','');
}
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<input type="text" value="" class="form-control" placeholder="autocomma textbox" id="box"/>
<input type="text" value="" placeholder="same value but no comma" id="textbox2" required name="amount1" min="100" autocomplete="off"/>
<input id="bet4" class="amount btn btn-success" type="button" onclick="showme('5,000')" value="5000">
document.addEventListener("input", action)
document.addEventListener("click", action)
function action(ev){if (ev.target.tagName=="INPUT"){
const ch=ev.target.closest("div").children;
if(ev.target!=ch[1])
ch[1].value=(ev.target.value-0).toLocaleString()
if(ev.target==ch[2])
ch[0].value=ev.target.value;
}}
<div>
<input type="text" value="" class="form-control" required/>
<input type="text" value=""/>
<input class="amount btn btn-success" type="button" value="5000">
</div>
<div>
<input type="text" value="" class="form-control" required/>
<input type="text" value=""/>
<input class="amount btn btn-success" type="button" value="2000000">
</div>
I wrote my snippet without jQuery as it is not really needed here and I reversed the roles of the input fields as it is
a better user experience if the input is not tampered with directly
difficult to "undo" a .toLocaleString(), see here
The trigger for action is the input event which also includes paste actions done via mouse clicks.
I also removed the id attributes from your input values. This way you can add further input groups to your page and re-use the script without further change.
All my addEventListener() actions are done in the "delegated" mode, to the parent document. By doing it this way the event will also be triggered by dynamically added elements (elements that might get added through some user interaction).

Trying to create a form that would give a print window containg form data

As my title suggests, I'm trying to create a form that would take some user input like Name, Age, Gender, Hobbies, Contact details & Photo etc. (basically I'm thinking of making a simple local html based application that would create RESUME), and after taking user input, supposedly after clicking on the submit button it should create a new print window where every entered data should be arranged in a resume like format including photo.
This is what I'm trying for my input page...(ps: it's incomplete!!! most of my script part is just Ctrl+C & Ctrl+V 🤣
<!DOCTYPE html>
<html>
<head>
<title>Resume maker</title>
</head>
<body>
<div id="BMain" class="body">
<h1>Please enter your resume data!</h1>
<form action="#">
<p>Name</p>
<input type"text" id="name" name="name">
<p>Mother's name</p>
<input type"text" id="mName" name="mName">
<p>Father's name</p>
<input type"text" id="fName" name="fName">
<p>Gender</p>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<div class="container" id"dobPick">
<p>Date of Birth</p>
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker3'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker3').datetimepicker({
format: 'L'
});
});
</script>
</div>
</div>
<label for="myfile">Upload your photo:</label>
<input type="file" id="myPic" name="myPic"><br><br>
<input type="submit">
</form>
After clicking on the submit button I'm expecting a print window with predefined background image like some vector art or some stamp like image or some pattern, well that's post work.
This is how my print window should be looking...
Print window
Any help on this mates..... at this stage scripts looks too messy to me. I'm excited to try this on my browser.
My question is how can I make it happen or rather I say what should I do or add into my input page to get the desired output I'm expecting? My above code was just a conceptual example.
The easiest way to do this would be to add a second div element to the page outside of your form. Once the form is validated and submitted, it can be hidden and the second div can be populated with that information. You can then use CSS media queries (there are print-specific queries) and trigger the print() method in Javascript. You would need to include the following in your html file:
<link rel = "stylesheet" type = "text/css" media = "print" href = "mystyle.css">
Then, if your markup were to look like this:
<div id="resumeform">
<input id="name" type="text" />
<input id="age" type="text" />
<input id="address" type="text" />
<input id="height" type="text" />
<input id="btnSubmit" type="button" value="Submit Info"/>
</div>
<div id="result">
<span id="r_name"></span>
<span id="r_age"></span>
<span id="r_address"></span>
<span id="r_height"></span>
</div>
Your JS could look like this:
var btn = document.getElementById("btnSubmit");
btn.addEventListener("click", btnHandler);
function btnHandler(el){
var resumeform = document.getElementById("resumeform");
var result = document.getElementById("result");
var name = document.getElementById("name");
var age = document.getElementById("age");
var address = document.getElementById("address");
var height = document.getElementById("height");
var r_name = document.getElementById("r_name");
var r_age = document.getElementById("r_age");
var r_address = document.getElementById("r_address");
var r_height = document.getElementById("r_height");
r_name.innerHTML = name.value;
r_age.innerHTML = age.value;
r_address.innerHTML = address.value;
r_height.innerHTML = height.value;
resumeform.style.display = "none";
result.style.display = "block";
window.print();
}
And your CSS could look like this:
#resumeform {
display: block;
}
#result {
display: none;
}
input {
width: 200px;
display: block;
margin: 10px;
}
#media print {
span {
/* Your CSS rules would go here */
}
}
Working Fiddle:
https://jsfiddle.net/9apfwjxz/

Change text on the button [duplicate]

This question already has answers here:
How do I change the text of a span element using JavaScript?
(18 answers)
Closed 3 years ago.
I have a form and I have a button that is filtering some required fields. It's all working nicely but I want to also change the text of the button.
For example: by default it displays you all fields in the form, when you click the button (show required fields) it displays you only required fields, here I want change text on the button to displays text (Show all).
Here is my code:
<button type="checkbox" onclick="yesnoCheck();" id="yesCheck" value="Show required fields">Show required fields</button> <br>
<div id="ifYes">
<input type="text" value="" /> One
<input type="text" value="" />Two
<input type="text" value="" />Three
<input type="text" value="" required/>Four
</div>
JS:
function yesnoCheck() {
var x = document.getElementById("ifYes");
if (x.style.display === "none") {
x.style.display = "flex";
} else {
x.style.display = "none";
}
}
Basically, when you click the button to show the required fields I want to change text to "Show all".
Is this what you're looking for?
function yesnoCheck() {
var x = document.getElementById("ifYes");
var button = document.getElementById("yesCheck");
if (x.style.display === "none") {
x.style.display = "flex";
button.textContent = "Show required fields";
} else {
x.style.display = "none";
button.textContent = "Show All";
}
}
<button type="checkbox" onclick="yesnoCheck();" id="yesCheck" value="Show required fields">Show required fields</button> <br>
<div id="ifYes">
<input type="text" value="" /> One
<input type="text" value="" />Two
<input type="text" value="" />Three
<input type="text" value="" required/>Four
</div>

How do I disable textarea on checkbox click?

How do I disable the textarea onclick of the checkbox?
<p>What caused the damage?</p>
<textarea rows="5"></textarea>
<input type="checkbox">
<label>I don't know</label>
This code should work as what you intend to achieve.
$('#checkbox').on('click', function(){
if($("#checkbox").is(":checked")){
$('#textArea').val('');
$('#textArea'). attr('disabled','disabled');
}else{
$('#textArea').removeAttr('disabled');
}
}
);
Using the disabled property of a <textarea> liike <textarea disabled>.
let checker = document.getElementById("checker");
let textInput = document.getElementById("textInput");
checker.addEventListener('click', () => textInput.disabled = checker.checked);
<p>What caused the damage?</p>
<textarea id="textInput" rows="5"></textarea>
<input type="checkbox" id="checker">
<label>I don't know</label>
The HTML Markup consists of a CheckBox and a TextBox which is by default disabled using the disabled attribute. The CheckBox has been assigned a JavaScript OnClick event handler.
When the CheckBox is clicked, the EnableDisableTextBox JavaScript function is executed. Inside this function, based on whether CheckBox is checked (selected) or unchecked (unselected), the TextBox is enabled or disabled by setting the disabled property to false or true respectively.
<script type="text/javascript">
function EnableDisableTextBox(chkPassport) {
var txtPassportNumber = document.getElementById("txtPassportNumber");
txtPassportNumber.disabled = chkPassport.checked ? false : true;
if (!txtPassportNumber.disabled) {
txtPassportNumber.focus();
}
}
</script>
<label for="chkPassport">
<input type="checkbox" id="chkPassport" onclick="EnableDisableTextBox(this)" />
Do you have Passport?
</label>
<br />
Passport Number:
<input type="text" id="txtPassportNumber" disabled="disabled" />
var textArea = document.querySelector('#text-area');
var checkbox = document.querySelector('#cbox');
function toggleTextArea() {
var disabled = textArea.getAttribute('disabled');
if (disabled) {
textArea.removeAttribute('disabled');
} else {
textArea.setAttribute('disabled', 'disabled');
}
}
checkbox.addEventListener('click', toggleTextArea);
<p>What caused the damage?</p>
<textarea rows="5" id="text-area"></textarea>
<input type="checkbox" id="cbox">
<label for="cbox">I don't know</label>
I just added a JavaScript that selects the text area and enable and disable it based on what your checkbox
<script>
var flagChk = document.getElementById("chk");
function disableBox(){
document.getElementById("myTextArea").disabled = chk.checked;
document.getElementById("myTextArea").enabled = chk.unchecked;
}
</script>
<p>What caused the damage?</p>
<textarea rows="5" id="myTextArea"></textarea>
<input type="checkbox" onclick="disableBox()" id="chk">
<label>I don't know</label>
$('#checker').click(function(){
if($("#checker").is(":checked")){
$('#textInput').attr('disabled',true).val("");
}else{
$('#textInput').attr('disabled',false);
}
});

I am stuck with Checkbox Attribute

I recently start to learn JavaScript and have a question about checkbox Attribute.
I want to put Nickname feature that is if someone want to put his/her nickname, he/she can check the checkbox and it appears the text box for Nickname.
However, when the page is loaded, the text box is there even though the checkbox is not checked.
Can anyone please help me with the problem...?
<fieldset>
<form>
<div>
<label for = "yesNick"> Nickname?:</label>
<input id="yesNick" name="yesNick" type="checkbox" value="yes" onchange="nicknameFunction()"/><br/>
</div>
<div id= "nick">
<label for = "nickname">Nickname:</label>
<input type="text" name="nickname" id="nickname"><br/>
</div>
<input type="submit" value="Vertify"/>
<script type="text/javascript">
function nicknameFunction() {
if (document.getElementById('yesNick').checked){
document.getElementById('nick').style.display="inline";
document.getElementById('nickname').setAttribute('required',true);
}
else{
document.getElementById('nickname').removeAttribute('required');
document.getElementById('nick').style.display="none";
}
}
</script>
</form>
</fieldset>
</p>
Set your initial display for the #nick div to 'none'. Your function only runs on change of the checkbox so you will need to ensure initial state on your own.
function nicknameFunction() {
if (document.getElementById('yesNick').checked){
document.getElementById('nick').style.display="inline";
document.getElementById('nickname').setAttribute('required',true);
}
else{
document.getElementById('nickname').removeAttribute('required');
document.getElementById('nick').style.display="none";
}
}
#nick {
display:none;
}
<fieldset>
<form>
<div>
<label for = "yesNick"> Nickname?:</label>
<input id="yesNick" name="yesNick" type="checkbox" value="yes" onchange="nicknameFunction()"/><br/>
</div>
<div id= "nick">
<label for = "nickname">Nickname:</label>
<input type="text" name="nickname" id="nickname"><br/>
</div>
<input type="submit" value="Vertify"/>
</form>
</fieldset>
You don't need JavaScript for this; in fact, you shouldn't use JS for this because accessing the dom is quite slow. CSS is more than sufficient. You can also make it animated by using width instead of display property, but for my example I only used the display property.
#yesNick:checked ~ #nickname {
display: block;
}
#nickname {
display: none;
}
<div>
<label for = "yesNick"> Nickname?:</label>
<input id="yesNick" name="yesNick" type="checkbox" value="yes"/><br/>
<label for = "nickname">Nickname:</label>
<input type="text" name="nickname" id="nickname"><br/>
</div>
<input type="submit" value="Vertify"/>
try hiding the textbox for the first time :
var nickName = document.getElementById('nick');
nickName.style.display="none";
function nicknameFunction() {
if (document.getElementById('yesNick').checked){
nickName.style.display="inline";
document.getElementById('nickname').setAttribute('required',true);
}
else{
document.getElementById('nickname').removeAttribute('required');
nickName.style.display="none";
}
}

Categories