I'm trying to hide two fields on my form depending on the selection of the use on the radio field. This is the field HTML:
function show1() {
document.getElementByClass('extra').style.display = 'none';
}
function show2() {
document.getElementByClass('extra').style.display = 'block';
}
<div class="form-radio">
<div class="radio">
<label>
<input type="radio" name="radio" onclick="show1();" /><i class="helper"></i>
I can come
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="radio" onclick="show2();" /><i class="helper"></i>
I cant come
</label>
</div>
</div>
<div class="form-group extra">
<input type="text" required="required" />
<label class="control-label" for="input">Dietary Requirements</label>
<i class="bar"></i>
</div>
<div class="form-group extra">
<input type="text" required="required" />
<label class="control-label" for="input">What song would you like played?</label>
<i class="bar"></i>
</div>
It should work by hiding the dietary requirements and what song fields when the user selects "I can't come" on the radio field. I get the following result:
Uncaught ReferenceError: show2 is not defined
at HTMLInputElement.onclick ((index):627)
Your code fails for two reasons:
There is no method of document called getElementByClass. The correct method to use is getElementsByClassName.
The methodgetElementsByClassName returns an HTMLCollection and not a single element, so setting style.display for the HTMLCollection won't have the desired effect, because you are not setting it for each individual element of it, but rather for the HTMLCollection object itself.
The correct code is:
function show() {
/* Cache the collection. */
var extra = document.getElementsByClassName('extra');
/* Iterate over every element in the collection. */
[].forEach.call(extra, function (element) {
element.style.display = 'block';
});
}
function hide() {
/* Cache the collection. */
var extra = document.getElementsByClassName('extra');
/* Iterate over every element in the collection. */
[].forEach.call(extra, function (element) {
element.style.display = 'none';
});
}
Snippet:
/* ----- JavaScript ----- */
function show() {
/* Cache the collection. */
var extra = document.getElementsByClassName('extra');
/* Iterate over every element in the collection. */
[].forEach.call(extra, function(element) {
element.style.display = 'block';
});
}
function hide() {
/* Cache the collection. */
var extra = document.getElementsByClassName('extra');
/* Iterate over every element in the collection. */
[].forEach.call(extra, function(element) {
element.style.display = 'none';
});
}
<!----- HTML ----->
<div class="form-radio">
<div class="radio">
<label>
<input type="radio" name="radio" onclick="show();" checked/>
<i class="helper"></i>
I can come
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="radio" onclick="hide();"/>
<i class="helper"></i>
I cant come
</label>
</div>
</div>
<div class="form-group extra">
<input type="text" required="required" />
<label class="control-label" for="input">Dietary Requirements</label>
<i class="bar"></i>
</div>
<div class="form-group extra">
<input type="text" required="required" />
<label class="control-label" for="input">What song would you like played?</label>
<i class="bar"></i>
</div>
you can use jQuery instead of javascript.
jQuery(document).ready(function($){
$('input:radio[name="radio"]').change(function(){
if($(this).val() == 'hide'){
$('.extra').hide();
}
else {
$('.extra').show();
}
});
});
<div class="form-radio">
<div class="radio">
<label>
<input type="radio" name="radio" value="show" /><i class="helper"></i>
I can come
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="radio" value="hide" /><i class="helper"></i>
I cant come
</label>
</div>
</div>
<div class="form-group extra">
<input type="text" required="required" />
<label class="control-label" for="input">Dietary Requirements</label>
<i class="bar"></i>
</div>
<div class="form-group extra">
<input type="text" required="required" />
<label class="control-label" for="input">What song would you like played?</label>
<i class="bar"></i>
</div>
Related
I have HTML that looks like this:
<div class="form-group">
<div class="input-group">
<label for="daterange-vacancy" class="input-group-addon">Van</label>
<input type="text" id="daterange-vacancy" class="form-control" name="daterange-vacancy" placeholder="dd/mm/yyyy" data-class="daterangepicker" required="required" />
<label for="daterange-vacancy" class="input-group-addon">
<span class="fa fa-calendar"></span>
</label>
</div>
</div>
<div class="form-group">
<input class="custom-radio" type="radio" id="temp" name="time" value="1" checked="checked" required/><label for="temp" class="bold-sm">Bepaalde dag(en)</label><br/>
<input class="custom-radio" type="radio" id="project" name="time" value="2" required/><label for="project" class="bold-sm">Bepaalde periode</label><br/>
<input class="custom-radio" type="radio" id="struct" name="time" value="3" required/><label for="struct" class="bold-sm">Terugkerend</label>
</div>
<div class="form-group">
<div class="input-checkbox text-left">
<input class="form-checkbox" type="checkbox" id="other" name="other" />
<label for="other">Af te spreken</label>
</div>
</div>
This creates a calendar, 3 radio buttons and a checkbox.
The calendar and 3 radio buttons should be looked at as one, they have to be filled in together or the validation should not let it pass to the next step.
The only exception is when the checkbox is checked. This will disable the calendar and the radiobuttons (and remove the validation on them). Upon unchecking the checkbox again, I want the calendar and the radiobuttons to be required again.
My javascript looks like this:
var other = document.getElementById('other');
if (other) {
other.onchange = function () {
document.getElementById('daterange-vacancy').value = "";
document.getElementById('daterange-vacancy').disabled = this.checked;
$('input[name=other]').change(function(){
if($(this).is(':checked')) {
$('input[name=time]').attr('checked',false);
}
});
}
}
The problem is that the radiobuttons do not uncheck when checking the checkbox. And it does not remove the validation on it.
Here might be a start. And for your own sanity, comment the heck out of your code. It'll help with debugging.
// Create my references
var other = document.getElementById('other');
var vanEl = document.getElementById("daterange-vacancy");
var timeBtnEls = document.getElementsByName("time");
// This will handle the checkbox
if (other) {
other.addEventListener("click", handleOtherClick)
}
// and this will handle all the radio buttons
for (var i = 0; i<timeBtnEls.length; i++) {
timeBtnEls[i].addEventListener("click", handleTimeClick);
}
function handleOtherClick(evt){
// if the box is checked, set the text el to
// disabled.
vanEl.disabled = other.checked;
// set the check status of all radio els to
// the OPPOSITE of the checkbox. End result?
// either NO buttons selected (if the check box
// is selected), or the LAST radio selected (if
// the checkbox is de-selected).
for (var i = 0; i<timeBtnEls.length; i++){
timeBtnEls[i].checked = !other.checked;
}
}
function handleTimeClick(evt){
// The following line will set the checked
// to the OPPOSITE of the currently-clicked
// radio button. I could have simply set it to
// false, but this also works.
other.checked = !evt.target.checked;
// and we re-enabled the text box.
vanEl.disabled = false;
}
<div class="form-group">
<div class="input-group">
<label for="daterange-vacancy" class="input-group-addon">Van</label>
<input type="text" id="daterange-vacancy" class="form-control" name="daterange-vacancy" placeholder="dd/mm/yyyy" data-class="daterangepicker" required="required" />
<label for="daterange-vacancy" class="input-group-addon">
<span class="fa fa-calendar"></span>
</label>
</div>
</div>
<div class="form-group">
<input class="custom-radio" type="radio" id="temp" name="time" value="1" checked="checked" required/>
<label for="temp" class="bold-sm">Bepaalde dag(en)</label>
<br/>
<input class="custom-radio" type="radio" id="project" name="time" value="2" required/>
<label for="project" class="bold-sm">Bepaalde periode</label>
<br/>
<input class="custom-radio" type="radio" id="struct" name="time" value="3" required/>
<label for="struct" class="bold-sm">Terugkerend</label>
</div>
<div class="form-group">
<div class="input-checkbox text-left">
<input class="form-checkbox" type="checkbox" id="other" name="other" />
<label for="other">Af te spreken</label>
</div>
</div>
Its a simple form that looks like below:
<form class="form register-form" data-parsley-validate data-parsley-excluded="input[type=button],input[type=submit], input[type=reset]" method="POST">
<div class="notification hide"></div>
<div class="row first-rg">
<div class="col-sm-6">
<input type="text" class="tfield-2" name="contact_fname" id="contact_fname" placeholder="First Name*" required data-parsley-trigger="focusout">
<div style="display:none;"><input type="text" class="tfield-2" name="contact_projectname" id="contact_projectname" value="Royal Pearls"></div>
</div>
<div class="col-sm-6">
<input type="text" class="tfield-2" name="contact_lname" id="contact_lname" placeholder="Last Name*" required data-parsley-trigger="focusout">
</div>
</div>
<div class="row second-rg">
<div class="col-sm-6">
<input type="text" id="contact_phone" placeholder="Phone No. *" name="contact_phone" maxlength="50" required="" class="international-number-input international-phone-number-input intl-phone-number-input" aria-required="true" autocomplete="off" data-parsley-intl-tel-no data-parsley-trigger="focusout" required>
</div>
<div class="col-sm-6">
<input type="email" class="tfield-2" name="contact_email" id="contact_email" placeholder="Email*" data-parsley-type="email" data-parsley-trigger="focusout" data-parsley-error-message="Enter Valid Email" required>
</div>
</div>
<p class="form-tag">Are you searching for a</p>
<div class="checkbox regiterpage">
<label class="background-co">
<input
type="checkbox"
value="1"
name="bedroom[]"
required
type="checkbox"
data-parsley-mincheck="1"
data-parsley-error-message="Check atleast 1"
>
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span> 1 Bedroom </label>
<label class="background-co" >
<input type="checkbox" value="2" name="bedroom[]">
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span> 2 Bedrooms </label>
<label class="background-co">
<input type="checkbox" value="3" name="bedroom[]">
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span> 3 Bedrooms </label>
<label class="background-co">
<input type="checkbox" value="4" name="bedroom[]">
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span> 4 Bedrooms </label>
</div>
<div class="radioin">
<p class="form-tag">Are you searching for a property as an</p>
<label class="radio-inline background-co">
<input type="radio"
name="propertytype"
required
data-parsley-mincheck="1"
data-parsley-error-message="Check atleast 1"
>
<span class="rlabl">End-user / Owner-occupier</span> </label>
<label class="radio-inline background-co">
<input type="radio" name="optradio">
<span class="rlabl">Investor</span> </label>
</div>
<!-- HIDDEN INPUTS FOR google captcha -->
<input type="hidden" value="No Bots" id="google-captcha" required>
<input type="hidden" id="google-captcha-check" data-parsley-equalto="#google-captcha" data-parsley-error-message="Fill the captcha!" required>
<!-- HIDDEN INPUTS FOR google captcha -->
<div class="captch">
<div class="g-recaptcha" data-sitekey="6LdksigUAAAAAKw5idd69Xa3ysK_RZJ3xAleTbVj" data-callback="google_captcha_callback" data-expired-callback="google_captcha_callback"></div>
</div>
<button type="submit" class="btn-default">Submit</button>
</form>
Now i have validated the form using parsely.js , the validation works just fine , but there is a problem with my submit handler, i have the following submit handler in my form:
$('.register-form').submit(function() {
$.ajax({
type: 'POST',
url: 'mail/reg_send.php',
data : $('.register-form').serialize(),
success : (data , status) => {
(data === 'success') ? $('.notification').text('Thank you for contacting us.').removeClass('hide') : $('.notification').text('There was a problem submitting your form').removeClass('hide');
$('.register-form')[0].reset();
}
});
return false;
});
But even though i have a submit handler and a return false in the submit handler, the page still refreshes and even the i add a breakpoint to my submit handler in my dev tools , the breakpoint is never reached. Why ? what am i doing wrong here ?
I have tried changing the submit handler to something more generic such as:
$('form').submit((){
// code here
})
But my page will still refreah. Why ?
Include the event in the handler with function(e) and prevent default on it.
$('.register-form').submit(function(e) {
e.preventDefault();
// the rest of your code
});
Your other problem might be that your event handler is not being attached to the element because it is not available when the JavaScript is executed. You can test this easily by using the following instead:
$(document).on("submit", ".register-form", function(e) {
e.preventDefault();
// the rest of your code
});
I have a script that checks if form inputs are valid or not. Then it adds a class called 'has-error' to a .form-group class if there is an error.
I don't fully understand how it picks the correct .form-group but i suspect "closest" means it goes back until it finds the first one then applies it:
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url'],input[type='radio'],Select"),
isValid = true;
$(".form-group").removeClass("has-error");
for(var i=0; i<curInputs.length; i++){
if (!curInputs[i].validity.valid){
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
???$(curInputs[i]).closest(".form-group").addClass("has-error");???
}
}
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
So this works for example:
<div class="form-group col-md-6">
<label class="control-label">Surname</label>*
<input id="Surname" name="Surname" maxlength="100" required="required" class="form-control" placeholder="" type="text">
</div>
Now I have a radio button and I am trying to work out either A) how to change my HTML code to match the same structure as the text box input above or B) what to add to the script between ???.....??? to add the class 'has-error' to the label on line 2 below. It adds it to the two labels below the input which is good (as I guess these are the 'closest') but not the first one :
<div class="col-md-12">
<label class="control-label">Gender</label>*
<div class="form-group funkyradio">
<div class="form-group funkyradio-primary col-md-6">
<input type="radio" name="GenderRadio" id="radio1" required="required" />
<label class="control-label" for="radio1">Male</label>
</div>
<div class="form-group funkyradio-primary col-md-6">
<input type="radio" name="GenderRadio" id="radio2" required="required"/>
<label class="control-label" for="radio2">Female</label>
</div>
</div>
</div>
Thank you!
EDIT:
So this modification works:
<div class="form-group col-md-12">
<label class="control-label">Gender</label>*
<div class="funkyradio">
<div class="funkyradio-primary col-md-6">
<input type="radio" name="Gender" value="M" id="radio1" required="required" />
<label class="control-label" for="radio1">Male</label>
</div>
<div class="funkyradio-primary col-md-6">
<input type="radio" name="Gender" value="F" id="radio2" required="required"/>
<label class="control-label" for="radio2">Female</label>
</div>
</div>
</div>
Though I'd still be interested to know what to put between ???...??? if i wanted to target another element on the page somewhere, perhaps this?:
(curInputs[i]).find?("#div-with-unique-ID").addClass("has-error");
I have a .less file with a form-validate class in it. When the input type is set to url, and an invalid url is entered, the border turns red.
Normally it works, but when I add the element dynamically, it does not.
The .less file is from a template and I don't know much about it.
I'm adding the input element dynamically on a button click.
I've added the form-validate to the form which is parent.
$("#panelHolder").html('<input type="url" name="hostUrl" id="hostUrl" ng-model="hostUrl" placeholder="http://" class="form-control "/>');
If the same code is added directly in the panelHolder, it works.
<form name="myForm" class="form-validate " data-ng-submit="create(myForm.$valid)"
novalidate>
<script>
function showPanel1()
{
$("#servicePanelHolder").html('<div id="panel1" class="controls"><div class="form-group"><label class="control-label">Host</label><input type="url" form="syncForm" name="hostUrl" id="hostUrl" ng-model="hostUrl" placeholder="http://"class="form-control "/><span ng-show="form.validateInput(\'url\', \'url\')"></span></div></div>');
}
function showPanel2()
{
$("#servicePanelHolder").html('<div id="panel2" class="controls"><div class="form-group"><label class="control-label">Access Key</label><input type="text" name="accessKey" id="accessKey" ng-model="accessKey" class="form-control "/></div><div class="form-group"><label class="control-label">Secret Access Key</label><input type="text" name="secretKey" id="secretKey" ng-model="secretKey"class="form-control "></div></div>');
}
</script>
<div class="panel-body">
<div class="form-group">
<label class="control-label">Name</label>
<input type="text" name="name" id="name" ng-model="name" class="form-control "/>
</div>
<legend>Service</legend>
<div class="row form-group">
<label class="radio-inline c-radio ">
<input type="radio" name="type" value="Panel1"
checked="" ng-model="type"
onchange="showPanel1()"/>
<span class="fa fa-circle"></span>Panel 1</label>
<label class="radio-inline c-radio">
<input type="radio" name="type" value="Panel2"
ng-model="type"
onchange="showPanel2()"/>
<span class="fa fa-circle"></span>Panel 2</label>
</div>
</div>
<div class="panel-body" id="servicePanelHolder">
</div>
<div class=" mt">
<input type="submit" class="mb-sm btn btn-primary">
</div>
</form>
UPDATE: I'm also unable to read values of these elements in my controller when the form is submitted.
I'm trying to use javascript to show/hide a div's content depending on which radio button is selected. I have an onchange function that I use to change the the div content from one div to another, but it doesn't work. If you can do this in jquery instead thats ok but im not that familiar with jquery so if you could update my jsfiddle with it I would be appreciativw :) Here is the JSFiddle: https://jsfiddle.net/markusbond/au77Ladg/
Any help is appreciated :)
JAVASCRIPT:
function changeSelection() {
if (document.getElementById("selectionTables").checked) {
document.getElementById("populateCheckBoxes").show;
document.getElementById("unpopulateCheckBoxes").hidden;
} else {
document.getElementById("unpopulateCheckBoxes").show;
document.getElementById("populateCheckBoxes").hidden;
}
}
HTML:
<form role="form">
<div class="row">
<!--this is the onchange call-->
<div class="radio col-xs-2" id="populateSelection" onchange="changeSelection()">
<!--this is the first radio button-->
<label>
<input type="radio" name="optradio" id="selectionTables" />Use Tables
</label>
<!--this is the second radio button-->
<label>
<input type="radio" name="optradio" id="selectionViews" />Use Views
</label>
</div>
<!--this is the first changed div-->
</div>
<div class="row" id="populateCheckBoxes">
<div class="checkbox">
<label>
<input type="checkbox" id="selectionCondition" />Condition
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="selectionDistribution" />Distribution
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="selectionProgram" />Program
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="selectionTreatment" />Treatment
</label>
</div>
</div>
<!--this is the second changed div-->
<div class="row" id="unpopulateCheckBoxes"></div>
</form>
Example using JQuery FIDDLE
JavaScript
$('input:radio[name=optradio]').change(
function(){
if (this.value == 'selectionTables') {
$("#unpopulateCheckBoxes" ).hide();
$("#populateCheckBoxes").show();
}
else {
$("#unpopulateCheckBoxes" ).show();
$("#populateCheckBoxes").hide();
}
}
);
Give your first radio button a value value="selectionTables"
<!--this is the first radio button-->
<label>
<input type="radio" name="optradio" id="selectionTables" value="selectionTables" />Use Tables
</label>
I hope I understood you correctly.
This is the correct way
<script>
function changeSelection() {
if (document.getElementById("selectionTables").checked) {
document.getElementById("populateCheckBoxes").style.visibility = "hidden";
document.getElementById("unpopulateCheckBoxes").style.visibility = "visible";
} else {
document.getElementById("unpopulateCheckBoxes").style.visibility ="hidden";
document.getElementById("populateCheckBoxes").style.visibility = "visible";
}
}
</script>
You are using
document.getElementById("unpopulateCheckBoxes").hidden;
but you should
document.getElementById("populateCheckBoxes").style.visibility = "hidden";
Hope this helps
or via jquery, thats what i would prefer:
function changeSelection() {
if ($("#selectionTables").attr("checked") {
$("#populateCheckBoxes").show();
$("#unpopulateCheckBoxes").hide();
} else {
$("#unpopulateCheckBoxes").show();
$("#populateCheckBoxes").hide();
}
}
document.getElementById('myElementID').style.display = 'none'; // Will hide an element
document.getElementById('myElementID').style.display = 'block'; // Will show an element
It is worth noting that you will not always want your element to be display:block;. There are many display options and you probably want to toggle back and forth based on how your element was originally shown.
Problem is html does not supports show/hide attribute. Try using style attribute with display property. Also use checked attribute to make default radio selection.
<input type="radio" name="optradio" id="selectionTables" checked='' />
function changeSelection() {
var pop = "none",
upop = "block";
if (document.getElementById("selectionTables").checked) {
pop = "block";
upop = "none";
}
document.getElementById("unpopulateCheckBoxes").style.display = upop;
document.getElementById("populateCheckBoxes").style.display = pop;
}
<form role="form">
<div class="row">
<!--this is the onchange call-->
<div class="radio col-xs-2" id="populateSelection" onchange="changeSelection()">
<!--this is the first radio button-->
<label>
<input type="radio" name="optradio" id="selectionTables" checked='' />Use Tables
</label>
<!--this is the second radio button-->
<label>
<input type="radio" name="optradio" id="selectionViews" />Use Views
</label>
</div>
<!--this is the first changed div-->
</div>
<div class="row" id="populateCheckBoxes">
<div class="checkbox">
<label>
<input type="checkbox" id="selectionCondition" />Condition
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="selectionDistribution" />Distribution
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="selectionProgram" />Program
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="selectionTreatment" />Treatment
</label>
</div>
</div>
<!--this is the second changed div-->
<div class="row" id="unpopulateCheckBoxes"></div>
</form>