Listbox from a dropdownlist - javascript

Can anyone tell me how can i load a listbox from a selected item of a dropdownlist?
Let's say i have a dropdownlist that contain "option1=male" & "option2=female"
I want that when male is selected, a list of male employees is shown in a listbox.
Added note:
i want to know how can i do this if employees names are saved in a file / data base?

Is this what you're after?
Selecting from a dropdown box a specific option will trigger an ajax call for a specific json file. On success, we display file's content into a listbox. This is just a demo.
Code sample:
$(document).ready(function() {
var listbox = $('#listbox'),
populateListbox = function(data) {
for (var i = 0, item; i < data.length; i++) {
item = data[i];
var option = $('<option>').val(item.age).text(item.name);
listbox.append(option);
}
showListbox();
},
emptyListBox = function() {
listbox.empty();
},
showListbox = function() {
listbox.removeClass('hide');
},
hideListbox = function() {
listbox.addClass('hide');
};
$('#dropdown').on('change', function (e) {
emptyListBox();
hideListbox();
var selectedOption = $("option:selected", this),
selectedValue = this.value;
switch (selectedValue) {
case 'male':
$.getJSON( "male.json", populateListbox);
break;
case 'female':
$.getJSON( "female.json", populateListbox);
break;
}
});
});

I gather that you want it to populate another listbox asynchronously? What you would need to do to achieve this is to use JavaScript and to call a function when the document loads. For example
$(document).ready(function(){
exampleFucntion();
});
This will call the function "exampleFunction" when the document loads. Inside this function the following code can be put where #dropdownbox would be the ID of your HTML drop down box.
$("#dropdownbox").change(exampleOnDropDownChanged);
This again will call a function that performs an action everytime the index of the drop down box changes. Inside the called function is where you would put the code to create another dropdown box dynamically with the details of male or female employees (or just populate an existing dropdown). Within the function you could put 'if' statements to get the male or female employees and then carry out the corresponding code to populate the dropdown. This function could also call a PHP page which could retrieve data and then populate the drop down.
The way I have described doesn't require the HTML page to be refreshed. I also suggest that you read around JavaScript and AJAX and also basic techniques, such as populating dropdown boxes.

I think this is what you are looking for. DEMO HERE
Select your gender and shows relative listbox.
<form id="survey" action="#" method="post">
<div id="section1">
<label for="Gender">Select employee gender.</label>
<select id="Gender" onchange="selection(this);">
<option value="Gender">---Select---</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div id="section2" style="display:none;">Please select employee gender from above.</div>
<div id="section3" style="display:none;">Male Employees
<br />
<label for="Jim">Jim</label>
<input type="radio" id="Jim" />
<label for="Tom">Tom</label>
<input type="radio" id="Tom" />
<label for="Sam">Sam</label>
<input type="radio" id="Sam" />
</div>
<div id="section4" style="display:none;">Female Employees<br />
<label for="Kate">Kate</label>
<input type="radio" id="Kate" />
<label for="Claire">Claire</label>
<input type="radio" id="Claire" />
<label for="Sue">Sue</label>
<input type="radio" id="Sue" />
</div>
</form>
<script>
var sections = {
'Gender': 'section2',
'Male': 'section3',
'Female': 'section4'
};
var selection = function (select) {
for (var i in sections)
document.getElementById(sections[i]).style.display = "none";
document.getElementById(sections[select.value]).style.display = "block";
};
</script>

Related

jQuery radio button value is not changed on page load

I searched the net and tried all solutions for similar questions from SO, but just can't get this one working.
I am working in Django admin, and I have RadioSelect widget for the field is_valid, with two radio buttons in the form:
<div class="form-row field-is_valid">
<div>
<label for="id_is_valid_0">Is it valid?</label>
<ul id="id_is_valid" class="inline">
<li><label for="id_is_valid_0"><input type="radio" name="is_valid" value="True" id="id_is_valid_0" checked>
Yes
</label>
</li>
<li><label for="id_is_valid_1"><input type="radio" name="is_valid" value="False" id="id_is_valid_1">
No
</label>
</li>
</ul>
</div>
</div>
<div class="form-row field-not_valid_reason">
<div>
<label for="id_not_valid_reason">Reason:</label>
<select name="not_valid_reason" id="id_not_valid_reason">
<option value="" selected>Choose</option>
<option value="Expired">Expired</option>
<option value="Not adopted">Not adopted</option>
<option value="Unknown">Unknown</option>
</select>
</div>
</div>
I want to hide a class .field-not_valid_reason when 'Yes' (True) is checked (which is default for is_valid field) and show it when I click 'No'. This I accomplished.
Here is my jQuery code:
(function($) {
$(function() {
var isValid = $('input[type=radio][name=is_valid]'),
notValidReason = $('.field-not_valid_reason'),
function toggleFields(value) {
if (value === 'True') {
notValidReason.hide(250);
} else {
notValidReason.show(250);
}
}
// show/hide on load based on previous value of isValid
toggleFields(isValid.val());
// show/hide on change
isValid.change(function() {
toggleFields($(this).val());
alert(isValid.val());
});
});
})(django.jQuery);
But, for some reason, after the object is saved in the database with the is_valid field False, when I am on the change page of that object, the class .field-not_valid_reason is hidden, albeit active radio button is set to "No" (False).
Can you help, please?
In your current jquery code you where using alert(isValid.val()); to see which option is selected but this will give you first value only so to get current value which user has selected use $(this).val().
Then , onload you where getting right value for radio but the div was still hidden because you are again passing toggleFields(isValid.val()); which will give you first value only .So , to overcome this pass radio value which is checked i.e : $("input[name='is_valid']:checked").val() .

Using Json how can I select a radio button based on value in my database?

Hi I have a form that has a button used to prefill my form with data from my database. Using Json It works fine to populate text inputs but how do I get it to select a radio button based on the value returned from my database?
FORM
<form action="#">
<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>
<button id="submit-id">Prefill Form</button>
<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">
<input type="radio" id="q1" name="q1" value="4.99" />
<input type="radio" id="q1" name="q1" value="7.99" />
<button id="submit-form" name="Submit-form" type="submit">Submit</button>
</form>
SCRIPT
<script>
$(function(){
$('#submit-id').on('click', function(e){ // Things to do when
.......
.done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
$('#q1').val(data.q1);
});
});
});
</script>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
........
while ($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
die(); // assuming there is just one row
}
}
?>
Don't use ID because you have same ID of both radio buttons
done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
// Don't use ID because the name of id is same
// $('#q1').val(data.q1);
var $radios = $('input:radio[name=q1]');
if($radios.is(':checked') === false) {
$radios.filter('[value='+data.q1+']').prop('checked', true);
}
});
You currently have both radio buttons using the same ID. ID's should be unique.
You can use the [name] attribute to do this, or you can set a class on the element. Here is an example:
$('input[name=q1][value="'+ data.q1 +'"]').prop('checked', true);
You can do it based on the value of said input:
instead of
$('#q1').val(data.q1);
Try
$('input:radio[value="' + data.q1 + '"]').click();
On a side note, you have both radios with the same ID, the results of an id based selector are going to vary from browser to browser because an id should be UNIQUE
you can refer the following link to solve your problem. works fine for me
JQuery - how to select dropdown item based on value

Onchange inside onchange jquery

Im having trouble having code onchange inside onchange event.
some works and some dont work due to that.
<script>
$(document).on('change', '.sellkop', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#text_container").after(price_option());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").css({"display": 'none'
});
};
});
$('#category_group').on('change', function() { // this is select options
if ($(this).val() == 101) {
$("#underKategory").css({"display": 'none'});
$("#modelcontainer").remove();
$(".toolimage").css({ "display": 'block'});
$('.sellkop').on('change', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").css({"display": 'block'});
$(".toolimage").css({"display": 'block' });
} else {
$(".toolimage").css({"display": 'none'});
}
});
} else {
$(".bilar").remove();
$(".toolimage").css({ "display": 'none'});
}
if ($(this).val() == 102) {
$(".houses_container").remove();
$(".toolimage").css({"display": 'none'});
$("#underKategory").css({"display": 'inline-block'});
$("#modelcontainer").remove();
}
///............many other values continue
});
</script>
i know there is better way to manage this code and simplify it , how can i do it ?
EDIT:
what i want is : if i select an option , then get values to that option, then under this category option there is radio buttons , then every check button i need to get some data displayed or removed
here is a fiddle there looks my problem by jumping from categories when i select buy or sell , so
if i select category-->check buy -->then select others . i dont get same result as if i select directly cars ---> buy
I have never resorted to even two answers before (let alone three), but based on all the comments, and in a desire to keep things simple another solution is to data-drive the visibility of other items based on selections, using data- attributes to store the selectors on the options and radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/28/
e.g the HTML for the select becomes
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101' data-show="#sellbuy,.cars,.toolimage,#licenscontainer">cars</option>
<option value='102' id='cat102' data-show="#sellbuy,#underKategory">others</option>
</select>
and the radio buttons like this:
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' data-show="#price_container,.cars,.toolimage"/>
The code becomes very simple then, simply applying the filters specified in the selected items.
$(document).on('change', '.sellkop', function () { // this is radio button
// Hide defaults
$("#price_container,.cars,.toolimage").hide();
// Show the items desired by the selected radio button
$($(this).data("show")).show();
});
$('#category_group').on('change', function () { // this is select options
// Get the various possible data options and decide what to show/hide based on those
var $this = $(this);
var value = $this.val();
// Get the selected option
var $li = $('option[value='+ value+']', $this);
// Hide all the defaults first
$('#licenscontainer,.cars,.toolimage,.sell,#underKategory').hide();
// Now show any desired elements
$($li.data('show')).show();
// Fire change event on the radio buttons to ensure they change
$('.sellkop:checked').trigger('change');
});
This is a very generic solution that will allow very complex forms to turn on/off other elements as required. You can add data-hide attributes and do something similar for those too if required.
Note: This was an attempt to fix the existing style of coding. I have posted an alternate answer showing a far simpler method using hide/show only.
A few problems.
If you must nest handlers, simply turn them off before you turn them on. Otherwise you are adding them more than once and all the previously recorded ones will fire as well.
Your HTML strings are invalid (missing closing </div>)
You can simply use hide() and show() instead of all the css settings. You should use css styling for any specific element styling requirements (e.g. based on classes).
You need to replace specific divs, rather than keep using after, or you progressively add more html. For now I have use html to replace the content of the #text_container div.
HTML in strings is a maintenance nightmare (as your example with missing </div> shows). Instead use templates to avoid the editing problems. I use dummy script blocks with type="text/template" to avoid the sort of problems you have found. That type means the browser simply ignores the templates.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/17/
HTML (with templates)
<script id="saljkop">
<div class='sex sell' id='sellbuy' >
<label ><input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked'/> Sell </label>
<label ><input id='rk' type='radio' class='radio sellkop' value='k' name='type'/>buy</label>
</div>
</script>
<script id="price_option">
<div class="container" id = "price_container">
<div>
<label><input class="price_option" name="price_opt" value="1" type="radio"/> Fix </label>
<label class="css-label"><input class="price_option" name="price_opt" value="2" type="radio"/> offer </label>
</div>
</div>
</script>
<script id="cars">
<div class="cars" >
<div id="licenscontainer" ><div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</script>
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">textttttt</div>
New jQuery code:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#sellbuy").after($('#cars').html());
$("#text_container").html($('#price_option').html());
$("#underKategory").hide();
$(".toolimage").show();
$('.sellkop').off('change').on('change', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").show();
$(".toolimage").show();
} else {
$(".toolimage").hide();
}
});
} else {
$(".cars").remove();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#text_container").html($('#price_option').html());
$(".toolimage").hide();
$("#underKategory").show();
}
///............many other values continue
});
Now if you prefer to not nest handlers (recommended), just add to your existing delegated event handler for the radio buttons:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
$("#licensenumber_c").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
$(".toolimage").hide();
};
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/20/
Note: This was a second answer, hoping to simplify the overall problem to one of hiding/showing existing elements. I have posted a third(!) answer that takes it to an even simpler scenario using data- attributes to provide the filter selections.
I am adding a second answer as this is a complete re-write. The other answer tried to fix the existing way of adding elements dynamically. I now think that was simply a bad approach.
The basic principal with this one is to have very simple HTML with the required elements all present and simply hide/show the ones you need/ Then the selected values are retained:
This uses the multi-structure to effectively hide.show the licence field based on two separate conditions.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/23/
Html (all element s present, just the ones you do not need hidden):
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
<div class='sex sell' id='sellbuy' style="display: none">
<label>
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' />Sell</label>
<label>
<input id='rk' type='radio' class='radio sellkop' value='k' name='type' />buy</label>
</div>
<div class="cars" style="display: none">
<div id="licenscontainer">
<div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">
<div class="container" id="price_container" style="display: none">
<div>
<label>
<input class="price_option" name="price_opt" value="1" type="radio" />Fix</label>
<label class="css-label">
<input class="price_option" name="price_opt" value="2" type="radio" />offer</label>
</div>
</div>
</div>
jQuery:
$(document).on('change', '.sellkop', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#price_container").show();
$(".cars").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").hide();
$(".cars").hide();
$(".toolimage").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").hide();
$("#sellbuy").show();
$(".cars").show();
$("#underKategory").hide();
$(".toolimage").show();
$('#licenscontainer').show();
} else {
$('#licenscontainer').hide();
$(".cars").hide();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").hide();
$("#sellbuy").show();
$(".toolimage").hide();
$("#underKategory").show();
$(".cars").hide();
}
$("#price_container").toggle($("#rs").is(':checked'));
///............many other values continue
});

Trying to find selected radio button. What's wrong?

I can read out text field values, but when I try to find the selected radio button, I get nothing.
$(document).ready(function(){
$("form#create_form").submit(function() {
var title = $('#title').attr('value');
var owner = $('#owner').attr('value');
var users = $('#users').attr('value');
var groups = $('#groups').attr('value');
var begin_date = $('#begin_date').attr('value');
var end_date = $('#end_date').attr('value');
// get selected radio button
var type = '';
for (i=0; i<document.forms[0].type.length; i++) {
if (document.forms[0].type[i].checked) {
type = document.forms[0].type[i].value;
}
}
HTML:
<div class="create-new">
<form id="create_form" name="create_form" action="" method="post">
...
<input name="type" id="type" value="individuel" type="radio" /> Individuel <br/>
<input name="type" id="type" value="course" type="radio" /> Course <br/>
<button class="n" type="submit">Create</button>
</form>
What am I doing wrong?
I would suggest an alternative method to getting the selected radio button (since you are already using jQuery):
$('input:radio[name=type]:checked').val();
This solution is an example on .val().
The above solution is much more succinct, and you avoid any conflicts in the future if other forms are added (i.e you can avoid the potentially hazardous document.forms[0]).
Update
I tested your original function with the following fiddle and it works:
http://jsfiddle.net/nujh2/
The only change I made was adding a var in front of the loop variable i.

Trigger AJAX with jquery click event

I have two drop down menus, one of which I am trying to replace with radio buttons using jquery. The second box is updated via AJAX with new options any time the user makes a selection in the first drop down. I have successfully generated radio buttons that change the values for the first drop down but when the user updates the first drop down menu using the radio buttons, it no longer effects values in the second drop down boxes. I am not great with AJAX or JS and I can't figure out how to trigger the AJAX load when the user selects one of radio buttons.
I apologize in advance for the wall of code, Im not sure what is important so I included everything that seemed relevant. If you want to see the page in question you can see it here.
The code I am using to generate radio buttons looks like this:
$(function(){
$("#options-1 option").each(function(i, e) {
$("<input type='radio' name='r' />")
.attr("value", $(this).val())
.attr("checked", i == 0)
.click(function () {
$("#options-1").val($(this).val());
})
.appendTo("#r");
$("#options-1").change(function(){
$("input[name='r'][value='"+this.value+"']").attr("checked","checked");
});
});
});
$("#options-1").change(function(){
$("input[name='r'][value='"+this.value+"']").attr("checked","checked");
});
The HTML for the drop downs look like this:
<form action="http://example.com/dev3/?page_id=5" method="post" class="shopp product validate">
<div id="r"></div>
<ul class="variations">
<li>
<label for="options-1">Framing</label>
<select name="products[1][options][]" class="category-catalog product1 options" id="options-1"><option value="1">Print Only (Unframed)</option>
<option value="2">Professionally Framed</option>
</select><li>
<label for="options-2">Size</label>
<select name="products[1][options][]" class="category-catalog product1 options" id="options-2"><option value="3">12 x 8</option>
<option value="4">24 x 36</option>
</select></li>
</ul>
<p><input type="hidden" name="products[1][product]" value="1" /><input type="hidden" name="products[1][category]" value="catalog" /><input type="hidden" name="cart" value="add" /><input type="submit" name="addtocart" value="Add to Cart" class="addtocart" /></p>
</form>
The AJAX looks like this:
<script type='text/javascript' src='http://example.com/dev3?sjsl=colorbox,shopp,catalog,cart&c=1&ver=98239bb061a58639408323699680ad0e'></script>
<script type='text/javascript'>
/* <![CDATA[ */
var ShoppSettings = {
ajaxurl: "http://example.com/dev3/wp-admin/admin-ajax.php",
cp: "1",
c: "$",
p: "2",
t: " ",
d: ".",
g: "3",
nocache: "",
opdef: ""
};
var pricetags = {};
jQuery(window).ready(function(){ var $ = jqnc();
pricetags[1] = {};
pricetags[1]['pricing'] = {"18770":{"p":10,"i":false,"s":false,"t":"Shipped"},"25785":{"p":21,"i":true,"s":"1","t":"Shipped"},"23510":{"p":20,"i":false,"s":false,"t":"Shipped"}};
pricetags[1]['menu'] = new ProductOptionsMenus('select.category-catalog.product1.options',true,pricetags[1]['pricing'],0);
});
/* ]]> */
</script>
When you change the value of a Combo Box via js, it doesn't trigger the onChange function nor onClick and so on.
You'll have to use the same code you use to update Combo 2 with Combo 1 where you update Combo 1 with the Radio.
I suggest to place that code inside another function, and call that function from both places.
Hope it helps.

Categories