How to disable/enable form elements using a checkbox with Javascript? - javascript

I'm at a loss - after wracking my brain for hours on this one, it's time to throw the question up here.
I'm trying to have a checkbox execute some javascript code that, when checked, enables some form elements, and when unchecked, disables those elements again.
Here's the javascript that I have:
function houseclean()
{
if (document.orderform.cleaning.checked == true)
{
document.orderform.rooms.disabled = false;
document.orderform.datetime.disabled = false;
document.orderform.howoften.disabled = false;
}
else
{
document.orderform.rooms.disabled = true;
document.orderform.datetime.disabled = true;
document.orderform.howoften.disabled = true;
}
}
And here is my HTML code:
<form id="orderform" style="margin-left: 6cm">
<input type="checkbox" name="cleaning" value="yes" onclick="houseclean()"/> Home cleaning <br />
Service: <select name="rooms" id="rooms" disabled >
<option value="1bedroom">One Bedroom Apt</option>
<option value="2bedroom">Two Bedroom Apt</option>
<option value="3bedroom">Three Bedroom Townhome or SF Home</option>
<option value="4bedroom">Four Bedroom Home</option>
<option value="5bedroom">Five Bedroom Home</option>
<option value="6bedroom">Six Bedroom Home</option>
</select> <br />
Date / Time: <input type="text" name="datetime" disabled /><br />
How often would you like a cleaning?: <select name="howoften" disabled>
<option value="once">One Time Only</option>
<option value="2bedroom">Every Week</option>
<option value="3bedroom">Every Other Week</option>
<option value="4bedroom">Once a Month</option>
</select> <br />
</form>

This code will do the trick. You should be explicit about your element IDs and use getElementById whenever possible.
The HTML:
<form id="orderform" style="margin-left: 6cm;">
<input type="checkbox" id="cleaning" name="cleaning" value="yes" onclick="javascript:houseclean();"/> Home cleaning <br />
Service: <select name="rooms" id="rooms" disabled >
<option value="1bedroom">One Bedroom Apt</option>
<option value="2bedroom">Two Bedroom Apt</option>
<option value="3bedroom">Three Bedroom Townhome or SF Home</option>
<option value="4bedroom">Four Bedroom Home</option>
<option value="5bedroom">Five Bedroom Home</option>
<option value="6bedroom">Six Bedroom Home</option>
</select> <br />
Date / Time: <input type="text" id="datetime" name="datetime" disabled /><br />
How often would you like a cleaning?: <select id="howoften" name="howoften" disabled>
<option value="once">One Time Only</option>
<option value="2bedroom">Every Week</option>
<option value="3bedroom">Every Other Week</option>
<option value="4bedroom">Once a Month</option>
</select> <br />
</form>​
And the javascript:
function houseclean()
{
if (document.getElementById('cleaning').checked == true)
{
document.getElementById('rooms').removeAttribute('disabled');
document.getElementById('datetime').removeAttribute('disabled');
document.getElementById('howoften').removeAttribute('disabled');
}
else
{
document.getElementById('rooms').setAttribute('disabled','disabled');
document.getElementById('datetime').setAttribute('disabled','disabled');
document.getElementById('howoften').setAttribute('disabled','disabled');
}
}
JSFiddle example: http://jsfiddle.net/HQQ4n/10/

I got your code to work. I added the id attribute to the form elements and used document.getElementById to be on the safe side.
JFiddle example: http://jsfiddle.net/vxRjw/1/

Not super robust, but a dynamic jquery solution...
$("#mycheckbox").click(function() {
enableFormElements("#myform", $(this).attr('checked'));
});
function enableFormElements(form, enable) {
var fields = ["checkbox","textarea","select"];
var selector = form+" input";
$.each(fields, function(i,e) { selector += ","+form+" "+e; });
$(selector).each(function(idx) {
if (enable) {
$(this).removeAttr("disabled");
$(this).removeAttr("readonly");
} else {
$(this).attr("disabled","disabled");
$(this).attr("readonly","readonly");
}
if ($(this).is("select") || $(this).is("textarea")) {
var id = $(this).attr("id");
var txt_equiv = id+"_text";
var val = $(this).find("option[value='"+$(this).val()+"']").text();
// dynamically add the span to this element...so you can switch back and forth...
if ($(this).parent().find("span").length == 0) {
$(this).parent().append("<span class='record_display_text' id='"+txt_equiv+"'>"+val+"</span>");
}
}
if ($("#"+txt_equiv).length != 0) {
if (enable) {
$("#"+id).show();
$("#"+txt_equiv).hide();
} else {
$("#"+txt_equiv).show();
$("#"+id).hide();
}
}
});
}
The function basically looks for all input, selects, textareas found inside the element provided and disables or enables each one. If using JQuery 1.9, you may want to change those to prop settings, but I've found that not all browsers are consistently working with that yet. (bleh). In the cases of textareas or selects, it actually creates a related span with an id that matches the input except with "_text" after it. If you have other IDs on your page that might conflict, you might want to edit that...but putting that in place allows the code later to hide/show either the text or the actual select/textarea depending on whether you want everything enabled or disabled. Again, not tested in all circumstances, but feel free to copy and edit for your purposes...
Oh, and make sure that all selects or textareas are an only child to their parent...wrap in a span if you have to because it dynamically adds the related span within the same parent...so if the select or textarea isn't wrapped in a parent (like a span, a div, or a td or something), then it might throw the generated text span somewhere random. :P
And then you can add some CSS to make form elements look more like your normal page or standard span elements...
input[readonly],
select[readonly],
textarea[readonly] {
cursor: default;
}
input[disabled] {
background-color:#F0F0F0;
border:none;
-moz-box-shadow: none;
-webkit-box-shadow:none;
box-shadow:none;
padding: 0;
}
You will probably want to change the background-color to match your page color...and the "cursor:default" one is if bootstrap twitter is adding the annoying "restricted" cursor or whatever it is over disabled elements...but anyways, this is a solution I came up with this evening and it's working for me. :)

Related

How do you pass a value to a hidden form field when a certain option is selected?

I am new to javascript and cannot find an easy-to-understand answer.
I would like a certain value to get passed to a hidden field when a user selects a certain option from the select dropdown.
I know that there are if/else statements but I'm not sure if that would be used in this situation.
For example: I have a select dropdown of a list of states.
<select name="HomeState" required>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
As you can see, any option other than California will be rated at a value of 1.
I would like it to where if the user selects the option of California, then the value of $300 will get passed to a hidden form field.
<input name="AmountNeeded" type="hidden" value="300" />
If they select anything other than California, the hidden field would get passed $100
<input name="AmountNeeded" type="hidden" value="100" />
How would I implement this logic? Would it be using if/else statement? I am new and don't exactly know how to set that up.
To keep this simple you could assign ids to the <select> and hidden <input> and listen to the change event via onchange() on the <select> with a function call.
And based on the selected item, change the value of hidden input.
NOTE: To test the snippet out I have removed the type="hidden". Do place it back.
function homeSelected(){
const home = document.getElementById("homeSelector").value;
if(home == 5){
document.getElementById("amountNeeded").value = 300;
}else{
document.getElementById("amountNeeded").value = 100;
}
}
<select id="homeSelector" name="HomeState" onchange="homeSelected()" required>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
<input id="amountNeeded" name="AmountNeeded" value="100" />
You can do this as follows:
<select name="HomeState" required onChange=myFunction(this)>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
Javascript code is:
<script>
function myFunction(x) {
val = x.options[x.selectedIndex].text;
if(val == 'California')
document.getElementsByName("AmountNeeded")[0].value = 300
else
document.getElementsByName("AmountNeeded")[0].value = 100
}
</script>
If else statement is good for you if you are sure that All other states have value 1 except California. If all states may have different values like some states may have 1 or some may have 2 or some may have 3, then there may be other alternatives to solve this like you can pass give one more attribute data-src-amount to options and give amount to data-src-amount. You can create options like <option value="1" data-src-amount="100">Alabama</option> and in script, you can fetch data-src-amount on select change event instead of if-else statement.

Multiple options from one drop down giving alternate results - Javascript/html

I'm looking to have separate sections of my form become visible dependant on the selection from a drop down menu.
Currently i'm having two issues, its only hiding the first area i want hidden and also i'm struggling with the syntax to get the multiple options working using if statements.
Am i looking at this the right way or is there an easier way of doing this.
In the code below i've only got 2 if statements as i've been struggling to get that correct so haven't done it for all 8 options i need to.
function showfield(name){
if (name=='Supplier meetings') {
document.getElementById('div1').style.display="block";
} else {
document.getElementById('div1').style.display="none";
if (name=='Product meetings') {
document.getElementById('div2').style.display="block";
} else {
document.getElementById('div2').style.display="none";
}
}
}
function hidefield() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
document.getElementById('div3').style.display='none';
document.getElementById('div4').style.display='none';
document.getElementById('div5').style.display='none';
document.getElementById('div6').style.display='none';
document.getElementById('div7').style.display='none';
document.getElementById('div8').style.display='none';
}
in my html i have:
<body onload="hidefield()">
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1">Worked hours</option>
<option value="2">Overtime</option>
<option value="3">Sickness</option>
<option value="4">Unpaid leave</option>
<option value="5">Compassionate leave</option>
<option value="6">Holiday inc bank holidays</option>
<option value="7">Team meetings</option>
<option value="8">One to ones</option>
<option value="9">One to one prep</option>
<option value="10">Huddles</option>
<option value="Supplier meetings">Supplier meetings</option>
<option value="Product meetings">Product meetings</option>
<option value="Training/coaching">Training/coaching</option>
<option value="Handling other peoples cases">Handling other peoples cases</option>
<option value="15">Project work</option>
<option value="16">Surgery time for GK</option>
<option value="17">Letter checks and feedback</option>
<option value="18">MI/Reporting/RCA</option>
</select>
Then divs that contain the parts i need displayed off each option.
Hope that makes sense.
Thanks
Instead of writing condition for each option value, you can use the value directly in selecting the div that is to be shown:
function showfield(name){
hidefield();
document.getElementById( 'div-' + name).style.display="block";
}
For this to work, your id's should match up with corresponding option values.
e.g. <option value="1">1</option>
corresponding div:
<div id="div-1"></div>
You can add a data-div attribute to every option which will be ID of respective div which will be shown and other divs will be hidden.
You need a class on every div so they can be hidden using that class name except the div which will be shown based on selection.
HTML
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1" data-div="one">Worked hours</option>
<option value="2" data-div="two">Overtime</option>
</select>
<div id="one">First Div</div>
<div id="two">Second Div</div>
Javascript
function showfield(val)
{
var divID = $("select[name=acti]").find("option[value='" + val + "']").attr("data-div");
$(".divClass").hide();//You can also use hidefield() here to hide other divs.
$("#" + divID).show();
}

jQuery checkbox auto disable and re-enable

I have my HTML code and my JavaScript code like this (I'm using jQuery)
HTML :
<input type="checkbox" name="type" value="program" id="box-1" /> Desktop Programming
<select name="lang-1" id="select-1" disabled>
<option value="c">C/C++</option>
<option value="vb">VB</option>
<option value="cs">C#</option>
</select><br /><br />
<input type="checkbox" name="type" value="web" id="box-2" /> Web Development
<select name="lang-2" id="select-2" disabled>
<option value="asp">ASP</option>
<option value="php">PHP</option>
<option value="ror">Ruby on Rails</option>
</select><br /><br />
JavaScript (jQuery) :
$(document).ready(function(){
var x;
$("#box-" + x).click(function(){
var $this = $(this);
if ($this.is(":checked")) {
$("#select-" + x).prop('disabled', false);
} else {
$("#select-" + x).prop('disabled', true);
}
});
});
And I want when I checked the programming checkbox, the programming select option (beside the checkbox) is enable. As well as when I checked the web dev checkbox, the web dev select option is enable. But my code doesn't work. Can anybody help me?
You're better off using classes in stead of ID's with a random number.
I would give all my checkboxes the class "box" and the id 1, 2, 3 and so on.
Also, I think $this doesn't work. It has to be $(this).
Then your code would look like (working example):
$(document).ready(function(){
$('.box').click(function(){
var x= $(this).attr("id");
if ($(this).is(":checked")) {
$("#select-" + x).prop('disabled', false);
} else {
$("#select-" + x).prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="type" value="program" class="box" id="1" /> Desktop Programming
<select name="lang-1" id="select-1" disabled>
<option value="c">C/C++</option>
<option value="vb">VB</option>
<option value="cs">C#</option>
</select><br /><br />
<input type="checkbox" name="type" value="web" class="box" id="2" /> Web Development
<select name="lang-2" id="select-2" disabled>
<option value="asp">ASP</option>
<option value="php">PHP</option>
<option value="ror">Ruby on Rails</option>
</select><br /><br />
For things like this use classes , no need for ID.
Right now your variable x is undefined and without a loop to parse the ID's it won't work
<input type="checkbox" class="box" /> Desktop Programming
<select name="lang-1" class="select" disabled>
JS
$('input:checkbox.box').change(function(){
$(this).next('.select').prop('disabled', !this.checked);
});
If the layout is such that the select is not right after the input we can modify traverse a bit
Hi you can do something like this working demo
Please have one same class to all of your checkbox here i taken as checkbox then your HTML will look like this
<input type="checkbox" name="type" value="program" class="checkbox" id="box-1" /> Desktop Programming
<select name="lang-1" id="select-1" disabled>
<option value="c">C/C++</option>
<option value="vb">VB</option>
<option value="cs">C#</option>
</select><br /><br />
<input type="checkbox" name="type" value="web" class="checkbox" id="box-2" /> Web Development
<select name="lang-2" id="select-2" disabled>
<option value="asp">ASP</option>
<option value="php">PHP</option>
<option value="ror">Ruby on Rails</option>
</select><br /><br />
add write this jquery
$(document).ready(function(){
$('.checkbox').on('change',function(){
var checked_id = $(this).prop('id');
var a = checked_id.slice(4);
$("#select-"+a).prop('disabled',!this.checked);
});
});
So there are lots of answers here, much of which are better ways to do what you are trying with smaller cleaner code. But for the sake of it I am adding this answer to show you what was wrong with code you wrote and a working example.
So you declared variable x but never assigned it a value. It seems like you wanted to loop over the checkboxes and use the index x to assign the event. Since you started using IDs with 1 we need to compensate in the code for it. Then since x has no scope to our event directly we need to find the value of x since when the event runs it will only have the last value of x.
All HTML I left the same and only altered the javascript. As I said there are much better ways to do this and there are many answers here that show it but this is to show you what you were doing wrong.
Fiddle: https://jsfiddle.net/quyn4y23/
$(document).ready(function() {
// Find all checkboxes and get the length of all found
var x, inputs = $('input[type="checkbox"]'), length = inputs.length;
// For each checkbox assign event
for (x = 1; x <= length; x++) {
$("#box-" + x).click(function() {
var $this = $(this);
// Find the number in the checkbox id
var x = $this.attr('id').replace("box-", "");
// Use number to find correct select
if ($this.is(":checked")) {
$("#select-" + x).prop('disabled', false);
} else {
$("#select-" + x).prop('disabled', true);
}
});
}
});

Set class from <select> if selected option contains ID='answer' in HTML/JavaScript (JQuery)

I am completely new to HTML and JQuery, and I can't figure out how I can set a class for my select element if the currently selected option has an ID="answer". I want to do this to check if the multiple choice question is correct.
If this is impossible to do this in JQuery, JavaScript would also be fine. I just want to prevent making a DataBase query and thought that JQuery would be the best route to take.
This is the current html section that I have:
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question </label>
<select class="form-control select-class">
<option value="1" class="ans-class" id="answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question </label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class" id="answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary"
onclick="checkAnswers()">Check</button>
</form>
When I click the button it runs a Javascript function called: "checkAnswers()".
This function should check if the option that is selected in the dropdown box, has an id="answer". In this case, that would be if option one is selected. And if that option is selected, I want the background color of the select element to change.
How would I go about checking the currently selected dropdown options' ID? And how do I do this for more than 1 question at a time?
And how would I add a class programaticly in JavaScript to that select element so it can change BG color?
This is what I tried in JavaScript:
var s = document.getElementsByClassName("select-class");
var idSelectedOption = s[s.selectedIndex].id;
alert(idSelectedOption);
But that returns an error: "Uncaught TypeError: Cannot read property 'id' of undefined"
I think that is because it returns an array from all classes. How would I go about checking every single one of them? And changing the background colors of the ones that have the correct option selected?
Thanks in advance,
Mats.
Use data-* attributes instead of id as you should not have multiple elements having same id value in a document.
getElementsByClassName will return nodelist hence you need to iterate through elements and then apply conditions accordingly. Array.prototype.forEach.call is used in example below to iterate through elements.
Try this:
function checkAnswers() {
var s = document.getElementsByClassName("select-class");
Array.prototype.forEach.call(s, function(elem) {
var idSelectedOption = elem[elem.selectedIndex].getAttribute('data-id');
if (idSelectedOption == 'answer') {
var selectedAnswer = elem[elem.selectedIndex].getAttribute('value');
alert(selectedAnswer);
}
});
}
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question</label>
<select class="form-control select-class">
<option value="1" class="ans-class" data-id="answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question</label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class" data-id="answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary" onclick="checkAnswers()">Check</button>
</form>
Fiddle here
You can't have two elements with the same id. Use a custom data attribute or a class instead
After fixing that, this code should to the trick. I tried to use vanilla JavaScript since you didn't indicate using jQuery.
// Lazy: Bind the event to the form.
document.getElementById('ansForm').addEventListener('change', function(event) {
var selectElement = event.target;
// Only respond if the clicked element is one of the selects.
if (selectElement.classList.contains('select-class')) {
// Get the option that is currently selected.
var selectedOption = selectElement[selectElement.selectedIndex];
// Check if this option contains the class 'answer'.
var isAnswerSelected = selectedOption.classList.contains('answer');
console.log(isAnswerSelected);
// Remove the indicators. You could easily use classList.toggle, but the second
// argument is not supported in IE.
// selectElement.classList.toggle('right', isAnswerSelected);
// selectElement.classList.toggle('wrong', !isAnswerSelected);
// So, second best. Just remove both and re-add the class we want.
selectElement.classList.remove('right');
selectElement.classList.remove('wrong');
selectElement.classList.add(isAnswerSelected?'right':'wrong');
} else {
// Ignore clicks on any other element.
}
});
.right {
color: green;
}
.wrong {
color: red;
}
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question </label>
<select class="form-control select-class">
<option value="1" class="ans-class answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question </label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary"
onclick="checkAnswers()">Check</button>
</form>
Try this for jQuery approach,
$(function(){
// This will bind 'click' event handler to element with id 'checkBtn'
$('#checkBtn').on('click', function(){
// This gets all selects element which has class containing 'select-class'.
var $selects = $('select.select-class');
// Iterate all the selects element.
$selects.each(function(k, v){
// Get the option for this current select element which has an id of 'answer'.
var $selectAnswerOpt = $(this).children('option#answer');
// Get the value attribute of the option element.
var answer = $selectAnswerOpt.attr('value');
// Get the selected value for the select element.
var selectedValue = $(this).val();
// Checking if the selected value for the select element is the option that has an id of 'answer'
if (selectedValue == answer)
{
// If the selected value has the id of 'answer'
$(this).css('background-color', 'green');
}
else
{
// Else
$(this).css('background-color', 'yellow');
}
});
});
});
And the FIDDLE

jQuery: Show/Hide Elements based on Selected Option from Dropdown

UPDATE: The original question asked was answered. However, the code revealed for all. So, I've modified my question below:
So I have the following dynamically generated html via php
<div class="image-link link-posttypes mainSelector1">
<select id="wp_accordion_images[20110630022615][post_type]" name="wp_accordion_images[20110630022615][post_type]">
<option value="">default</option>
<option value="post" class="post-type">Post</option><option value="page" class="post-type">Page</option><option value="dp_menu_items" class="post-type">Menu Items</option>
<option value="wps_employees" class="post-type">Employees</option><option value="custom-link">Custom Link</option>
</select>
</div>
<div class="image-link link-pages1">
<select id="wp_accordion_images[20110630022615][page_id]" name="wp_accordion_images[20110630022615][page_id]">
<option value="50" class="level-0">About</option>
<option value="65" class="level-0">Contact</option>
<option value="2" class="level-0">Sample Page</option>
<option value="60" class="level-0">Staff</option>
</select>
</div>
<div class="image-link link-posts1">
<select onchange="javascript:dropdown_post_js(this)" id="wp_accordion_images[20110630022615][post_id]" name="wp_accordion_images[20110630022615][post_id]">
<option value="http://localhost/tomatopie/?p=1" class="level-0">Hello world!</option>
</select>
</div>
<div class="image-link link-custom1">
<input type="text" size="25" value="" name="wp_accordion_images[20110630022615][image_links_to]">
</div>
***THEN IT REPEATS four times: where the #1 goes to 2..3...4 (max to 4 at this time).
I have the ability to label div .classes, select #ids, and option classes. However, what I want to be able to do is based on the option selected from div .link-posttypes, I want to reveal .link-pages (if page is selected) or .link-posts (if post is selected) and .link-custom for all others (except the default).
So as written on the screen there should only be the initial div, and once the user selects an item, the appropriate div appears.
I have never developed anything in jQuery or javascript. This is my maiden voyage. Any help will be greatly appreciated!
***Also, this will be loaded via an external js file.
Here is the final answer that worked:
jQuery(document).ready(function($) {
$(".link-posttypes select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="post"){
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").slideDown('slow');
$(this).parent().nextAll(".link-custom").hide();
}else if(selectedVal=="page"){
$(this).parent().nextAll(".link-pages").slideDown('slow');
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().nextAll(".link-custom").hide();
}else if(selectedVal!=""){
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().next().nextAll(".link-custom").slideDown('slow');
}else{
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().nextAll(".link-custom").hide();
}
});
});
jQuery(document).ready(function($) {
$(".image-content select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="content-limit"){
$(this).parent().next().nextAll(".content-limit-chars").slideDown('slow');
$(this).parent().nextAll(".content-custom").hide();
}else if(selectedVal=="custom-content"){
$(this).parent().nextAll(".content-limit-chars").hide();
$(this).parent().next().nextAll(".content-custom").slideDown('slow');
}
});
});
Thanks for your help!
Assuming that you're outputting proper IDs, you can do something like this (note I replaced the id):
$(window).load(function(){
// hide all the divs except the posttypes
$('.image-link').not('.link-posttypes').hide();
$('#wp_accordion_images_20110630022615_post_type').change(function() {
var divSelector = '.link-' + $(this).val();
$('.image-link').not('.link-posttypes').hide();
$(divSelector).show();
});
});
Also, consider changing your options like this:
<option value="posts" class="post-type">Post</option>
<option value="pages" class="post-type">Page</option>
<option value="menu_items" class="post-type">Menu Items</option>
<option value="wps_employees" class="post-type">Employees</option>
<option value="custom">Custom Link</option>
Here's a jsfiddle for this: http://jsfiddle.net/JrPeR/
There's my understandable jquery script
jQuery(document).ready(function($) {
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").hide();
$(".link-posttypes select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="post"){
$(".link-pages").hide();
$(".link-posts").show();
$(".link-custom").hide();
}else if(selectedVal=="page"){
$(".link-pages").show();
$(".link-posts").hide();
$(".link-custom").hide();
}else if(selectedVal!=""){
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").show();
}else{
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").hide();
}
});
});
Demo here. Take me couple minute to make you easy to understand. Have fun.
http://jsfiddle.net/JrPeR/3/
added a conditional so if its not the two variables it defaults to the custom.

Categories