I have made a way to present a droplist to end user and by default containing 4 items (value=a,value=b,value=c,value=d). When a user click on a checkbox the content of the droplist changes to only 2 items (value=a,value=b) IF unchecked returned to default state.
I achieve this way below using hiding div but wondering if a better different way using Jquery, I have searched and cant figure it out using let say if checked present these options else present default. Currently I have to work with 2 different dropdown which is awkward when passing values in a form.
THE CHECKBOX
<label for="optionChoice"><input class="optionChoice" type="checkbox" id="optionChoice" name="optionChoice" value="YES" onClick="if(this.c.........
IN MY PHP PAGE I HAVE 2 DIV WHERE ONE IS VISIBLE AND THE OTHER IS NOT ALL DEPENDS ON IF CHECKBOX CLICKED THEN MAKE ONE VISIBLE AND THE OTHER INVISIBLE VISVERSA.
<div id="test">
<table class="TableStyle">
<tr>
<td>
<label for="serviceType">Service Type<font color="red"><b> * </b></font></label>
</td>
</tr>
<tr>
<td>
<select name="serviceType" id="serviceType">
<option value="" label="-- Choose One --"> -- Choose One --</option>
<option value="A" label="A">A</option>
<option value="B" label="B">B</option>
<option value="C" label="C">C</option>
<option value="D" label="D">D</option>
</select>
</td>
</tr>
</table>
</div>
<div id="test2">
<table class="TableStyle">
<tr>
<td>
<label for="serviceType2">Service Type<font color="red"><b> * </b></font></label>
</td>
</tr>
<tr>
<td>
<select name="serviceType2" id="serviceType2">
<option value="" label="-- Choose One --"> -- Choose One --</option>
<option value="A" label="A">A</option>
<option value="B" label="B">B</option>
</select>
</td>
</tr>
</table>
</div>
script
$(function() {
enable_cbChoice();
$("#optionChoice").click(enable_cbChoice);
});
function enable_cbChoice() {
if (this.checked) {
$("#test").hide();
$("#test2").show();
}
else{
$("#test").show();
$("#test2").hide();
}
}
Try to just have one dropdown (id="serviceType") and then add or remove the options based on the state of the checkbox:
var detached;
$('#optionChoice').on('change', function() {
var $el = $(this);
if( $el.prop('checked') ) {
detached = $('option[value="C"], option[value="D"]').detach();
} else {
$('#serviceType').append(detached);
}
});
Working Fiddle: http://jsfiddle.net/jhummel/D43fh/
You can achieve this by detecting the state of the checkbox using javascript. I can show you the method using jquery. Then you can use the remove and append function of jquery to add and remove values from the dropdown. To achieve your problem, you can do something like this.
$('input[type="checkbox"]').click(function() {
if( $(this).is(':checked') ) {
$("#selectBox option[value='C']").remove();
$("#selectBox option[value='D']").remove();
} else {
$('#selectBox').append('<option value="C">C</option>');
$('#selectBox').append('<option value="D">D</option>');
}
});
Related
I have a drop down box, this is populated with options that after selecting it shows hidden text by calling the function toggletDisplay() and sending the value of the option throug, I want it to be able to do the same but without the drop down box to select, using instead plain text with onclick() instead of onchange() or something similiar.
Current Code
<form id="criteria" name="criteria">
<table width="200px" height="700px" name="criteria_search" align="left" border="1" style="margin-right:70px">
<tr>
<td class="dataLabel" width="100%" align="left"><strong>Add Rule : </strong>
<select name="rule" id="rule" onChange="toggletdDisplay(this.form);">
<optgroup label="Simple Rules">
<option value="instructions" selected="selected"> </option>
<option value="email">Email</option>
<option value="assigned">Assigned Racecourse</option>
</optgroup>
</select>
</td>
</tr>
</table>
<table align="right" border="1" width="300px" height="400px" style="float:left;">
<tr>
<td class="dataLabel" name="assigned" id="assigned" style="display: none;">
<table border="0">
<tr>
<td colspan="3"><h4>Assigned to Racecourse</h4></td>
</tr>
<tr>
<td style="margin-left:20px">
<b>Assigned To: </b><select name="selected_assigned_location" id="selected_assigned_location"></select>
</td>
</tr>
</table>
</td>
<td width="100px" class="dataLabel" name="email" id="email" style="display: none;" >
<table>
<tr>
<td colspan="3"><h4>Registered Email</h4></td>
</tr>
<tr>
<td><b>Do they have a registered Email Account?</b></td>
</tr>
<tr>
<td>
Yes <input type="radio" name="email_c" value="true_ex" {EMAIL_TEX_CHECKED} checked="checked"> No <input type="radio" name="email_c" value="false" {EMAIL_F_CHECKED}>
</td>
</tr>
</table>
</td>
...ect
I tried just sending the value through as an onclick
<td>
<p id="rule" name="rule" value="email" onclick="toggletdDisplay(this.form);">Email</p>
</td>
But I get an error of value rule is undefined. How would I send the value through the same as before but without using a select statement?
Added the toggletDisplay, simply uses the value sent back to change the style of the datalabel from hidden to inline
function toggletdDisplay(me)
{
list = Array("instructions","sex", "email", "mobile", "account", "age", "location", "spent", "booked_anything", "internet_booked", "package_type", "package_name", "booked_location", "new_booked_event", "booked_event_range","team", "no_reorder", "newsletter","hear_about","hear_about_bookings","mosaic_group","mosaic_type","assigned","assigned_user","lead_source","target_list","awc","birthday");
// hide any previously selected elements
for(x=0; x<list.length; x++)
{
deselect = getElementsByName_iefix("TD", list[x]);
for (j=0; j<deselect.length; j++)
{
deselect[j].style.display = "none";
}
}
// display currently selected criteria
selected = getElementsByName_iefix("TD", me.rule.value);
selected[0].style.display = "inline";
}
There seem to be a number of issues with your code. One of them is the undefined function toggletdDisplay() that is called whenever you change the selection in your select field.
But, basically, if you want to send a value of an input field or a select box within a form to a php script on your server you will need to define an action attribute in your <form> tag and make sure that the form is submitted. This can be achieved in your case by changing the onchange attribute in your select box (simplified code, without the table architecture):
Whenever you change the selection in your select box the form will be submitted and the value of that select box will be sent to target.php. The address line in your browser will show something like
...<your URL>/target.php?rule=email
It is also not clear to me why you use colspan attributes in some of your <td>-elements, as there is only one column to display in that table.
My advice is to be economical with "cut and paste" and only use code that you fully understand. Build your page slowly, step by step. That way you will be able to understand what needs to be fixed if something goes wrong.
Edit
With your toggletdDisplay() script we have something to work on. The first thing that springs to my mind is that you are not using jquery functions where they might be helpful. And secondly, you don't do anything to display the form values in the console window or send them to a php script.
It is also important to note that name attributes can only be assigned to <input> or <select> elements and not to <td> elements. In my following script I used the id attribute instead.
var tds,tdis;
$(function(){
var list = ["instructions","sex", "email", "mobile", "account", "age", "location", "spent", "booked_anything", "internet_booked", "package_type", "package_name", "booked_location", "new_booked_event", "booked_event_range","team", "no_reorder", "newsletter","hear_about","hear_about_bookings","mosaic_group","mosaic_type","assigned","assigned_user","lead_source","target_list","awc","birthday"];
// consider only TDs with IDs from list array:
tds= $('td').filter(function(i,el){return $.inArray(el.id,list)>-1;});
// trigger the display of results only for select and input elements within tds:
tdis=$('select,input', tds).on('change',listResults);
// assign the toggletdDispla function to the rule selector:
$('.action').on('change',toggletdDisplay);
});
function toggletdDisplay(){ tds.hide().filter('#'+this.value).show()}
function listResults(){
$('#show').html('<p>Values to be sent:</p>'+tdis.serialize().replace(/&/g,'<br/>'))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="target.php">
<table name="criteria_search" align="left" border="1" style="margin-right:70px">
<tr><td class="dataLabel"><strong>Add Rule : </strong>
<select name="rule" id="rule" class="action">
<optgroup label="Simple Rules">
<option value="instructions" selected="selected"> </option>
<option value="email">Email</option>
<option value="assigned">Assigned Racecourse</option>
</optgroup>
</select>
</td><td class="dataLabel" id="email" style="display:none">
<b>email:</b>
<br/><label><input type="radio" name="email_c" value="true_ex"> yes</label>
<br/><label><input type="radio" name="email_c" value="false"> no</label>
<br/><label><input type="radio" name="email_c" value="soon"> not yet</label>
</td>
<td class="dataLabel" id="assigned" style="display:none">
Racecourse<br/>
<b>Assigned To: </b>
<select name="selected_assigned_location">
<option value=""></option>
<option value="a">racecourse A</option>
<option value="b">racecourse B</option>
<option value="c">racecourse C</option>
</select>
</td>
</tr>
</table>
</form><br style="clear:both" />
<div id="show"></div>
I have a group of dynamic rows each with a dropdown and checkboxes and need to change the individual dropdown value of that row if all its checkboxes are selected.
Currently I can only get this to work if I select all checkboxes in all rows.
How can I make it so only a row's dropdown changes when the checkboxes it belongs to are all selected?
I setup this fiddle with markup of what works right now. Thanks for the help!
http://jsfiddle.net/uyv3mk7b/
<!--First row eventRegistrations[1]-->
<select class="regSelect" name="eventRegistrations[1].eventRegistrationStatusTypeID" id="registrationStatusSelect">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked" name="eventRegistrations[1].markAttendance[1].attendanceDate" value="1">9/21/14
<input type="checkbox" class="regChecked" name="eventRegistrations[1].markAttendance[2].attendanceDate" value="2">9/22/14 <br>
<!--There could be multiple dynamic rows whose input names increment like eventRegistrations[i]-->
<!--Next dynamic row eventRegistrations[2]-->
<select class="regSelect" name="eventRegistrations[2].eventRegistrationStatusTypeID" id="registrationStatusSelect">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked" name="eventRegistrations[2].markAttendance[1].attendanceDate" value="1">10/23/14
<input type="checkbox" class="regChecked" name="eventRegistrations[2].markAttendance[2].attendanceDate" value="2">10/24/14
//Change dropdown to Attended when all of checkbox group is selected
//Currently only works when all 4 checkboxes are selected, not the 2 in each group/row
$('.regChecked:checked').length == $('.regChecked').length
$(".regChecked").change(function () {
if ($('.regChecked:checked').length == $('.regChecked').length) {
$('.regSelect').val('2');
}
});
You need to add a wrapper to your rows, like section, or div, and on change, you can loop through only the parents childrens collection.
Tyr this: http://jsfiddle.net/uyv3mk7b/3/
HTML
<!--First row eventRegistrations[1]-->
<section>
<select class="regSelect" name="eventRegistrations[1].eventRegistrationStatusTypeID" id="registrationStatusSelect1">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked" name="eventRegistrations[1].markAttendance[1].attendanceDate" value="1">9/21/14
<input type="checkbox" class="regChecked" name="eventRegistrations[1].markAttendance[2].attendanceDate" value="2">9/22/14 <br>
</section>
<!--There could be multiple dynamic rows whose input names increment like eventRegistrations[i]-->
<!--Next dynamic row eventRegistrations[2]-->
<section>
<select class="regSelect" name="eventRegistrations[2].eventRegistrationStatusTypeID" id="registrationStatusSelect2">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked" name="eventRegistrations[2].markAttendance[1].attendanceDate" value="1">10/23/14
<input type="checkbox" class="regChecked" name="eventRegistrations[2].markAttendance[2].attendanceDate" value="2">10/24/14
</section>
jQuery
//Change dropdown to Attended when all of checkbox group is selected
$(".regChecked").change(function() {
var checks = $(this).parent().find('.regChecked');
var allChecked = true;
$.each(checks, function(idx, value) {
if (!$(this).is(':checked')) {
allChecked = false;
}
});
if (allChecked) {
$(this).parent().find('.regSelect').val(2);
} else {
$(this).parent().find('.regSelect').val(1);
}
});
//When dropdown value is Attended, select all in checkbox group
$("select").change(function() {
if ($(this).val() === '2') {
$(this).parent().find('.regChecked').prop('checked', true);
}
});
You can add some sort of identifier to each group like
<select class="regSelect group-select-1" name="eventRegistrations[1].eventRegistrationStatusTypeID" id="registrationStatusSelect">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked group-1" name="eventRegistrations[1].markAttendance[1].attendanceDate" value="1">9/21/14
<input type="checkbox" class="regChecked group-1" name="eventRegistrations[1].markAttendance[2].attendanceDate" value="2">9/22/14 <br>
and then manipulate with this identifiers
$(".group-1").change(function () {
if ($('.group-1:checked').length == $('.group-1').length) {
$('.group-select-1').val('2');
}
});
Fiddle
UPD Added fiddle with else cases, thx to Roberto Linares.
P.S. ids have to be unique
Here i come with two question one is on onload all listbox to be hide depend of radio button listbox had to show/hide listbox but its not working here and other one is i have to check if listbox option value contain null value or empty space if means i have to remove it. thats too not working there any mistake in code could some one help on this .
<script>
if ($('input[name=B]:checked').val() == "city") {
$("#country,#zone,#state,#Areamanager,#outlet").val('');
$("#country_value,#zone_value,#state_value,#Areamanager_value,#outlet_value").val('');
$("#city").show();
$("#country,#zone,#state,#Areamanager,#outlet").hide();
}
$.each(main, function (i, val) {
if (val == "Null Value" || val == "") {
val = null;
}
});
</script>
Refer the link
Had a look at the fiddle provided
Fiddle http://jsfiddle.net/Varinder/tHXN3/1/
It is considered bad practice to inline JS event calls.
Usualy it is a good indication to refactor if you notice the logic being repeated more than three times.
Correct me if im wrong, you're requirements are:
show a bunch or dependant fields based on the radio button selected
reset all the fields that are not related to currently active radio button
on page load strip off all the select box options that are either having "Null value" or simply an empty string.
A little bit of refactoring on HTML side of things can go a long way when traversing it via jQuery:
Heres the structure i reckon will suit your requirement ( more on this further down ). And i've simplified it a bit by only working on the first radio button row:
<table cellpadding="0" cellspacing="0" border="2">
<tr>
<td><input type="radio" name="A" data-dependson=".maingroup-section"/></td>
<td><font size="2">Main Group</font></td>
<td><input type="radio" name="A" data-dependson=".subgroup-section"/></td>
<td><font size="2">Sub Group</font></td>
<td><input type="radio" name="A" data-dependson=".itemname-section" /></td>
<td><font size="2">Item Name</font></td>
</tr>
</table>
<div class="form-row">
<div class="maingroup-section">
field values related to main group:<br />
<select id="maingroup">
<option value="Null Value">Null Value</option>
<option value="1">AA</option>
<option value="2">BB</option>
<option value="3">CC</option>
<option value="Null Value">Null Value</option>
</select>
<input type="hidden" id="maingroup_value" />
</div>
<div class="subgroup-section">
field values related subgroup:<br />
<select id="subgroup">
<option value="Null Value">Null Value</option>
<option value="1">DD</option>
<option value="2">EE</option>
<option value="3">FF</option>
<option value="Null Value">Null Value</option>
</select>
<input type="hidden" id="subgroup_value" />
</div>
<div class="itemname-section">
field values related to itemname:<br />
<select id="itemname">
<option value="Null Value">Null Value</option>
<option value="1">GG</option>
<option value="2">HH</option>
<option value="3">II</option>
<option value="Null Value">Null Value</option>
</select>
<input type="hidden" id="itemname_value" />
</div>
</div>
First things first, you'll notice the use of data-attributes in this case its data-dependson which contains class name of div containing dependant fields
JS
Start off by caching references to all the elements that will be (ab)used:
var $aGroupRadioButtons = $("input[name='A']");
var $formRow = $(".form-row");
var $allDropdowns = $formRow.find("select");
Handling FormSections ( .maingroup-section, .subgroup-section etc ) can be abstracted away in a function like below, it takes reference to currently active formsection and hides and resets the value of sibling form sections.
function handleFormSections( $formSection ) {
var $currentFormSection = $formSection.show();
var $otherFormSections = $currentFormSection.siblings().hide();
resetFormSections( $otherFormSections );
}
And resetFormSections function resets input and select elements of the form sections provided by the argument
function resetFormSections( $formSections ) {
$formSections.find("select").val("");
$formSections.find("input").val("")
}
Well, the above two functions are good enough to show dependant form section, hide and reset other form sections.
Now you can hook up those functions via event handlers, im using jQuery 1.8 so i can use $(selector).on("event", handler) syntax.
$aGroupRadioButtons.on("click", function(e) {
var $radioItem = $( this );
var dependantSectionName = $radioItem.attr("data-dependson");
var $dependantSectionElement = $( dependantSectionName );
handleFormSections( $dependantSectionElement )
});
As from the code above, its looking at the data-dependson value to identify which form section to show and which ones to hide.
And somewhere along the line you'd want to strip off empty or null values. Again, how about we create a function to handle that for us? and maybe call it removeNullOrEmptyOptionsFrom( selectBox ) which will recieve a selectBox element to work on, heres how:
function removeNullOrEmptyOptionsFrom( selectBox ) {
var $selectBoxOptions = $(selectBox).children();
$selectBoxOptions.each(function() {
var $option = $(this);
var optionValue = $option.attr("value");
if ( optionValue == "Null Value" || optionValue == "" ) {
$option.remove();
}
});
}
Now, you can call the above function on every select box in the .form-row container like below:
$allDropdowns.each(function() {
removeNullOrEmptyOptionsFrom( this );
});
I noticed in your code there is a call to combobox method, if it is a jQuery plugin then probably a good idea to call it after we've stripped off all the null or empty options:
// $allDropdowns.combobox(); // initialize combox once maybe after reseting selects?
I would like to do to auto select in check box when the selection box is selected in the same row.
Although I found this question in stackoverflow, unfortunately it didn't match my requirement. So, please give me some suggestions.
There are many rows in a table. In each row, there has one check box and one selection box in each column.If I selected something in selection box in a row, I want to do auto check in check box in the same row.
I wrote the code as the following.
<script>
$(document).ready(function() {
$('.sel_ActList_status').change(function() {
$('.sel_ActList_status').parent('td').silbings('td').find(".chk_ActList_select").checked = true;
//$('.sel_ActList_status').parent('td').silbings('td').find(".chk_ActList_select").prop("checked", true);
});
});
</script>
<table>
<tr>
<td>
<input id="chk_ActList_select[0]" class="chk_ActList_select" type="checkbox" value="true" name="chk_ActList_select[0]">
</td>
<td>xxxxx</td>
<td>
<select id="sel_ActList_status" class="sel_ActList_status" name="sel_ActList_status">
<option selected="selected" value="2">11111</option>
<option value="0">22222</option>
<option value="1">33333</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="chk_ActList_select[1]" class="chk_ActList_select" type="checkbox" value="true" name="chk_ActList_select[1]">
</td>
<td>xxxxx</td>
<td>
<select id="sel_ActList_status" class="sel_ActList_status" name="sel_ActList_status">
<option value="2">11111</option>
<option selected="selected" value="0">22222</option>
<option value="1">33333</option>
</select>
</td>
</tr>
</table>
But my code is not working to auto check in checkbox when I selected something in selectbox. Is there anything wrong in my jquery code? Pls give me some guideline.
Thanks in advance.
Try This, this is helpfull for you
$('.sel_ActList_status').change(function(){
$(this).closest('tr').find('input:checkbox').prop('checked',true);
});
try this
$('.sel_ActList_status').change(function() {
$(this).parent('td').siblings().find(".chk_ActList_select").attr("checked", "true");
});
try this
$('.sel_ActList_status').change(function(){
$(this).parent().parent().find('input[type=checkbox]').attr('checked','checked');
});
At its simplest, I'd suggest:
$('select').change(function(){
$(this).closest('tr').find('input').prop('checked',true);
});
JS Fiddle demo.
Though if you enable checking by selecting, or changing the select-box, you should probably enable un-checking by the same route (just to retain a consistent UI), so I'd amend the select elements, adding a 'none' option (<option selected="selected" value="-1">None</option>), and, if that's selected, un-check the box:
$('select').change(function(){
var self = this;
$(this).closest('tr').find('input').prop('checked', self.value !== '-1');
});
JS Fiddle demo.
I have created this form with several select menu and a couple of jQuery hide and show functions. The way the form is supposed to work is that, when you click on the options from the main select menu it sould autimatically show you the corresponding select submenu.
Here is my code:
jQuery:
$("#mankleding").bind("click",menclothes);
$("#manschoen").bind("click",menshoes);
$("#manaccessoires").bind("click",menaccessoires);
function menclothes(evt){
$("#subkledingheren").show("fast");
$("#subschoenenheren").hide("fast");
$("#subsaccessoiresheren").hide("fast");
}
function menshoes(evt){
$("#subkledingheren").hide("fast");
$("#subschoenenheren").show("fast");
$("#subsaccessoiresheren").hide("fast");
}
function menaccessoires(evt){
$("#subkledingheren").hide("fast");
$("#subschoenenheren").hide("fast");
$("#subsaccessoiresheren").show("fast");
}
HTML:
<tr>
<td> Artikel hoofd-categorie: </td> <td> <select id="manhoofd">
<option>HEREN</option>
<option id="mankleding">KLEDING</option>
<option id="manschoen">SCHOENEN</option>
<option id="manaccessoires">ACCESSOIRES</option>
</select>
</td>
</tr>
<tr>
<td> Artikel sub-categorie: </td> <td id="subcategorie"> <select id="subkledingheren">
<option>HEREN-KLEDING</option>
<option>Broeken & Jeans</option>
<option>Jassen</option>
<option>Sweaters & Hoodies</option>
<option>Zwemkleding</option>
</select>
<select id="subschoenenheren">
<option>HEREN-SCHOENEN</option>
<option>Sneakers / Casual</option>
<option>Slippers & Sandalen</option>
<option>Instappers</option>
</select>
<select id="subsaccessoiresheren">
<option>HEREN-ACCESSOIRES</option>
<option>Horloges</option>
<option>Brillen & Zonnebrillen</option>
<option>Stropdassen</option>
</select>
</td>
</tr>
Try using change event:
$('#manhoofd').change(function(){
var i = $('option:selected', this).text();
$('select(:not(:first))').hide();
$('select:contains('+i+')').show()
})
DEMO