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";
}
}
Related
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/
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>
I have a some custom validation for a small input form, that checks if a field is required. If it is a required field it alerts the user, if there is no value. At the moment it will validate all inputs other than check boxes.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value)
alert(field.name + ' is required');
});
console.log(fields);
}
</script>
If anyone can work out how to include validation of check boxes, it would be much appreciated.
Even though some answers already provide a solution, I've decided to give mine, that will validate every required input in your form, regardless of being a checkbox (maintaining your each loop).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name">
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
$.each(fields, function(i, field) {
field=$(field).find('input, select, textarea')[0]
if (!field.value || (field.type=='checkbox' && !field.checked))
alert(field.name + ' is required');
});
}
</script>
The problems were:
serializeArray() would try to get the value from your checkbox, and because it returned nothing, the checkbox input was never added to fields!
Checkboxes don't have a property value, instead they are checked
There is more than one way to determine this:
Check the length of the JQuery wrapped set that queries for only checked checkboxes and see if it is 1:
if($("input[name='Check_0']:checked").length === 1)
Check the checked property of the DOM element itself (which is what I'm showing below) for false. To extract the DOM element from the JQuery wrapped set, you can pass an index to the wrapped set ([0] in this case), which extracts just that one item as a DOM element and then you can use the standard DOM API.
if(!$("input[type='checkbox']")[0].checked)
NOTE: It's important to understand that all client-side validation can be easily bypassed by anyone who really wants to. As such, you
should always do a second round of validation on the server that will
be receiving the data.
FYI: You have some invalid HTML: There is no closing tag for input elements and for label elements, you must either nest the element that the label is "for" inside of the label or you must add the for attribute to the label and give it a value of the id of the element that the label is "for". I've corrected both of these things below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="userName" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value){
alert(field.name + ' is required');
}
});
// Check to see if the input is a checkbox and if it's checked
if(!$("input[type='checkbox']")[0].checked){
alert("You must agree to the terms to continue.");
}
}
</script>
Personally (and I'm far from alone on this), the use of JQuery is way overused in today's world. When it came out, the standard DOM API wasn't as mature as it is now and JQuery made DOM element selection and manipulation very simple. Back then, JQuery was a Godsend.
Today, the DOM API has matured and much of what we use to rely on JQuery to make easy, can be done just as easily without JQuery. This means you don't have to reference the JQuery library at all (faster page loading) and you're code follows standards.
If you're interested, here's your code without JQuery:
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="name" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
// Get all the required elements into an Array
var fields = [].slice.call(document.querySelectorAll(".ss-item-required > *"));
// Loop over the array:
fields.forEach(function(field) {
// Check for text boxes or textareas that have no value
if ((field.type === "text" || field.nodeName.toLowerCase() === "textarea")
&& !field.value){
alert(field.name + ' is required');
// Then check for checkboxes that aren't checked
} else if(field.type === "checkbox" && !field.checked){
alert("You must agree to the terms to continue.");
}
});
}
</script>
I'm building a system where the checkbox input will actually be an image, so to check the checkbox, the user would have to click the label(the image would be part of it).
I've written a small code in Javascript with Jquery, and it works initially, but if the user unchecks and wants to check again, it's a nops. Give it a try please, you'll understand it more easily.
I can't share the system so instead I've put just the necessary parts below (no images, just the problem above described - notice that the user could only click on labels on my system and not the checkboxes themselves).
My Javascript/Jquery skills are still very much beginning so sorry for the terrible code. Thanks for your help!
$(document).ready(function () {
$('.negociacao').on('click', 'label', function () {
$(this).closest('div').find('.tatica').prop("checked", true);
if ($(this).closest('div').find('.tatica').checked = true) {
$('.negociacao').on('click', 'label', function () {
$(this).closest('div').find('.tatica').prop("checked", false);
})
}
})
})
.negociacao label {
display: inline-block;
cursor: pointer;
position: relative;
padding-left: 25px;
margin-right: 15px;
z-index: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="negociacao">
<form method="post">
<fieldset>
<div>
<input type="checkbox" class="tatica" value="ana_est">
<label id="ana_est">Análise Estratégica</label>
<br>
</div>
<div>
<input type="checkbox" class="tatica" value="cat_com">
<label id="cat_com">Catálogo de Compras</label>
<br>
</div>
<div>
<input type="checkbox" class="tatica" value="com_cen">
<label id="com_cen">Compras Centralizadas</label>
<br>
</div>
<div>
<input type="checkbox" class="tatica" value="com_spo">
<label id="com_spo">Compras Spot</label>
<br>
</div>
<div>
<input type="checkbox" class="tatica" value="con_cur">
<label id="con_cur">Contrato Curto Prazo</label>
<br>
</div>
<div>
<input type="checkbox" class="tatica" value="ges_con">
<label id="ges_con">Gestão de Contratos</label>
<br>
</div>
<div>
<input type="checkbox" class="tatica" value="ges_ris">
<label id="ges_ris">Gestão de Risco de Fortalecimento</label>
<br>
</div>
<div>
<input type="checkbox" class="tatica" value="pad_esp">
<label id="pad_esp">Padronização das Especificações</label>
<br>
</div>
<div>
<input type="checkbox" class="tatica" value="sou_ppu">
<label id="sou_ppu">S. Sourcing - PPU</label>
<br>
</div>
<div>
<input type="checkbox" class="tatica" value="sou_tca">
<label id="sou_tca">S. Sourcing - TCA</label>
<br>
</div>
</fieldset>
</form>
</div>
You have an assignment = when you meant to compare with ==:
if ($(this).closest('div').find('.tatica').checked = true
should be
if ($(this).closest('div').find('.tatica').checked == true)
or just
if ($(this).closest('div').find('.tatica').checked)
However the code as written will then always be true as you just set it on the previous line.
The next problem is nesting click handlers. You just do not do that.
The whole problem can be simplified to the following:
$(document).ready(function () {
$('.negociacao').on('click', 'label', function () {
// Find the associated checkbox
var $check = $(this).closest('div').find('.tatica');
// Toggle the checked on/off
$check.prop("checked", !$check.prop("checked"));
})
})
hello,
I'm trying to select hidden radio input when selecting another one
<div class="questions">
<div class="questions_title">
<span> Q : What Are you doing now ?</span>
</div>
<div class="answers">
<script>
$('#answerid_').on('checked', function() {
$('#degres_').prop('checked', true);
return false;
});
</script>
<div class="field">
<input type="radio" value="1915" id="answerid_1" name="answerid_1" class="required">
<input type="hidden" value="0" id="degres_1" name="degres_1">
<span class="questions_label">Working. </span>
</div>
<div class="field">
<input type="radio" value="1916" id="answerid_2" name="answerid_1">
<input type="hidden" value="1" id="degres_2" name="degres_1">
<span class="questions_label">Playing.</span>
</div>
<div class="field">
<input type="radio" value="1917" id="answerid_3" name="answerid_1">
<input type="hidden" value="2" id="degres_3" name="degres_1">
<span class="questions_label">not Sleeping </span>
</div>
<div class="field">
<input type="radio" value="1918" id="answerid_4" name="answerid_1">
<input type="hidden" value="3" id="degres_4" name="degres_1">
<span class="questions_label">Nothing.</span>
</div>
</div>
I need => When selecting any answer the according next hidden degree would be checked too
You can't check a hidden-type input. However, you can check a radio-type invisible input (with display:none style).
it should be..
$('[id^=answerid_]').on('change', function() {
$(this).next().prop('checked', true);
return false;
});
You need wild card to attach event and change event.
Live Demo
$('[id^=answerid_]').on('change', function() {
$(this).next(':hidden').prop('checked', true);
return false;
});
Instead of using check of hidden I would suggest you to set the value of hidden field.
$(this).next(':hidden').val("true");
you can try this
JS CODE
$('[id^=answerid_]').on('change', function() {
$(this).siblings('[id^=degres_]').prop('checked', true);
alert($(this).siblings('[id^=degres_]').prop('checked'));
return false;
});
DEMO
You can't check a hidden-type input. it is expecting a value, so the value could be 1 if previous is cecked or 0 if not checked.
after use the folowing code
$('[id^=answerid_]').on('change', function() { $(this).siblings('[id^=degres_]').prop('checked', true); //alert($(this).siblings('[id^=degres_]').prop('checked')); return false; });
and changing hidden input to another radio because it now work and by adding
style="margin-left: -16px; position: absolute;"
for every answer input to be above degrees radio it work successfully.
but in the last question it's not work or check degree input :(