jQuery - On Select Option Event - javascript

I am trying to make it so when somebody selects a certain option from my list it will trigger an event. I know you are supposed to use the .change event but that isn't working for me.
Checkout the code below.
Select:
$co1 = array("English", "Math", "Science", "History");
for($c=1;$c<5;$c++){
echo '<select name="c'.$c.'" id="course'.$c.'" class="selectpicker"><option selected="selected" id="course'.$c.'" value="course'.$c.'" name="'.$c.'">Course '.$c.'</option>';
foreach ($co1 as &$cl1){
echo '<option value="'.$cl1.'" name="'.$cl1.'">'.$cl1.'</option>';
}
echo '</select>';
}
jQuery:
<script>
$('#course1').change(function(){
$("#course2 option[value='Math']").each(function() {
$(this).remove();
});
})
</script>
I basically used PHP to make it so there are four different select options with the same options but different values for a grading system. I want to use this script to make it so when you select Math for the first course it will remove it from the list in the other 3 courses.
Any ideas how this would work? I'm up for suggestions on other ways to do this.

Use delegation
$('body').delegate('#course1','change',function(){
$("#course2 option[value='Math']").each(function() {
$(this).remove();
});
})

Try:
$("body").on("change","#course1",function () {
$("#course2").find("option[value='Math']").remove();
});
Fiddle here.

Attribute name and id just for only select tag. Open this link to see standard select option html tag.
If you do that, you have two same id there. <select>, and your first <option>.
try to change your PHP become :
$co1 = array("English", "Math", "Science", "History");
for($c=1;$c<5;$c++){
echo '<select name="c'.$c.'" id="course'.$c.'" class="selectpicker">
<option selected="selected" value="course'.$c.'">Course '.$c.'</option>';
foreach ($co1 as &$cl1){
echo '<option value="'.$cl1.'">'.$cl1.'</option>';
}
echo '</select>';
}

This is the shortest I could come up with:
$('#course1').change(function () {
$('#course2').find('option:gt(0)').remove().end().append($(this).find('option:gt(0)[value!=' + $(this).val() + ']').clone())
})
jsFiddle example

this will hide the option from course2 if same is selected as course1 and show if user selects another one in course1
$('#course1').change(function () {
var val = $(this).val()
if($('#course2').val()==val)
$('#course2').val($('#course2').children('option:first').val())
$("#course2 option").each(function () {
if ($(this).val() == val)
$(this).hide(); //change this line to $(this).remove() to remove permanently
//and remove the else part below
else
$(this).show()
});
})
DEMO
Note that after removing completely you will not be able to show it again hence i will recommend using show and hide on change of course1

I hope I got right what you want to do. Try this fiddle
You could just .hide() the option which matches the current selected and to show the before hidden again just .show() the current :hidden elements?
$('#course1').change(function(){
var sel = $(this).val();
$("#course2 option:hidden").show();
$("#course2 option[value='"+sel+"']").each(function() {
$(this).hide();
});
});

Related

jquery - dynamically changing the option text is not working

Please find the jsfiddle
https://jsfiddle.net/qs008so7/
I have an option box in html and I am trying to set the option using jquery.
But its not working . Please find the code below.
If I call the code in console and I am able to see the expected html is getting returned. Means , the changes are properly affected int he DOM but it is not getting reflected in UI. . You can see my jfiddle .
HTML:
<select class="form-control" name="test" id="test">
<option value="0">Disabled</option>
<option value="1">Enabled</option>
</select>
JS:
setGivenOption(test,"Enabled");
setGivenOption(test,"Disabled");
function setGivenOption(elementId, option) {
//Make all the old selections to null
$(elementId).each(function () {
$('option', this).each(function () {
$(this).attr('selected', null);
});
});
//set the given option
$(elementId).find(">option:contains('" + option + "')").attr("selected", "selected");
}
Thanks.
You where almost there: Try like this https://jsfiddle.net/q5886d5o/1/
Update after #Chips_100 comment
setGivenOption("test","Disabled");
setGivenOption("test","Enabled");
function setGivenOption(elementId, option) {
//Make all the old selections to null
$('#' + elementId).children('option').each(function () {
$(this).attr('selected', null);
});
//set the given option
$('#' + elementId).children("option:contains('" + option + "')").attr("selected", "selected");
}
Simply
$(elementId).find('option:contains(' + option + ')').attr('selected', true);
That will diselect whatever that was selected and select the new option

using the .Change() with dropdownlistFor (want to add the values selected to another div as text)

I'm trying to add the values you select in a dropdownlistfor as text inside an div. Trying to implement this with Jquery, but as I'm totally new to this, I can't seem to get it to work.
Dropdownlistfor code:
<p>
#Html.Label("Departure route:")
#Html.DropDownListFor(m => m.Departureroute, Model.RoutesList, new {#class = "dropdownlist", #id = "departureroute"})
</p>
I have assigned it with an id = departureroute.
Js code
<script type="text/javascript">
$("#departureroute").change(function () {
var str = "";
$("#departureroute option:selected").each(function () {
str += $(this).text() + " ";
});
$("informationcontent-outbound").text(str);
}).change();
</script>
The div i want this text to appear is "informationcontent-outbound"
Hope someone can see what is wrong here.
You just need to use this.value for getting selected value, no need to use each(). Also your div selector is not valid
$("#departureroute").change(function() {
$("#informationcontent-outbound").text(this.value);
//-^--------- if class then use '.'
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id=departureroute>
<option value=1 selected>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<div id="informationcontent-outbound"></div>
Working Demo
depends on the informationcontent-outbound Div
//Using Id Selector
$("#departureroute").change(function () {
$("#informationcontent-outbound").text(this.value);
//If informationcontent-outbound is an Id use above line
$(".informationcontent-outbound").text(this.value);
//If informationcontent-outbound is a class use above line
});
//Using Class Selector
$(".dropdownlist").change(function () {
$("#informationcontent-outbound").text(this.value);
//If informationcontent-outbound is an Id use above line
$(".informationcontent-outbound").text(this.value);
//If informationcontent-outbound is a class use above line
});

js change select name based on option selection

I have a dynamic drop down menu where options are loaded from database, Now i need to change the attribute every time different option is selected from the drop down menu.
To achieve this I am trying to use js in my opinion suitable to do the job but unfortunately I find it difficult and cannot come up with a correct solution, actually i dont know how to start it.
Here is my PHP code that dynamicly generates drop down menu:
$opt = '<select id="Forex" name="" style="display: none">';
$opt1 = '<option value="">Select Forex Workshop</option>';
$opt2 = '';
while($result = mysqli_fetch_assoc($query)){
if($timestamp < $result['endingDate']){
$opt2 .= '<option id="'.$result['id'].'" value="'.$result['startingDate'].'">'.$result['course'].'</option>';
}
}
$opt3 = '</select>';
return $opt.$opt1.$opt2.$opt3;
Could some one suggest a solution a at least give me a link to a article that covers this problem
You can add "onchange" event and change the name whatever you like:
$('#Forex').change(function(){
var val = $(this).val(); // you can get the value of selected option
//you can process your conditions here
$(this).attr('name', 'your_choice_name'); // this will change the name attribute
});
or you can do this from javascript
<select id="Forex" name="abc" onchange="changeAttr(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<script type="text/javascript">
function changeAttr(ele)
{
var val = ele.value;
var n = "";
if(val == 1){
n = 'xyz';
} else if(val == 2){
n = 'abc';
}
ele.setAttribute('name', n);
}
</script>
Hope this will help you what you want...
Use jquery, with a "onChange" event that will change the attribute you want with the selected item in the list.
jQuery get value of select onChange
Hei!
Not sure if I understood you, but you can use jQuery to manipulate attributes on change event.
For event http://api.jquery.com/change/
To change atribute http://api.jquery.com/attr/

How to select option value from select tag using jquery

sorry guys, previously I didn't mention the my dropdown list is made with bootstrap. based on #rps suggestion I asked to my colleague(who is made template) he said it's made with bootstrap.
I am putting basic html dropdown code,so I think you guys can understand How bootstrap code will be.
html code:
<select name="primary" class="select-block" id="select_alert">
<option "selected">Choose Alert T</option>
<option value="T1">T1</option>
<option value="T2">T2</option>
<option value="T3">T3</option>
<option value="T4">T4</option>
</select>
Initially i am getting the select menu in the following way.
for my conformation,I am finding the menu value in the following way.
i/p: document.getElementById('select_alert').value
o/p: "choose Alert T"
Now using javascript or jquery, I want to change select option in the follwoing way.For this I tried the below it's not working
document.getElementById('select_alert').value="T1";
Again If I check the value of select menu,it should be "T1".
Thanks
you can try this
// Get the value from a dropdown select
$( "#select_alert option:selected").val();
$( "#select_alert option:selected" ).text();
My reading of the question is ambiguous, but if you're trying to set the value, or set the selected-option, to T1:
$('#select_alert option[value="T1"]').prop('selected',true);
JS Fiddle demo.
If you're trying to retrieve the value of the selected option:
$('#select_alert option:selected').val();
Using jQuery you can just do this:
$('#select_alert').val('T1');
Demo : Fiddle
use as follows :
$('#select_alert').val('T1'); // in jquery
also your javascript code is correct, there must be some other error on the page.
without jquery you can use
document.getElementById('select_alert').selectedIndex = 1
http://jsfiddle.net/uzqZA/1/
if you want to find out the option index by given value try this
var sel = document.getElementById('select_alert'),
selopt = sel.options,
searchidx;
//alert(selopt[sel.selectedIndex].value);
//sel.selectedIndex = 1;
//alert(selopt[sel.selectedIndex].value);
//alert(sel.value)
// search for the index
searchidx = getoptidx(selopt, "T3");
if (searchidx !== false) {
sel.selectedIndex = searchidx;
alert(selopt[sel.selectedIndex].value);
} else {
alert("index not found")
}
/**
* returns the index of a value
* #todo optimize search?
*/
function getoptidx(opts, searchterm) {
for (var i in opts) {
if (opts[i].text === searchterm) return i;
}
return false;
}
the fiddle: http://jsfiddle.net/uzqZA/6/
Try to do it this way :
$('#select_alert').val("T3");
$("#select_alert").selectmenu();
$("#select_alert").selectmenu("refresh");

Add selected in option using jquery

I am trying to have one of the values in my list selected. I also have a hidden field which I have to match the values in the option of the selection. If it finds one then this has to be selected.
This is the code I have.Hidden field html code.
<input type="hidden" id="supp" name="supp" value="<?php echo $_POST['suppliers'];?>" />
My js:
<script type="text/javascript">
$(document).ready(function() {
var addSelected = $('#supp').val();
$("#suppliers option[value='" + addSelected + "']").attr("selected","selected");
console.log(addSelected);
});
</script>
The code above is not working.
Here's a jsFiddle that shows a better way to do this: http://jsfiddle.net/ATJvv/
You can just call .val on the <select> itself.
try this:
$("#suppliers option").each(function(index, element){
element.selected = element.value === addSelected;
});

Categories

Resources