Remove one value from all drop down using jquery - javascript

I have multiple drop down with same value.If they select Lunch first time from other drop down I have to remove Lunch. Following is my code
Front end code
<?php for($i=1; $i<=7; $i++)
{?>
<select name="task<?php echo $i;?>" onchange="checkSelected(this,<?php echo $i; ?>);" id="task<?php echo $i;?>"
<option value="Testing">Testing</option>
<option value="Lunch">Lunch</option>
<option value="Other">Other</option>
</select>
<?php } ?>
In javascript I am removing 3rd select box (task3) its got removed but i have to remove all the other except the selected one how i can implement this
javascript function
function checkSelected(e,number)
{
if(e.value == 'Lunch')
{
$('#task3 option[value="Lunch"]').remove();
}
}
I tried this but its not working
$("#task+"number"+ > option[value='Lunch']").remove();

It should be
$("#task" + number + " > option[value='Lunch']").remove();

You could use the .each() function to remove only the option that has the value you select from the list.
$('select').change(function(){
var value = $(this).val()
// Probably best to store this value here before removing the option below.
$(this).children().each(function(){
if($(this).val() == value){
$(this).remove();
}
});
});
Working example - http://jsfiddle.net/amQuU/
Example with multiple dropdowns http://jsfiddle.net/amQuU/1/
Example that removes the options from another select box - http://jsfiddle.net/amQuU/2/
The only problem in doing this is that by removing the selected option it is not shown as the selected option. you can however store the value after selecting it and before removing it from the list as commented above.
Another thing you should consider is changing .remove() to .attr('disabled','true') so that you can re-enable the option later on if you need to e.g. someone wants to go back and change the previous select. Here is an example of that too http://jsfiddle.net/amQuU/3/

If only the "lunch" option is concerned by your answer (see my comment above), then there's a solution. It's not already full-optimized, but you see how you can do it.
JSFiddle http://jsfiddle.net/4qndV/1/
HTML
<form action="demo.html" id="myForm">
<p>
<label>First:</label>
<select class="event_handler" name="task1">
<option value="Testing">Testing</option>
<option value="Lunch">Lunch</option>
<option value="Other">Other</option>
</select>
</p>
<p>
<label>Second:</label>
<select class="event_handler" name="task2">
<option value="Testing">Testing</option>
<option value="Lunch">Lunch</option>
<option value="Other">Other</option>
</select>
</p>
<input type="submit" value="Submit">
</form>
JQuery
$(function () {
// Handler for .ready() called.
$(".event_handler").on("change", function () {
event.preventDefault();
var name_select = $(this).attr("name");
if ($(this).val() == "Lunch") {
//Loop through each "lunch" element
$('.event_handler option[value=Lunch]').each(function(){
//Remove all 'lunch' option, except the ont in the 'name_select' select
if($(this).parent().attr("name") != name_select){
$(this).remove();
}
});
}
})
});
NB: I suppose you have to allow the user to change his selection. It's why I use "disable" in place of "remove". But you can easily adapt this code if you really want to remove the option element.

Related

Database value cannot get it to the Dropdownlist jQuery

In my database there's a column, name is Sequence & it consist of numbers(int). In my application's edit function I need to show that selected number in my jQuery dropdown list.
In my AJAX call I sent ProductId and get the specific row.
Html Control
<select class="form-control" id="drpsequence"></select>
My jQuery dropdown
$("#drpsequence option:selected").append($("<option></option>").val(msg._prodlng[0].Sequence).text(msg._prodlng[0].Sequence));
In the above code msg._prodlng[0].Sequence comes as selected number
I'm not sure what you are trying to do but it looks like you are adding an <option> tag into another <option> tag which is most likely not what you want.
If the returned value already exists as a selected option:
$("#drpsequence").val(msg._prodlng[0].Sequence).prop('selected', true);
Or, if you need to add an option:
var opt = $("<option>")
.val(msg._prodlng[0].Sequence)
.text(msg._prodlng[0].Sequence);
$("#drpsequence").append(opt);
Snippet example:
// foo --> select
$('#foo').val('baz').prop('selected', true);
$('#bim').click(function(){
$('#foo').append('<option id="boop" value="boop">boop</option>'); //<-- or loaded value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="foo">
<option>-- select --</option>
<option id="bar" value="bar">bar</option>
<option id="baz" value="baz">baz</option>
</select>
<button id="bim">Add an option</button>
You need to do one of following.
Either find that option and make that selected = true like this.
$("#sel option").each(function(i) {
if ($(this).val() == "Orange") $(this).attr("selected", "true");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</select>
Or if that option is not found then add and make that selected = true.
Like the one, which you had in your question.

Remove the first select option

I'd like to remove the first option of an select tag when I click on the select tag. Is this possible?
I don't want to see the first option after that click.
Thanks for any help.
You can remove the first option on click with jQuery.
$(document).on('click', 'select', function() {
$(this).find('option').get(0).remove();
});
This simply removes the first option of a select tag on click. You need to add an if statement to check if it was already removed.
There's also a simple no-javascript solution:
<select>
<option style="display: none">--Choose--</option>
<option>Cheese Cake</option>
<option>Hot Pockets</option>
<option>Sausage</option>
<option>Cookies</option>
<option>Bacon</option>
</select>
(Copied from the comments from #chipChocolate.py)
If you use bootstrap add placeholder attribute in your select.
If your not
<select required>
<option value="" disabled selected>Select your option</option>
<option value="1">1</option>
</select>
// to remove first...
document.getElementById("element_id_str").options[0].remove();
//to remove the lot...
document.getElementById("element_id_str").options.length = 0;
<select required>
<option value="" disabled selected hidden>Select your option</option>
<option value="1">1</option>
</select>
Probably you just want this:
<select required>
<option value="" hidden>Select your option</option>
<option value="1">1</option>
</select>
A very naive way of doing this:
$("#selector").change(function(evt) { //listen to changes of selection
var theElement = $(this);
if (!theElement.data("selected")) { //check if flag is not set
theElement.children("option")[0].remove(); //remove 1st child
theElement.data("selected", true); //set flag, so it doesn't continue removing items for every change
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector">
<option>--Choose--</option>
<option>Apple</option>
<option>Banana</option>
<option>Papaya</option>
</select>
If you want to remove the first option use this
$(document).ready(function()
{
$("select").children().first().remove();
});
If you want to remove the first option after clicking on the select box use this
$(document).ready(function()
{
var removed=false;
$(document).on("click","select",function()
{
if(!removed)
{
$(this).children().first().remove();
removed=true;
}
});
});
Javascript:
document.getElementById("SelectId")[0].remove();
Get the first option in the select and remove it.
I had the same problem, but the solutions above just work with one form, not with many. I added some extra code in order to validate it for many in your form:
$(document).ready(function()
{
$(document).on("change","select",function()
{
var x = $(this).children().first().attr("name");
var n = x.localeCompare("todelete");
if (n == 0)
$(this).children().first().remove();
});
});
Where "todelete" is the name for all first elements [0] defined inside the
Please select value //all first elem must have the same name
"> //the others another name (can be the same BUT not "todelete")
You need the id or class to remove the item. While testing and debugging I found 'option:first' fails to remove the item. But 'option:first-of-type' always does the work. You can get more info about 'first-of-type' here :first-of-type
$("#ID_or_.CLASS option:first-of-type").remove();

Having a input text appear when chosen option in a double drop down select option

Say I want to create a double drop down select options where the second drop down list changes according to which the first drop down option is selected. I've already figured out how to do this. BUT one of my first drop option is "Others" and I want an input textbox to appear if I select "others" in the first dropdown list instead of having a second drop down option list. So far, I've been able to get the input textbox to appear, but the second drop down option list also appears (as undefined). How do I make the second drop down option list disappear?? Also, if one of the options in the first dropdown list doesn't need or have a second drop down option list, how do I code this?
This is an example of my script (I only changed the names of the categories):
<form name="search" method="get">
<select name="cat" id="cat" size="1" onChange="redirect(this.options.selectedIndex)">
<option selected disabled>Category</option>
<option value="fruit">Fruit</option>
<option value="music">Music</option>
<option value="vegetable">Vegetable</option>
<option value="book">Book</option>
<option value="other">Other</option>
</select>
<input type='text' id="other" class="hidden" />
<select name="cat2" size="1">
<option selected disabled>Sub-category</option>
</select>
<input type="button" name="Search" value="Search" onClick="go()" /
</form>
This is my javascript:
$('#cat').change(function(){
var selected_item = $(this).val()
if(selected_item == "other"){
$('#other').val("").removeClass('hidden');
}else{
$('#other').val(selected_item).addClass('hidden');
}
});
var groups=document.search.cat.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=0
group[1][0]=new Option("Moodle")
group[1][1]=new Option("Ultranet")
group[1][2]=new Option("Private School")
group[2][0]=new Option("Gmail")
group[2][1]=new Option("Windows Live")
group[2][2]=new Option("Office 365")
group[3][0]=0 //has no second dropdown option, how do I make it disappear?
group[4][0]=new Option("Kamar")
group[4][1]=new Option("Musac")
group[5][0]=new Option("Windows")
group[5][1]=new Option("Mac")
group[5][2]=new Option("Novell")
group[5][3]=new Option("Linux")
group[6][0]=new Option("Ruckus Wireless")
group[6][1]=new Option("Aerohive Networks")
group[6][2]=new Option("Aruba Networks")
group[7][0]=new Option("Pre-Trial")
group[7][1]=new Option("Implementation")
group[7][2]=new Option("Full Trial")
group[8][0]=0 //The 'others', I don't know what to put here to make this disappear
var temp=document.search.cat2
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
You need to add 2 new lines to the .change function, from:
$('#cat').change(function(){
var selected_item = $(this).val()
if(selected_item == "other"){
$('#other').val("").removeClass('hidden');
}else{
$('#other').val(selected_item).addClass('hidden');
}
});
Change it to
$('#cat').change(function(){
var selected_item = $(this).val()
if(selected_item == "other"){
$('#other').val("").removeClass('hidden');
$("select[name=cat2]").addClass('hidden');
}else{
$('#other').val(selected_item).addClass('hidden');
$("select[name=cat2]").removeClass('hidden');
}
});
So when you remove hidden class from the input you have to add it to the select with name "cat2", and vice-versa. Hope this helps you.

Javascript function to check a box based on value of select option

I currently have a javascript function, which changes a select option to 1 if a checkbox is checked. What I can't seem to figure out, is how to automatically check the box if the user fails to tick the checkbox and just chooses a value (other than 0) from the select dropdown. The script has ID's and names that are generated with php array values.
Thank you for taking the time to look at this.
function quantityChangeHandler(source) {
var qtyElem = document.getElementById(source.getAttribute('rel'));
if (source.checked) {
if (qtyElem.value == 0)
qtyElem.value = 1;
}
else
qtyElem.value = 0;
}
<input type="checkbox" onclick="quantityChangeHandler(this)"
name="prodid[<?php echo $prodid;?>][]" rel="prodqty_<?php echo $prodid . '_' . $contactid; ?>"
value="<?php echo $contactid; ?>" /><br />
Qty
<select id="prodqty_<?php echo $prodid . '_' . $contactid; ?>"
name="prodqty[<?php echo $prodid; ?>][<?php echo $contactid; ?>]">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
You should add a similar handler and rel attribute to the select tag, and set source.checked based on the value of the select element.
Add this to your Javascript:
function selectChangeHandler(source) {
var checkboxElem = document.getElementById(source.getAttribute('rel'));
checkboxElem.checked = source.value != 0;
}
Example changes to HTML:
<input id="checkbox_0" ... />
...
<select ... rel="checkbox_0" onchange="selectChangeHandler(this)">
...
Working JSFiddle
From my understanding manually trigger the checkbox selection is by triggering the click event.
say you checkbox id = "mychkbox"
then using the jquery you can do by $('#mychkbox').trigger('click');
this makes the check box selected selected.
and your check condition for if checkbox is selected or not.

two select options in javascript

i have two select options but i found little complication between them in the javascript.
here is my javascript code :
function displayVals() {
var singleValues = $("select option:selected").text(); //to stay slected
$("#hiddenselect").val(singleValues); //hidden field of second select option
$("samp").html("" + singleValues); // this to insert text between samp tags
$("select > option:first").prop("disabled", "disabled") // this to disable first option
}
$(document).ready(function(){
$("select").change(function() {
displayVals();
});
displayVals();
$("select#menucompare").change(function() {
$("#aform").submit(); // second select options to submit
});
$("select#infmenu").change(function() {
$("#infform").submit(); // first select options to submit
});
});
now what i expect is :
- only the first select options ( the first option is disabled), need the second select option also (the first option be disabled)
here is my html code
my first select option :
<form action="" id="infform" method="post">
<select id="infmenu" name ="infmenu" size="1" class="select" onchange="submitinfform()" >
<option value="0" >Please Select your country</option>
<option value="<?php echo $row9['id'] ;?>" <?php if ($_SESSION['infmenu'] == $row9['id']) { echo " selected='selected'"; } ?> ><?php echo $row9['name'] ;?></option><?php } ?>
</select>
<input type="hidden" name="hiddenselect" value="<?php echo $infmenu; ?>" />
</form>
this the second select options
<form id="aform" method="post">
<select id="menucompare" name ="menucompare" size="1" class="select" onchange="submitaform()">
<option value="0">Select one</option>
<option value="west" <?php if ($menucompare == "west") { echo " selected='selected'"; } ?> >West</option>
<option value="est" <?php if ($menucompare == "est") { echo " selected='selected'"; } ?> >Est</option>
</select>
<input type="hidden" name="hiddenselect" value="<?php echo $menucompare ; ?>" />
</form>
i have spent on this many days no luck
thanks for your time
Not able to understand you code well. Here is little help for you to try:
To get selected value (value attribute) of the first select element use:
$("#infmenu").val();
To get selected value (value attribute) of the first select element use:
$("#menucompare").val();
To disable first option in first select called "infmenu":
$("option", "#infmenu").first().attr("disabled", "disabled");
To disable first option in second select called "infmenu":
$("option", "#menucompare").first().attr("disabled", "disabled");
To get displayed text of the first select element use:
$("option:selected", "#infmenu").text();
To get displayed text of the second select element use:
$("option:selected", "#menucompare").text();
The jQuery selector that you're using is $("select option:selected"). This means "find all <option> tags that are selected and are children of a <select> element."
You have two <select> elements, so your selector is matching both of them. If you want to match a specific one, you'll need to refine your selector. Since you already have an ID attribute on the second one, try using $("#menucompare option:selected").
Change:
var singleValues = $("select option:selected").text(); //to stay slected
To:
var singleValues = $("#menucompare option:selected").text(); //to stay slected
You want to choose the second select tag. so you have to change your jquery selector in line 2:
var singleValues = $("select:nth-child(2) option:selected").text();

Categories

Resources