show hide data on load and check/uncheck of radio buttons - javascript

Running a script where I need to check if the value of checkbox is checked or not, and then run the jQuery code for hide and doing a show based upon specific checked value. I am not able to fix it.
Trying with this code
$(".choosezoho").click(function() {
var checkValue = $("input[type='radio']").is(':checked');
alert(checkValue);
});
This gives me true on which checkbox I check
This is my html
<div class="selectbox_radio">
<blockquote>
<div title="128167215">Training</div>
<input type="hidden" name="customer_name" id="customer_name" value="12817215~Training">
</blockquote>
<input type="radio" class="choosezoho" name="usethisexisting" checked value="12817215">Use Existing
<input type="radio" class="choosezoho" name="usethisexisting" value="12817215">Create New
<br/>
<small>If You Check "Choose New" Please Choose a New Contact from below List</small>
<br/>
</div>
<div class="selectbox" style="display:none;">
<select name="customer_name" id="customer_name_select" class="selectItemsLists">
<option></option>
</select>
</div>
and what I am trying is: if the checkbox is choose new, it should load the select box and hide the above and vice versa in other case.
Also it should check what is the initial selection and based upon that trigger in the jQuery code.

Try to use $(".choosezoho").change() instead of click and than use $(this) to see if it is checked.

Please check below snippet.
To achieve this I have changed the values of radio buttons to identify and show/hide accordingly.
And the existing and new customer HTML is wrapped with ids so we can make show/hide accordingly.
$(".choosezoho").on('change',function() {
var checkValue = $('input[name=usethisexisting]:checked').val()
if(checkValue=="new"){
$("#existingCustomer").hide();
$("#newCustomer").show();
}else{
$("#existingCustomer").show();
$("#newCustomer").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selectbox_radio">
<blockquote id="existingCustomer">
<div title="128167215">Training</div>
<input type="hidden" name="customer_name" id="customer_name" value="12817215~Training">
</blockquote>
<input type="radio" class="choosezoho" name="usethisexisting" checked value="existing">Use Existing
<input type="radio" class="choosezoho" name="usethisexisting" value="new">Create New
<br/>
<div id="newCustomer" style='display:none;'>
<small>If You Check "Choose New" Please Choose a New Contact from below List</small>
<br/>
</div>
<div class="selectbox" style="display:none;">
<select name="customer_name" id="customer_name_select" class="selectItemsLists">
<option></option>
</select>
</div>
</div>

$(".choosezoho").on('change',function() {
var checkValue = $('input[name=usethisexisting]:checked').val()
if(checkValue=="new"){
$("#existingCustomer").hide();
$("#newCustomer").show();
$('.selectbox').show();
}else{
$("#existingCustomer").show();
$("#newCustomer").hide();
$('.selectbox').hide();
}
});
<div class="selectbox_radio">
<blockquote id="existingCustomer">
<div title="128167215">Training</div>
<input type="hidden" name="customer_name" id="customer_name" value="12817215~Training">
</blockquote>
<input type="radio" class="choosezoho" name="usethisexisting" checked value="existing">Use Existing
<input type="radio" class="choosezoho" name="usethisexisting" value="new">Create New
<br/>
<div id="newCustomer" style='display:none;'>
<small>If You Check "Choose New" Please Choose a New Contact from below List</small>
<br/>
</div>
<div class="selectbox" style="display:none;">
<select name="customer_name" id="customer_name_select" class="selectItemsLists">
<option></option>
</select>
</div>
</div>

You should give each of your radio inputs a unique id, and then put them in a div. That way you can show / hide the entire div.
Then you can bind a change event to the Create New radio input and see if it is checked, if so you can show the select box and hide the radio fields.
$("#createNewID").bind("change",function() {
if($(this).is(':checked')){
$('.selectbox').show();
$('#radioInput').hide();
}
See JFiddle: https://jsfiddle.net/1h2xaL5x/

$(".choosezoho").on('change',function() {
var checkValue = $('input[name=usethisexisting]:checked').val()
if(checkValue=="new"){
$("#existingCustomer").hide();
$("#newCustomer").show();
$('.selectbox').show();
}else{
$("#existingCustomer").show();
$("#newCustomer").hide();
$('.selectbox').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="selectbox_radio">
<blockquote id="existingCustomer">
<div title="128167215">Training</div>
<input type="hidden" name="customer_name" id="customer_name" value="12817215~Training">
</blockquote>
<input type="radio" class="choosezoho" name="usethisexisting" checked value="existing">Use Existing
<input type="radio" class="choosezoho" name="usethisexisting" value="new">Create New
<br/>
<div id="newCustomer" style='display:none;'>
<small>If You Check "Choose New" Please Choose a New Contact from below List</small>
<br/>
</div>
<div class="selectbox" style="display:none;">
<select name="customer_name" id="customer_name_select" class="selectItemsLists">
<option></option>
</select>
</div>
</div>
Now it is updated

This solution is not very different from previous ones, however, it shows some small details that seem useful to me. The switch allows widespread use for more cases and makes things clearer.
I understand that the "input type text" must also be shown in the "Select New" option, the list appears in the other case. Right?
There are also minor changes in html.
$(".choosezoho").bind("change",function() {
if($(this).is(':checked')){
switch( $(this).attr('id') ) {
case "createNew":
$('#nameSelect1').hide();
$('#newCustomerDiv').show();
break;
case "useExisting":
$('#nameSelect1').show();
$('#newCustomerDiv').hide();
break;
}
}
});
//setDefault
$('#useExisting').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selectbox_radio" >
<blockquote>
<div title="128167215"
id="trainingID">
Training
</div>
<div id="newCustomerDiv">
<label for="customerName">New customer name:</label>
<input type="input"
id="customerName"
name="customer_name"
id="customer_name"
value="12817215~Training">
</div>
</blockquote>
<input type="radio"
id = "useExisting"
class="choosezoho"
name="usethisexisting"
checked value="12817215">
Use Existing
<input type="radio"
id="createNew"
class="choosezoho"
name="usethisexisting"
value="12817215">
Create New
<br/>
<small>If You Check "Choose New" Please Choose a New
Contact from below List</small>
<br/>
</div>
<div id="nameSelect1" class="selectbox" style="display:none;">
<select name="customer_name" id="customer_name_select"
class="selectItemsLists">
<option value="John Doe">John Doe</option>
<option value="Jane Doe">Jane Doe</option>
</select>
</div>

Related

How to prevent form submission until form is filled using JavaScript?

It should not be possible to submit the form if the user does not enter a value into the text entry fields, e.g. for surname or company, and at least one event has not been selected
(remember that users don’t always fill out forms in top to bottom order). Here is the sample code from php file which I can't edit. Only java script must be used.
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Thomas Bewick and His Apprentices</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="1" data-price="0.00"></span>
</div>
<div class="item">
<span class="eventTitle">Winter Festival # Discovery Museum</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00"></span>
</div>
</section>
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked=""> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
<section id="makeBooking">
<h2>Make booking</h2>
Your details
Customer Type: <select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename">
Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName">
</div>
<p style="color: red; font-weight: bold;" id="termsText">I have read and agree to the terms and conditions
<input type="checkbox" name="termsChkbx"></p>
<p><input type="submit" name="submit" value="Book now!" disabled=""></p>
</section>
</form>
Using HTMLFormElement.elements to dynamically set required attribute:
Just use the HTMLFormElement.elements property to get all the form controls (input, select, etc) inside your form and then use the Array.from() method to get a shallow-copied array of the HTMLFormControlsCollection which you can now loop over and use the setAttribute() method to dynamically set a required attribute to all the form controls.
Check and run the following Code Snippet or open this JSFiddle link for a practical example of the above approach:
// get the form
const form = document.getElementById("bookingForm");
// get the form controls
let x = form.elements;
// Convert the list of form controls to an array and set the required attribute to each control
Array.from(x).forEach(e => {
e.setAttribute("required", "");
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Thomas Bewick and His Apprentices</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="1" data-price="0.00"></span>
</div>
<div class="item">
<span class="eventTitle">Winter Festival # Discovery Museum</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00"></span>
</div>
</section>
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked=""> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
<section id="makeBooking">
<h2>Make booking</h2>
Your details
Customer Type: <select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename">
Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName">
</div>
<p style="color: red; font-weight: bold;" id="termsText">I have read and agree to the terms and conditions
<input type="checkbox" name="termsChkbx"></p>
<p><input type="submit" name="submit" value="Book now!"></p>
</section>
</form>
Using required:
Just add a required attribute to each input element like this:
<input type="text" name="forename" required>
<input type="text" name="forename" required>
<select name="customerType" required>
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
1_you can add required attribute to inputs by JS. :)
2_I'm not a pro and the only way I can think of , is using AJAX and JQuery .like this:
<script>
function echo() {
var name = $("#id");
if (name.val() === "") {
alert(name.attr('placeholder') + " is empty");
return;
}
$.ajax({
url: "your destination",
data: {
name: name.val(),
},
dataType: "json",
type: "POST",
success: function (data) {
if (data['error'] === false) {
alert(data['msg']);
} else {
alert(data['msg']);
}
}
});
}
</script
you need JQ just for the AJAX part of course, but the rest of the function can get done
just by JS.
I would suggest that you try and get access to your html and change it's structure e.g. the "Select Events" section could use a <select> dropdown instead of the current two checkboxes so you can make use of the cleaner and more concise required attribute approach shown in the other answer that I posted.
However, if you HAVE to use only JavaScript to validate the form, then you can just retrieve the form elements, validate each element and submit the form if they all pass.
To do that, you can just replace the current <input type="submit"> element with a <button> instead and then add a click listener to that button which in turn will run a function that will prevent the form from submitting using preventDefault() method, check and validate each form element and submit the form if all the elements pass the validation.
Check and run the following Code Snippet or open this JSFiddle for a practical example of the above approach:
const form = document.getElementById("bookingForm");
const events = document.querySelectorAll('input[name="event[]"]');
const terms = document.querySelector('input[name="termsChkbx"]');
const selectBox = document.querySelector('select[name="customerType"]');
const fName = document.querySelector('input[name="forename"]');
const sName = document.querySelector('input[name="surname"]');
const btn = document.getElementById("submitBtn");
function verifyEvents(e){
e.preventDefault();
if(selectBox.value != "" && terms.checked && fName.value != "" && sName != "" && (events[0].checked || events[1].checked)){
console.log(selectBox.value);
form.submit();
} else {
alert("Please fill the form.");
}
}
btn.addEventListener("click", verifyEvents);
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Thomas Bewick and His Apprentices</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="1" data-price="0.00"></span>
</div>
<div class="item">
<span class="eventTitle">Winter Festival # Discovery Museum</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00"></span>
</div>
</section>
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked=""> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
<section id="makeBooking">
<h2>Make booking</h2>
Your details
Customer Type: <select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename">
Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName">
</div>
<p style="color: red; font-weight: bold;" id="termsText">I have read and agree to the terms and conditions
<input type="checkbox" name="termsChkbx"></p>
<p><button id="submitBtn" name="submitBtn" value="Book now!">Book now!</button></p>
</section>
</form>

jQuery: Toggle field attribute: un-checked Checkbox means disabled

I would like to be able to edit a multi-select field when ("Update Data?") Checkbox is checked, and disabled the field again, when checkbox is un-checked.
Important is that checked status always leads to being able to edit, meanwhile un-checked means field is disabled, regardless if I load the form with a checked box or as un-checked as the initial state (I can save either or)
I find several useful answers but struggling with syntax to combine those into my solution.
Below can toggle once, then it gets stuck:
$(function() {
$("#checkbox1").change(function() {
if ($("#field2").attr('disabled', !this.checked)) {
$("#field2").removeAttr("disabled");
} else {
$("#field2").attr("disabled", "disabled");
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<div id="div_id_product" class="form-group row"> <label for="field2" class="col-form-label col-sm-4">
Multiselect
</label>
<div class="col-sm-7">
<select name="multiselect" class="select2-show-search selectmultiple form-control" id="field2" disabled="disabled" multiple style="width: 100%;">
<option value="1" selected>Product 1 </option>
<option value="3" selected>Product 3</option>
<option value="2">Product 2</option>
</select>
</div>
</div>
<div class="form-group row" id="checkbox1"> <label for="id_to_update" class="col-form-label col-sm-4">
Update Data?
</label>
<div class="col-sm-7">
<div class="input-group"> <input type="checkbox" name="to_update" class="checkboxinput" id="id_to_update"> <span class="input-group-append"></span> </div>
</div>
</div>
</form>
Just change your JS to this. You have the change listener on the wrong id.
The listener should be on #id_to_update (input) instead of #checkbox1 which is the div.
$(function() {
$("#id_to_update").change(function() {
$("#field2").prop('disabled', !this.checked);
});
})
Here is the solution you are looking for
$(function() {
$('#field-editable').change(function() {
$('#firstname').prop('disabled', !this.checked);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<label for="field-editable">
<input type="checkbox" id="field-editable">
do you want to edit
</label>
<input type="text" name="firstname" id="firstname" disabled="disabled">
</form>

forcing checkbox selected

I'm trying to find see if we can make a checkbox selected if we chose an option from the dropdown menu. Here's a mock-up code of what I'm trying to modify.
$('.stackoverflow').on('change', function() {
$(this).parent().next().find('input:checkbox').attr("checked", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkboxes">
<div class="checkbox_wrapper">
<input type="checkbox" id="How" /> How</div>
<div class="checkbox_wrapper">
<input type="checkbox" id="Do" /> do</div>
<div class="checkbox_wrapper">
<input type="checkbox" id="I" /> I </div>
<div class="checkbox_wrapper">
<input type="checkbox" id="Force" /> force </div>
<div class="checkbox_wrapper">
<input type="checkbox" id="The" /> the</div>
<div class="checkbox_wrapper">
<input type="checkbox" id="checkbox" /> checkbox
<select class="stackoverflow">
<option value="to">to</option>
<option value="be">be</option>
<option value="selected">selected</option>
<option value="when">when</option>
<option value="we">we</option>
<option value="select">select</option>
<option value="an">an</option>
<option value="option">option</option>
</select>
</div>
<div class="checkbox_wrapper">
<input type="checkbox" id="not this one" /> not this checkbox but the previous one</div>
I'm trying to have the checkbox "checkbox" be selected if I do select an option from the dropdown menu. Is there an easy way to do this? When searching stackoverflow, the closest thing that I found was to have the next one be selected and not the current one. Thank you very much for any help at all.
Just reference the correct checkbox correctly?
In your case, you have this:
$(this).parent().next().find('input:checkbox').attr("checked", true);
this refers to the select
parent refers to <div class="checkbox_wrapper">
next would then refer to <div class="checkbox_wrapper">
and finally find('input:checkbox') would find: <input
type="checkbox" id="not this one" />
Since the checkbox you want is a child of the same parent element that the select is in, the next() method call is what's causing the problem.
So, you could write:
$(this).parent().find('input:checkbox').attr("checked", true);
But, there are many ways to access an element. If it has an id, that is the simplest and most efficient way. So you are better off writing:
$('#checkbox').prop("checked", true);
Also, use .prop instead of .attr as .attr fails when you manually uncheck the checkbox and then select an item from the drop down.
$('.stackoverflow').on('change', function() {
$('#checkbox').prop("checked", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkboxes">
<div class="checkbox_wrapper">
<input type="checkbox" id="How" /> How</div>
<div class="checkbox_wrapper">
<input type="checkbox" id="Do" /> do</div>
<div class="checkbox_wrapper">
<input type="checkbox" id="I" /> I </div>
<div class="checkbox_wrapper">
<input type="checkbox" id="Force" /> force </div>
<div class="checkbox_wrapper">
<input type="checkbox" id="The" /> the</div>
<div class="checkbox_wrapper">
<input type="checkbox" id="checkbox" /> checkbox
<select class="stackoverflow">
<option value="to">to</option>
<option value="be">be</option>
<option value="selected">selected</option>
<option value="when">when</option>
<option value="we">we</option>
<option value="select">select</option>
<option value="an">an</option>
<option value="option">option</option>
</select>
</div>
<div class="checkbox_wrapper">
<input type="checkbox" id="not this one" /> not this checkbox but the previous one</div>
You have a couple of options to check the checkbox:
$(document).ready(function() {
$(".stackoverflow").on("change", function() {
//$("#checkbox").prop("checked", true);
$(this).prev("input[type='checkbox']").prop("checked", true);
})
})
Here is a fiddle of it working based on your example: https://jsfiddle.net/gz6mab4k/
Hurray, you are using the relative position of your dom elements to locate each other. I assume that's because you're going to get rid of all the IDs and add this structure many times to your page. So you have a small error in the javascript handler, as mentioned in a comment you break stuff by having .next(), which will force the handler to look for a checkbox in the div coming after the select's parent which is the one that contains checkbox id='not this one'. So you want:
$('.stackoverflow').on('change', function() {
$(this) // the select
.parent() // its parent DIV
.find('input:checkbox') // the only checkbox in the parent div
.attr("checked", true);
});

How to get html element id using jquery

I am need to get the id before and after html element of dropdown list on change. Please see blow source code.
When Fund name selected I need to get the previous selected checkbox id or name ( Cash / Epf ) & after selected checkbox id or name ( No.of Units Reedem / Amount Reedem / All units).
Thanks in advance.
$(document).ready(function () {
$('.units').change(function () {
alert($(this).attr('id'));
alert($(this).before().parent().parent().html());
});
});
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<div class="setup-content" id="form-3">
<div id="repurchase">
<div class="lblHead">REPURCHASE REQUEST</div>
<div class="form-group">
1.<input type="checkbox" name="Fm3CheckBoxList1[]" id="fm3chk11" value="CashPlan" class="singlecheckbox plan" /><label for="fm3chk11">Cash Plan</label>
<input type="checkbox" name="Fm3CheckBoxList1[]" id="fm3chk12" value="EPFPlan" class="singlecheckbox plan" /><label for="fm3chk12">EPF Plan</label>
</div>
<div class="form-group">
<div class="col-lg-6">
<label>Fund Name</label>
<select id="fundId" class="form-control drplst units" AppendDataBoundItems="true">
<option Value=""></option>
<option Value="123">123</option>
<option Value="369">369</option>
</select>
</div>
<div class="col-lg-6">
<div class="clearfix"></div>
<input type="checkbox" name="Fm3CheckBoxList2[]" id="fm3chk21" value="No_OfUnitToRedeem" class="singlecheckbox" /><label for="fm3chk21">No. of Unit to Redeem</label>
<input type="checkbox" name="Fm3CheckBoxList2[]" id="fm3chk22" value="Amount_ToRedeem" class="singlecheckbox" /><label for="fm3chk22">Amount to Redeem</label>
<input type="checkbox" name="Fm3CheckBoxList2[]" id="fm3chk23" value="All_Units" class="singlecheckbox" /><label for="fm3chk23">All Units</label>
<asp:TextBox ID="Fm3TextBox2" runat="server" class="form-control" placeholder="AMOUNT"></asp:TextBox>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
Try this :
$(document).ready(function () {
$('.units').change(function () {
alert($(this).closest('.form-group').prev().find('.singlecheckbox:checked').attr('id'));
alert($(this).parent().next().find('.singlecheckbox:checked').attr('id'));
});
});
This is working for single checked box, if more than one checkbox was chekced, you need to iterate that and doing something with that.
Assuming your plans are mutually exclusive, you would want radio buttons to represent them, unless that F3m... indicates some JS framework that would turn appropriately decorated checkboxes into mutually exclusive selections. Maybe you don't want them to be mutually exclusive. If that's the case I'll update my answer. Either way, you can use another attribute on the group of checkboxes to aggregate them all, such as name. See my changes to the code snippet (below) for using name to find the selected plan. You could assign all checkboxes in a particular group a name, class, or modify their IDs to include some base to use in a selector. You could put them inside a container element (div) for easier reference, and then bind your inputs' events...
var lastPlanSelection = "none";
$('input[name=targetSet]').on('click', function() { lastPlanSelection = $(this).val(); });
Modifying your snippet to find the selected radio button...same principle could be applied to checkboxes using class attribute.
$(document).ready(function () {
$('.units').change(function () {
var selectedPlan = $('input[name=plan]:checked');
alert("Selected Plan: " +
(selectedPlan.length === 1 ? selectedPlan.val() : "none"));
});
});
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<div class="setup-content" id="form-3">
<div id="repurchase">
<div class="lblHead">REPURCHASE REQUEST</div>
<div class="form-group">
1.<input type="radio" id="cashPlan" name="plan" value="Cash"><label for="cashPlan">Cash Plan</label><br/>
<input type="radio" id="epfPlan" name="plan" value="EPFPlan"><label for="epfPlan">EPF Plan</label>
</div>
<div class="form-group">
<div class="col-lg-6">
<label>Fund Name</label>
<select id="fundId" class="form-control drplst units" AppendDataBoundItems="true">
<option Value=""></option>
<option Value="123">123</option>
<option Value="369">369</option>
</select>
</div>
<div class="col-lg-6">
<div class="clearfix"></div>
<input type="checkbox" name="Fm3CheckBoxList2[]" id="fm3chk21" value="No_OfUnitToRedeem" class="singlecheckbox" /><label for="fm3chk21">No. of Unit to Redeem</label>
<input type="checkbox" name="Fm3CheckBoxList2[]" id="fm3chk22" value="Amount_ToRedeem" class="singlecheckbox" /><label for="fm3chk22">Amount to Redeem</label>
<input type="checkbox" name="Fm3CheckBoxList2[]" id="fm3chk23" value="All_Units" class="singlecheckbox" /><label for="fm3chk23">All Units</label>
<asp:TextBox ID="Fm3TextBox2" runat="server" class="form-control" placeholder="AMOUNT"></asp:TextBox>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>

Javascript hide/show questions depending on user input values

I am trying to hide and/or show form elements when a user selects certain values.
For example, if the user selects "yes" to the consent question, I need it to show a few questions, However, if they change their response to the consent question, I need it to hide those questions.
Here is what I have come up with so far...
$(document).ready(function () {
var input = document.getElementById('consent');
var consent_responses = [{ "0": hideConsent },{ "1": showConsent }];
input.addEventListner('click', function () {
var consent_response;
if (consent_responses[this.value]) {
content_response = consent_responses[this.Function()]
}
else {
content_response = consent_responses[this.Function]
}
});
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
function hideConsent(){
$("#date").hide(),
$("#referrer").hide(),
$("#f_name").hide(),
$("#phone_num").hide(),
$("#leave_msg").hide(),
$("#email").hide(),
}; });
Fiddle here: http://jsfiddle.net/7jX47/1/
You could do it like this: JSFiddle
Basically I only fixed a few typos (did you actually try your code before you posted here?) and added event listeners to the radio buttons with
document.getElementById(...).addEventListener(...)
I also gave your radio buttons unique IDs.
This can be simplified:
var input = document.getElementById('consent');
// Let's use the value as key, and the functions as values
var consent_responses = {
"0" : hideConsent,
"1" : showConsent
};
input.addEventListener("click", function () {
// Get the appropriate function given the value, and invoke it
consent_responses[this.value]();
});
function hideConsent() {
// ...
}
function showConsent() {
// ...
}
It's better to envelop your questions (that needs to be hidden) by a div with a class ".hidden" or style "display: none;". And simplify your code by simply asking that div to show() or hide() when needed.
Like so:
<form id="screening">
<div class="col-md-12 col-sm-12 col-xs-12 nopad" id="create">
<div class="form-group text-center">
<b>Do you agree to answer the screening questions?</b><br />
<div class="radio" id="consent">
<label>
<input type="radio" name="consent" id="consent" value="1">
Yes, I consent
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="consent" id="consent" value="0">
No, I do not consent
</label>
</div>
</div>
<!-- simplify by using this -->
<div id="questions" style="display: none;">
<div class="form-group" id="date">
<label for="date">What is today's date?</label>
<input type="date" class="form-control" id="date" name="date" />
</div>
<div class="form-group" id="referrer">
<label for="referrer">How did you hear about us/our studies?</label>
<select class="form-control" name="referrer" id="referrer">
<option></option>
<option value="1">Flyers</option>
<option value="2">Print Media</option>
<option value="3">A friend</option>
<option value="4">Online (e.g., Craigslist)</option>
<option value="5">Other</option>
</select>
</div>
<div class="form-group" id="other_explain">
<label for="other_explain">Please specify other source.</label>
<textarea class="form-control" rows="3" id="other_explain" name="other_explain"></textarea>
</div>
<div class="form-group" id="f_name">
<label for="f_name">What is your first name?</label>
<input type="text" class="form-control" id="f_name" name="f_name" />
</div>
<div class="form-group" id="phone_num">
<label for="phone_num">What is a phone number at which you can be contacted? </label>
<input type="tel" class="form-control" id="phone_num" name="phone_num" />
</div>
<div class="form-group" id="leave_msg">
<label for="leave_msg">If we call and you are not available, may we leave a message?</label><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="1">
Yes
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="0">
No
</label>
</div>
</div>
<div class="form-group" id="email">
<label for="email">What is an e-mail at which you can be contacted?</label>
<input type="email" class="form-control" id="email" name="email" />
</div>
</div>
</div>
</form>
and in your javascript instead of using this:
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
you use:
function showConsent(){
$("#questions").show(),
};

Categories

Resources