Show / Hide Form Elements based on Select - javascript

I'm trying to Show / Hide two elements based on a selection - a label and an input using Javascript getElementsByName. It works with getElementByID if I change things around on the label and input but for some reason Name isn't working. Here is the code:
<script language="JavaScript" type="text/javascript">
<!--
function Toggle(obj){
var val=obj.value;
if (!obj.m){ obj.m=''; }
if (!obj.m.match(val)){ obj.m+=','+val+','; }
var hide=obj.m.split(',');
for (var zxc0=0;zxc0<hide.length;zxc0++){
if (document.getElementsByName(hide[zxc0])){
document.getElementsByName(hide[zxc0]).style.display='none';
}
}
var show=val.split(',');
for (var zxc1=0;zxc1<show.length;zxc1++){
if (document.getElementsByName(show[zxc1])){
document.getElementsByName(show[zxc1]).style.display='';
}
}
}
//-->
</script>
and here are for form elements:
<div id="styled-select">
<select name="how" onchange="Toggle(this);" class="dropdown">
<option value="Internet Search">Internet Search</option>
<option value="Facebook" >Facebook</option>
<option value="Twitter" >Twitter</option>
<option value="LinkedIN" >LinkedIN</option>
<option value="Referral">Referral</option>
<option value="Other">Other</option>
</select>
</div>
<label name="Referral" style="display:none;">Referred By:</label>
<input name="Referral" style="display:none;" value="" class="hidden-txt">
When the user selects "Referal" it should display the Label and Input named "Referral". I had this working if I used getElementByID, gave the option two values separated by comma and used seperate IDs for the label and input.
Thank you for your help.

var elems = document.getElementsByName(hide[zxc0]);
if(elems) {
for(var i = 0;i < elems.length;i++) {
elems[i].style.display='none';
//Do whatever else you need to do with the element.
}
}
As mentioned by Kevin Boucher, getElementsByName returns an array. Assuming that you want to apply the display=none style to all elements with that name, the code above will achieve that. Also for performance's sake, the above code only calls document.getElementsByName() once as opposed to the 3+ times above which I'm sure will be beneficial.
It might be worth investigating JQuery for its ease of selecting elements.

Related

How to get an html select-element with a querySelector in javascript

I have a div with the classname "data" which contains 3 different elements: inpyt, select and textarea.
I would like to put the elements in an array with a querySelectorAll and loop over them to set the value back to empty. The input en textarea elements work fine but I can't "catch" the select element.
In the querySelectorAll I first use the classname and then the tagnames.
What do I need to change to make it work properly?
<div class="data">
<input></input>
<select>
<option value="" required></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<textarea></textarea>
</div>
<div>
<button onclick="resetValues()"<Click</button>
</div>
function resetValues() {
var arr = document.querySelectorAll(".data>input,textarea,select");
for (var i = 0; i < arr.length; i++) {arr[i].value = "";}
}
I tried to rewrite the querySelectorAll but it didn't work
document.querySelectorAll(".data>input,textarea,option[selected]");
document.querySelectorAll(".data>input,textarea,option[select]");
document.querySelectorAll(".data>input,textarea,select option");
document.querySelectorAll(".data>input,textarea,select>option");
document.querySelectorAll(".data>input,textarea,option");
One problem is the selector. The , separates distinct selectors. .data>input,textarea,select means
.data>input OR
textarea OR
select
You should be using .data>input,.data>textarea,.data>select.
Or if your are using browsers that support the new :is selector: .data > :is(input,textarea,select)

Is it possible to get a reference of the array of selected values on a Select2?

I have a select2 which is multiple select.
There are two ways to select an option:
Type and choose on the select box,
There is a menu on which you can click and it will add it to the select2 select box.
It's not properly working this time, but I can already select options using the menu.
What I want to know is, is it possible for me to have a reference of the array of selected values?
Because what I am doing right now is,
I have an array called, selectedValuesArray,
where when I select from the menu, it will push the id of the selection to the selectedValuesArray and
$('#selectbox').val(selectedValuesArray).trigger("change");
So can I just have a reference on the array of the selected value itself so I'll just push and splice items there?
EDIT:
Select2.val() is an array.
I want to have a reference to that array like,
var selectionArray = Select2.val();
And I want to manipulate that array dynamically.
// like adding a selection
selectionArray.push("1");
// or removing a selection
selectionArray.splice(indexOf("1"), 1);
Is it possible?
If I've understood your question properly, you're after something like this:
$("#e1").select2();
$("#checkbox").click(function () {
if ($("#checkbox").is(':checked')) {
$("#e1 > option").prop("selected", "selected");
$("#e1").trigger("change");
} else {
$("#e1 > option").removeAttr("selected");
$("#e1").trigger("change");
}
});
$("#button").click(function() {
console.log($("#e1").val());
});
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css">
<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<input type="checkbox" id="checkbox" />Select All
<input type="button" id="button" value="Check Selected" />
Original fiddle can be found here.
Alright I have managed to achive what you want. Here is the code;
var selectedArray = $('#selectbox').val();
var selectElem = $('#selectbox').select2();
//delete '42' from array
var index = selectedArray.indexOf('42');
data.splice(index,1);
selectElem.val(selectedArray);
selectElem.trigger('change');
//add '52' to array
selectElem.push('52');
selectElem.val(selectedArray);
selectElem.trigger('change');
Hope this helps :)

javascript enable and disable a combobox

I am a beginner in java-script , what I am doing right here is trying to make my combo-box named "dale" to enable and disable when i select "Reasons Specific Categorized" from my combo-box named "repSelect" but i keep getting an error on my java-script.
function makeEnable(value){
if(value=="rep4"){
var x=document.getElementById("dale")
x.disabled=false
}else{
var x=document.getElementById("dale")
x.disabled=true
}
}
</script>
</script>
<select onChange="makeEnable(value)" name="repSelect">
<option value="rep1">Employee</option>
<option value="rep2">Category Reasons Overall </option>
<option value="rep3">Department Overall </option>
<option value="rep4">Reasons Specific Categorized </option>
</select>
<select name="dale">
<option value="rep1">dale</option>
</select>
<input class="button" type="submit" value="Generar Reporte" >
</form>
My modification But dosent work
function makeEnable(){
var e = document.getElementById("repSelect");
var strUser = e.options[e.selectedIndex].value;
if(strUser=="rep4"){
document.getElementById("dale").disabled=false;
}else{
document.getElementById("dale").disabled=true;
}
}
You are using the .getElementById() method, but your element doesn't have an id defined. Add an id in the html:
<select id="dale" name="dale">
You may also need to modify the call to your function in the first select's onchange handler, to pass this.value instead of just value:
<select onChange="makeEnable(this.value)" name="repSelect">
You can also substantially simplify your function as follows:
function makeEnable(value){
document.getElementById("dale").disabled = value!="rep4";
}
Demo: http://jsfiddle.net/3t16p5p9/
EDIT: I just noticed that you had the jquery tag on your question. To use jQuery, remove the inline onChange= attribute and then add this to your script:
$(document).ready(function() {
$("select[name=repSelect]").change(function() {
$("#dale").prop("disabled", this.value!="rep4");
}).change();
});
This binds a change handler to the first select, and then calls it immediately so that the second one will be appropriately enabled or disabled when the page loads (as requested in a comment).
Demo: http://jsfiddle.net/3t16p5p9/2/
Actually you are using document.getElementById but your combobox doesn't have an Id.
Thats the reason its not working.
Instead of adding onchange in the html, use as below:
<select id='repselect' onchange=makeEnable() name="repSelect">
<option value="rep1">Employee</option>
<option value="rep2">Category Reasons Overall </option>
<option value="rep3">Department Overall </option>
<option value="rep4">Reasons Specific Categorized </option>
</select>
<select id="seldale" name="dale">
<option value="rep1">dale</option>
</select>
<input class="button" type="submit" value="Generar Reporte"/>
$('#repselect').change(function(){
if(this.value=="rep4"){
var x= document.getElementById("seldale")
x.disabled=false
}else{
var x =document.getElementById("seldale")
x.disabled=true
}
});

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.

Set option value with getElementsByName()

Having this fieldset:
<fieldset>
<legend>[*death]</legend>
<select name=death style="width: 120px">
<option value=Dead>[*died]
<option value=NotDead>[*alive]
<option value="" selected>-
</select>
</fieldset>
i want to set the [2].value to "-".
i have tried without any success:
document.getElementsByName('death')[2].checked = 'true';
document.getElementsByName('death')[2].value = '-';
Same kind of code works fine for radio boxes, checked boxes or other inputs in the form. How to do it with the option select (which is not an input)?
Thanks
[EDIT] of course, appropriate fieldset is:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
thanks.
It's a little bit unclear what you're asking. Are you simply asking to make the option at index 2 selected?
document.getElementsByName('death')[0].selectedIndex = 2;
Or, are you asking to change the value of option at index 2?
var d = document.getElementsByName('death')[0];
d.options[2].value = '-';
You need to manipulate the selected property of your select object, try
document.getElementsByName('death')[0].selectedIndex = 1;
In english, this reads "set the selected option to the second option in the first element in the document with name 'death'".
Fixing your HTML might make the results of your javascript more predictable. Close your tags, quote your attribute values, as follows:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
you can do this using jQuery... it's easy...
j("#death").val(2)
document.getElementsByName('death')[2] returns the third element named death - but you only have one element with that name. Instead, you want the first element named death (i.e. the one at index 0), and then you want its third option: document.getElementsByName('death')[0].options[2].value = ...
Here's an alert example of how to access your specific option values with getElementsByName
alert(document.getElementsByName('death')[0].options[0].value); // will return Dead
alert(document.getElementsByName('death')[0].options[1].value); // will return NotDead

Categories