I'm trying to show/hide some radio buttons under a double condition with Chosen. Not sure if it can be done.
I've this first select which populates a second select. The second select are indeed several selects shown and hidden depending on the first select's choice.
The goal is to show/hide some radio buttons depending on the select's choices. So if you have select1=A and select2=a' show a certain radio button.
So far I've manages this succesfully with one single select as a condition (JS):
$(".chosen").chosen();
$("#a").chosen().change(function () {
var value = $(this).val();
if (value=="Opt1") {
$("#b").show();
} else {$("#b").hide();}
}).trigger('change');
This is the function that shows/hides the second select.
As I've tried a lot of stuff and didn't succeed I've come to a desperate solution which is forget about double condition and trigger the radio buttons upon the second select's choice, like this (JS):
$(".chosen").chosen();
$("#c").chosen().change(function () {
var value = $(this).val();
if (value=="Opt1") {
$("#radio").show();
} else {$("#radio").hide();}
}).trigger('change');
However it ruins the whole thing because it shows this "c" select when it should be hidden according to the previous functions. Any idea on how overcome this?
UPDATE
This is the whole code. I removed id's making no sense with the real names:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chosen: A jQuery Plugin by Harvest to Tame Unwieldy Select Boxes</title>
<link rel="stylesheet" href="docsupport/style.css">
<link rel="stylesheet" href="docsupport/prism.css">
<link rel="stylesheet" href="chosen.css">
<style type="text/css" media="all">
/* fix rtl for demo */
.chosen-rtl .chosen-drop { left: -9000px; }
</style>
</head>
<body>
<form>
City
<div id="city">
<select data-placeholder="Select city" id="a" class="chosen-select" style="width:350px;" tabindex="2">
<option value="London">London</option>
<option value="Paris">Paris</option>
</select>
</div>
<br>
Trial
<div id="trial1">
<select data-placeholder="Select court" class="chosen-select" style="width:350px;" tabindex="2">
<option value="Court of District"> Court of District </option>
<option value="Magistrate’s Court"> Magistrate’s Court </option>
</select>
</div>
<div id="trial2">
<select data-placeholder="Select court2" class="chosen-select" style="width:350px;" tabindex="2">
<option value="Cour de cassation"> Cour de cassation </option>
<option value="Cour d’apell"> Cour d’apell </option>
</select>
</div>
<br>
<!--- this is a hidden radio that should show up when city== “Paris” and trial2== “Cour d’apell” --->
<div id=radio1><br>
<input type="radio" name="radiob" value="Apell Criminal"> Apell Criminal <br>
<input type="radio" name="radiob" value="Apell Civil" checked> Apell Civil <br>
</div>
<br>
<input type="button" id="btncalc" value="Go on">
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="chosen.jquery.js" type="text/javascript"></script>
<script src="docsupport/prism.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
<!--- Hides the third select and radio buttons--->
$('#trial2').hide();
$('#radio1').hide();
<!--- Shows/hides second and third select, depending on first select’s choice--->
$(".chosen").chosen();
$("#city").chosen().change(function () {
var value = $(this).val();
if (value=="London") {
$("#trial1").show();
$("#trial2").hide();
} else if (value == "Paris") {
$("#trial1").hide();
$("#trial2").show();
}
}).trigger('change');
<!--- show/hide the radio button--->
$('.chosen').chosen().change(onChange);
var onChange = function () {
var a = $('#city').find('select').val();
var b = $('#trial1').find('select').val();
var c = $('#trial2').find('select').val();
/* do all conditional checks here on values a, b, and c */
/* here is an example check on the values of a and b: */
if (a === 'Paris' && c === ‘Cour d’apell’) {
/* show radios */
$("#radio1").show();
}
}; $('.chosen').chosen().change(onChange);
</script>
</body>
</html>
For consistency's sake, let's wrap each select within a div. We can id the divs 'a', 'b', and 'c', but that is really ugly and I would suggest thinking up something more descriptive.
We can first write a function that we want to run whenever any of our selects has its value changed:
var onChange = function () {
var a = $('#a').find('select').val();
var b = $('#b').find('select').val();
var c = $('#c').find('select').val();
/* do all conditional checks here on values a, b, and c */
/* here is an example check on the values of a and b: */
if (a === 'X' && b === 'ya') {
/* show radios */
}
};
We will then pass our function as the change handler to all .chosen selects (we must be certain that all of the selects that we want to apply 'chosen' to have a class of 'chosen'):
$('.chosen').chosen().change(onChange);
Related
I have a form that contains a number of fields including some selects that are using the Selectize jquery plugin. Part of what the form does involves taking the input from a modal window, which is then added dynamically to the relevant 'selectized' select field.
I am currently doing this as follows:
//Initialise Selectize on the required fields
var $select = $('.selectize').selectize(...do some stuff in here...);
//Fetch the selectize instances
var select0 = $select[0].selectize;
var select1 = $select[1].selectize;
...etc, one for each select...
//This is where I get the text entered in the modal and update
//the relevant select field.
function processText(){
//Get the name of the field we need to update
var thisFormElement = $('#sourceFormElementName').val();
//Get the text to update the above field with
var thisText = $('#inputQuickTextOriginalText').val();
//Figure out which select field to update. Messy.
if(thisFormElement == "select0"){
//'select#' is the reference back to the selectize instances we declared earlier
select0.addOption({value:thisText, text:thisText});
select0.addItem(thisText);
}
else if(thisFormElement == "select1"){
select1.addOption({value:thisText, text:thisText});
select1.addItem(thisText);
}
...more statements...
}
Presumably one way to clean this up would be to reference the selectize instance using the thisFormElement value (or similar). Then there would be no need to the if statement and new fields can be added without altering this part of the code. E.g. something like:
//Assume thisFormElement = select0, for example
var thisFormElement = $('#sourceFormElementName').val();
thisFormElement.addOption({value:thisText, text:thisText});
thisFormElement.addItem(thisText);
I understand that the above won't work, but is there some way to achieve something similar (or a completely different way entirely)?
Below is an approach to enabling users to input an option in one field and add that option to a corresponding selectize field. For those just looking for basic functionality enabling users to add new options to a selectize field, check out the Tagging demo from the selectize documentation.
const params = {
options: [],
placeholder: 'Select...',
valueField: 'value',
labelField: 'text',
searchField: ['text'],
create: false
};
// init selectize inputs and add to 'selects' array
const selects = [];
selects.push($('#select1').selectize(params));
selects.push($('#select2').selectize(params));
$('#add button').click(() => {
$('#add input').each((index, elem) => {
if (elem.value) {
const id = $(elem).data('select-id');
for (const select of selects) {
// find corresponding selectize field and add option
if (id === select[0].id) {
const value = Object.keys(select[0].selectize.options).length + 1;
const text = elem.value;
select[0].selectize.addOption({value: value, text: text});
select[0].selectize.addItem(value);
break;
}
}
elem.value = '';
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Selectize</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.default.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.js"></script>
</head>
<body>
<div id="add">
<div>
<input name="add1" type="text" value="" placeholder="Add option to 1st select..." data-select-id="select1" />
</div>
<div>
<input name="add2" type="text" value="" placeholder="Add option to 2nd select..." data-select-id="select2" />
</div>
<div>
<button>Add</button>
</div>
</div>
<br>
<form id="select" action="" method="POST">
<input class="myselect" id="select1" name="select1" type="text" />
<input class="myselect" id="select2" name="select2" type="text" />
</form>
</body>
</html>
Here is what I want to achieve. I have a requirement in which there is one dropdown for country codes and another input field for mobile number. I want to send country code and mobile input value as combined value so for that I am using a hidden field. When not using a hidden field it is easy to change value of a third tag element but that will not send value when form is submitted. So hidden field has to be used. So I have tried doing this but it is not changing value of hidden field.
<html>
<head>
<script language="javascript">
var dropdown = '';
var mobilenum = '';
function calldropdown()
{
dropdown = document.getElementById("country_code_id").value;
return dropdown;
}
function calltxtfield()
{
mobilenum = document.getElementById("mobileid").value;
return mobilenum;
}
function codemobile()
{
document.getElementById("codemobileid").value = calldropdown() + ' ' + calltxtfield;
alert(document.getElementById("codemobileid").value);
}
</script>
</head>
<body>
<form>
<select name="country_code" id="country_code_id" onchange="calldropdown()">
<option value="">Select</option>
<option value="+975">Bhutan</option>
<option value="+977">Nepal</option>
<option value="+94">Sri Lanka</option>
</select>
<input type="text" name="mobile" id="mobileid" onchange="calltxtfield()" />
<input type="hidden" name="codemobile" id="codemobileid" value="" />
<input type="submit" name="submit" value="Submit" onclick="return codemobile();" />
</form>
</body>
</html>
I can not explain it right now, but name="codemobile" seems to silently shadow function codemobile(). Rename one of the two and it works.
Also note that right now you are concatenating the function body (... + calltxtfield;), it should rather be ... + calltxtfield();
The latest version of materialize has a nice looking multi-select implementation with checkboxes next to the options that are currently selected. But once an item has been selected, I don't seem to be able to un-select it again. The visible check mark goes away, but jquery still thinks it's selected. Here's the short example below (it doesn't look like materialize0.97.2's material_select works at all in jsfiddle, sorry). Once you show one of the two divs, you can't hide it again.
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.2/css/materialize.min.css">
</head>
<body>
<div class="container">
<div class="row">
<form>
<div class="input-field col s3" style="margin-left: 50px">
<select multiple id="column-selector">
<option value="" selected disabled>your choice</option>
<option value="first">first</option>
<option value="second">second</option>
</select>
</div>
</form>
</div>
<div class="row col s1">
<div class="first hide">first</div>
<div class="second hide">second</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.2/js/materialize.min.js"></script>
<script>
$(document).ready(function() {
/* this activates the "which columns to display" selectbox */
$('#column-selector').on('change',function() {
var selectedList = $(this).val();
var currentlySelected = {};
for (i in selectedList){
var colName = selectedList[i];
currentlySelected[colName] = true;
}
var colNames = [ "first", "second" ];
for (var i in colNames){
colname = colNames[i];
if (currentlySelected[colname]){
console.log('showing ' + colname);
$( '.' + colname).removeClass('hide');
}else{
console.log('hiding ' + colname);
$( '.' + colname).addClass('hide');
}
}
});
$('#column-selector').material_select();
});
</script>
</body>
</html>
Is there a better/more correct/working way to get the currently selected values of the material_select selectbox?
I did this, but it's not necessarily the best way.
Updating/Destroying Select
$('select').material_select('destroy');
Reinitialization
$('select').material_select();
Hopefully this helps ;)
I previously asked about showing mulple fields based on a dropdown which used JQuery:
Show multiple fields based on dropdown
However when I have other dropdown fields on my page, this no longer works. I did wonder it it was interfering with other JavaScript / JQuery elements, but removing those didn't correct the issue. I've also tried putting the elements into separate ULs and DIVS with no luck. Can someone help?
In my example, when selecting 'Taking over existing Mobile' it should display 'Existing Mobile No', however it won't when the 'Existing PC' is still listed on my page.
HTML:
<ul>
<li>
<label for>NS - Mobile</label>
<select class="selectmenu" id="_1_1_81_1" name="_1_1_81_1" onchange="markDirty();">
<option value="" ><None></option>
<option value="Mobile" >Mobile</option>
<option value="Blackberry" >Blackberry</option>
<option value="otheros" >Taking over Existing Mobile</option>
</select>
</li>
<li class="osother">
<label for>NS - Existing Mobile No</label>
<input class="valueEditable" TYPE="text" name="_1_1_83_1" title="NS - Existing Mobile No" id="_1_1_83_1" value="[LL_FormTag_1_1_83_1 /]" size="12" MAXLENGTH="11" ONCHANGE="markDirty();">
</li>
<li>
<label for>NS - Existing PC</label>
<select class="selectMenu" id="_1_1_84_1" name="_1_1_84_1" onchange="markDirty();">
<option value="" ><None></option>
<option value="Yes" >Yes</option>
<option value="No" >No</option>
</select>
</li>
</ul>
JQ:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select").change(function () {
$("select option:selected").each(function () {
if ($(this).attr("value") == "otheros") {
$(".osother").show();
} else {
$(".osother").hide();
}
});
}).change();
});
</script>
CS:
.osother{display:none;}
My other JQ is here and collapses sections on the page - maybe irrelevant:
<script type="text/javascript" src="[LL_SUPPORTPATH /]core/jquery.collapsible.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
//collapsible management
$('.collapsible').collapsible({
defaultOpen: 'section1,section2,section3,section4,section5'
});
});
</script>
There is also some JavaScript here and there that adds in TABS and Date dropdowns, but have tested without these elements and it seems still not to work.
Basically you're looping through every select in the page and checking for their values, when you actually should observe just the one with ID _1_1_81_1.
Also, you can simplify your code:
$(function () {
// Observe the particular select for changes in its value.
// As every element in the page should have its on ID, you can
// select it straight away (omitting the type - select).
$("#_1_1_81_1").on("change", function () {
// Toggle the input visibility based on the selected value.
// The .val() method works here just like for every type of
// input. You don't need to go through all the select options
// and test their values.
$(".osother").toggle($(this).val() == "otheros");
});
});
Demo
jQuery .toggle()
Note: This answer is based on the code you provided. If there are any other requirements or code involved, you should state it in the question.
Im trying to work out how to take form field values and selected drop down menu options using a single loop and display them into individual divs on the same page.
At the moment ive managed to only achieve this using repetitive code rather than using a single loop. The form will eventually be very long with many fields and drop down menus (select options), therefore a loop would be a better option.
I would appreciate any help. Thanks in advance.
My code
<html>
<head>
<script src="jquery.js"></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$("#name").keypress(event) {
var stt = $(this).val();
$("#d_name").text(stt);
});
$("#email").keypress(event) {
var stt = $(this).val();
$("#d_email").text(stt);
});
$("#telephone").keypress(event) {
var stt = $(this).val();
$("#d_telephone").text(stt);
});
$("#car").change(function(event) {
var stt = $(this).val();
$("#d_type").text(stt);
});
$("#type").change(function(event) {
var stt = $(this).val();
$("#d_type").text(stt);
});
});//]]>
</script>
</head>
<body>
Name:
<input type="text" value="" id="name"/>
Email:
<input type="text" value="" id="email"/>
Telephone:
<input type="text" value="" id="telephone"/>
Car:
<select id="car" >
<option value="volvo">Volvo</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Type:
<select id="type">
<option value="automatic">automatic</option>
<option value="manual">manual</option>
</select>
Your Data
Name: <div id="d_name" ></div>
Email: <div id="d_email" ></div>
Telephone: <div id="d_telephone" ></div>
Car: <div id="d_car" ></div>
Type: <div id="d_type" ></div>
</body>
</html>
Do you mean:
$('input, select').change(function() {
$('#d_' + this.id).text($(this).val());
});
To your edit:
var updateText = function() {
$('#d_' + this.id).text($(this).val());
}
$('input').keypress(updateText);
$('select').change(updateText);
Example:
http://jsfiddle.net/kBGZ6/
Try something like this :
$(":input,:select").change(function(event) {
var val = $(this).val(); // get the val
var id = $(this).attr('id'); // get the id
$("#d_" + id).text(val); // use #d_ plus id to set the test to val
});
First line selects all input and select elements and adds processes the following function on change. This only works when the id of the div is d_ plus the id attribute from the form element.
And if you really wanted to, you could do it in a single line:
$(":input,:select").change(function(event) {
$("#d_" + $(this).attr('id')).text($(this).val());
});